package jp.agentec.abook.abv.bl.data.dao;

import java.util.List;

import jp.agentec.abook.abv.bl.common.db.Cursor;
import jp.agentec.abook.abv.bl.dto.ContentPageDto;

public class ContentPageDao extends AbstractDao {

	/*package*/ ContentPageDao() {
	}

	@Override
	protected ContentPageDto convert(Cursor cursor) {
		ContentPageDto dto = new ContentPageDto();

		int colnum = cursor.getColumnIndex("content_id");
		if (colnum != -1) {
			dto.contentId = cursor.getLong(colnum);
		}
		colnum = cursor.getColumnIndex("page_num");
		if (colnum != -1) {
			dto.pageNum = cursor.getInt(colnum);
		}
		colnum = cursor.getColumnIndex("page_text");
		if (colnum != -1) {
			dto.pageText = cursor.getString(colnum);
		}
		colnum = cursor.getColumnIndex("page_thumbnail_name");
		if (colnum != -1) {
			dto.pageThumbnailName = cursor.getString(colnum);
		}

		return dto;
	}

	public List<ContentPageDto> getContentPages(long contentId) {
		return rawQueryGetDtoList("select * from t_content_page where content_id=? order by page_num", new String[]{""+ contentId}, ContentPageDto.class);
	}

	public List<ContentPageDto> getContentPages(long contentId, String searchKeyword) {
		return rawQueryGetDtoList(generateGetPageQuery(""+ contentId, searchKeyword), new String[]{""+ contentId, "%" + searchKeyword + "%"}, ContentPageDto.class);
	}

	private String generateGetPageQuery(String contentId , String searchKeyword) {
		StringBuffer sql = new StringBuffer();

		sql.append(" SELECT tcp.content_id AS content_id ");
		sql.append(" , tcp.page_num AS page_num  ");
		sql.append(" , tcp.page_text AS page_text ");
		sql.append(" , tcp.page_thumbnail_name AS page_thumbnail_name ");
		sql.append(" , tcp.hashed_thumbnail_header AS hashed_thumbnail_header ");
		sql.append(" FROM t_content_page  AS tcp ");

		if (contentId != null && searchKeyword != null) {
			sql.append("WHERE tcp.content_id = ?  AND tcp.page_text LIKE ? ");
		}else //noinspection VariableNotUsedInsideIf
			if (contentId != null) {
			sql.append("WHERE tcp.content_id = ?  ");
		}

		sql.append(" ORDER BY tcp.page_num  ");
		return sql.toString();
	}

	public String getContentPageText(long contentId,int pageNum) {
		return rawQueryGetString("select page_text from t_content_page where content_id=? AND page_num=?", new String[]{""+contentId,""+ pageNum});	}

	public void insertContentPages(ContentPageDto dto) {
		insert("insert into t_content_page (content_id, page_num, page_text, page_thumbnail_name) values (?,?,?,?)", dto.getInsertValues());
	}

	public void deleteContentPage(long contentId) {
		delete("t_content_page", "content_id=?", new String[]{""+ contentId});
	}

	public void deleteContentPage(long contentId, int pageNum) {
		delete("t_content_page", "content_id=? AND page_num=?", new String[]{""+ contentId, ""+ pageNum});
	}

}