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

import jp.agentec.abook.abv.bl.acms.type.DownloadStatusType;
import jp.agentec.abook.abv.bl.common.db.Cursor;
import jp.agentec.abook.abv.bl.dto.ContentDownloadQueueDto;
import jp.agentec.adf.util.DateTimeFormat;
import jp.agentec.adf.util.DateTimeUtil;

/**
 *  * TODO: ContentDtoに統合したのでいずれかの段階で削除
 * @author Taejin Hong
 * @version 1.1.1
 */
public class ContentDownloadQueueDao extends AbstractDao {
	
	/*package*/ ContentDownloadQueueDao() {
	}

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

		int column = cursor.getColumnIndex("content_id");
		if (column != -1) {
			dto.contentId = cursor.getLong(column);
		}
		column = cursor.getColumnIndex("resource_version");
		if (column != -1) {
			dto.resourceVersion = cursor.getInt(column);
		}
		column = cursor.getColumnIndex("status");
		if (column != -1) {
			dto.status = cursor.getString(column);
		}
//		colnum = cursor.getColumnIndex("display_status");
//		if (colnum != -1) {
//			dto.displayStatus = cursor.getString(colnum);
//		}
//		colnum = cursor.getColumnIndex("message_code");
//		if (colnum != -1) {
//			dto.messageCode = cursor.getString(colnum);
//		}
//		colnum = cursor.getColumnIndex("queued_date");
//		if (colnum != -1) {
//			dto.queuedDate = DateTimeUtil.toDate(cursor.getString(colnum), "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
//		}
		column = cursor.getColumnIndex("start_date");
		if (column != -1) {
			dto.startDate = DateTimeUtil.toDate(cursor.getString(column), "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
		}
//		colnum = cursor.getColumnIndex("download_avg_bps");
//		if (colnum != -1) {
//			dto.downloadAvgBps = cursor.getDouble(colnum);
//		}
		column = cursor.getColumnIndex("download_progress");
		if (column != -1) {
			dto.downloadProgress = cursor.getInt(column);
		}
		column = cursor.getColumnIndex("resource_downloaded_bytes");
		if (column != -1) {
			dto.resourceDownloadedBytes = cursor.getLong(column);
		}
//		colnum = cursor.getColumnIndex("resource_downloaded_file_path");
//		if (colnum != -1) {
//			dto.resourceDownloadedFilePath = cursor.getString(colnum);
//		}
//		colnum = cursor.getColumnIndex("resource_download_end_date");
//		if (colnum != -1) {
//			dto.resourceDownloadEndDate = DateTimeUtil.toDate(cursor.getString(colnum), "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
//		}
//		colnum = cursor.getColumnIndex("resource_extract_end_date");
//		if (colnum != -1) {
//			dto.resourceExtractEndDate = DateTimeUtil.toDate(cursor.getString(colnum), "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
//		}
		column = cursor.getColumnIndex("end_date");
		if (column != -1) {
			dto.endDate = DateTimeUtil.toDate(cursor.getString(column), "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
		}
		column = cursor.getColumnIndex("log_sended_flg");
		if (column != -1) {
			dto.logSendedFlg = toBool(cursor.getInt(column));
		}

//		colnum = cursor.getColumnIndex("content_name");
//		if (colnum != -1) {
//			dto.contentName = cursor.getString(colnum);
//		}
//		colnum = cursor.getColumnIndex("content_detail");
//		if (colnum != -1) {
//			dto.contentDetail = cursor.getString(colnum);
//		}
//		colnum = cursor.getColumnIndex("thumbnail_normal_path");
//		if (colnum != -1) {
//			dto.thumbnailNormalPath = cursor.getString(colnum);
//		}

		return dto;
	}

//	public ContentDownloadQueueDto getQueue(long contentId) {
//		return rawQueryGetDto("select * from t_content_download_queue where content_id=?", new String[] {""+ contentId}, ContentDownloadQueueDto.class);
//	}

	/**
	 * コンテンツのダウンロード状況を確認します。コンテンツ個別のダウンロード状況の変化は、Observerを通じて通知されますが、全体の状況を纏めて取得したい場合はこのメソッドを利用します。<br>
	 * ダウンロード状況画面の初期化などが当てはまります。
	 * @return {@link ContentDownloadQueueDto}のリストを返します。
	 * @since 1.0.0
	 */
//	public List<ContentDownloadQueueDto> getUnfinishedQueue() {
//		return rawQueryGetDtoList(generateUnfinishedQueueQuery(), null, ContentDownloadQueueDto.class);
//	}

	private String generateUnfinishedQueueQuery() {
		StringBuffer sql = new StringBuffer();

		sql.append(" SELECT tcdq.content_id ");
		sql.append("      , tc.content_name ");
		sql.append("      , tc.content_detail ");
		sql.append("      , tc.thumbnail_normal_path ");
		sql.append("      , tcdq.status ");
		sql.append("      , tcdq.display_status ");
		sql.append("      , tcdq.queued_date ");
		sql.append("      , tcdq.start_date ");
		sql.append("      , tcdq.download_avg_bps ");
		sql.append("      , tcdq.download_progress ");
		sql.append("      , tcdq.resource_downloaded_bytes ");
		sql.append("      , tcdq.resource_downloaded_file_path ");
		sql.append("      , tcdq.resource_download_end_date ");
		sql.append("      , tcdq.image_downloaded_bytes ");
		sql.append("      , tcdq.image_download_end_date ");
		sql.append("      , tcdq.resource_extract_end_date ");
		sql.append("      , tcdq.image_extract_end_date ");
		sql.append("      , tcdq.end_date ");
		sql.append("      , tcdq.message_code ");
		sql.append("   FROM t_content_download_queue AS tcdq ");
		sql.append("  INNER JOIN t_content AS tc ");
		sql.append("     ON tcdq.content_id = tc.content_id ");
		sql.append("  WHERE tcdq.status IN ('%s', '%s', '%s', '%s', '%s') ");
		sql.append("  ORDER BY tcdq.queued_date ");

		return String.format(sql.toString(), DownloadStatusType.Waiting.type()
				, DownloadStatusType.Downloading.type()
				, DownloadStatusType.Paused.type()
				, DownloadStatusType.Initializing.type(), DownloadStatusType.Failed.type());
	}

	/**
	 * DBにダウンロード状態の更新ができず、プロセスが落ちた場合もあり得る。
	 * プロセスを再起動すると、ダウンロードの再開や失敗処理ができるように、待機状態だけでなく、完了・失敗・キャンセル以外は全部取得します。
	 * @see jp.agentec.abook.abv.core.data.dao.IContentDonwloadQueue#getWaitingQueue(java.lang.Class)
	 * @since 1.0.0
	 */

//	public List<ContentDownloadQueueDto> getWaitingQueue(int queueCount) {
//		String selection = String.format("status IN ('%s', '%s')" 
//				, DownloadStatusType.WaitingResource.type() 
//				, DownloadStatusType.DownloadingResource.type());
//
//		return rawQueryGetDtoList("select * from t_content_download_queue where " + selection + " order by status, queued_date limit " + queueCount, null, ContentDownloadQueueDto.class);
//	}

	/**
	 * このメソッドは、アプリ起動時の１回のみ呼び出してください。
	 * @since 1.1.1
	 */
//	public void cleanErrorQueue() {
//		try {
//			beginTransaction();
//			StringBuffer sql = new StringBuffer();
//
//			sql.append(" UPDATE t_content_download_queue ");
//			sql.append("    SET display_status = status ");
//			sql.append("  WHERE display_status = '" + DownloadStatusType.Initializing.type() + "'");
//
//			execSql(sql.toString());
//
//			update("update t_content_download_queue set status=? where status=?", new Object[]{DownloadStatusType.WaitingResource.type(), DownloadStatusType.Initializing.type()});
//			commit();
//		} catch (Exception e) {
//			Logger.w("clenaErrorQueue failed.", e);
//			rollback();
//			throw new RuntimeException(e);
//		}
//	}

//	public DownloadStatusType getDownloadStatus(long contentId) {
//		DownloadStatusType status = null;
//
//		String ret = rawQueryGetString("select status from t_content_download_queue where content_id=?", new String[]{""+ contentId});
//		if (!StringUtil.isNullOrWhiteSpace(ret)) {
//			status = DownloadStatusType.parse(ret);
//		}
//
//		return status;
//	}


//	public List<ContentDownloadQueueDto> getSendLogQueue() {
//		return rawQueryGetDtoList("select * from t_content_download_queue where end_date IS NOT NULL AND (log_sended_flg = 0 OR log_sended_flg IS NULL)", null, ContentDownloadQueueDto.class);
//	}

//	public void insertQueue(ContentDownloadQueueDto dto) {
//		insert("insert into t_content_download_queue (content_id, resource_version, status, display_status, message_code, queued_date, start_date, download_avg_bps, download_progress, resource_downloaded_bytes, resource_downloaded_file_path, resource_download_end_date, resource_extract_end_date, end_date, log_sended_flg) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", dto.getInsertValues());
//	}

//	public boolean updateQueue(ContentDownloadQueueDto dto) {
//		long ret = update("update t_content_download_queue set resource_version=?, status=?, display_status=?, message_code=?, queued_date=?, start_date=?, download_avg_bps=?, download_progress=?, resource_downloaded_bytes=?, resource_downloaded_file_path=?, resource_download_end_date=?, resource_extract_end_date=?, end_date=?, log_sended_flg=? where content_id=?", dto.getUpdateValues());
//		return ret > 0;
//	}

//	public boolean updateQueue(long contentId, DownloadStatusType status) {
//		long ret = update("update t_content_download_queue set status=?, display_status=? where content_id=?", new Object[]{status.type(), status.type(), contentId});
//		return ret > 0;
//	}
}
