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.TaskReportSendDto;
import jp.agentec.adf.util.DateTimeFormat;
import jp.agentec.adf.util.DateTimeUtil;
import jp.agentec.adf.util.StringUtil;

/**
 * Created by seo-y on 2018/11/26.
 */

public class TaskReportSendDao extends AbstractDao {
    private static final String TAG = "TaskReportSendDao";

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

        int column = cursor.getColumnIndex("task_report_send_id");
        if (column != -1) {
            dto.taskReportSendId = cursor.getInt(column);
        }

        column = cursor.getColumnIndex("task_key");
        if (column != -1) {
            dto.taskKey = cursor.getString(column);
        }

        column = cursor.getColumnIndex("task_report_info_id");
        if (column != -1) {
            dto.taskReportId = cursor.getInt(column);
        }

        column = cursor.getColumnIndex("report_start_date");
        if (column != -1) {
            dto.reportStartDate = cursor.getString(column);
        }

        column = cursor.getColumnIndex("json_data");
        if (column != -1) {
            dto.jsonData = cursor.getString(column);
        }

        column = cursor.getColumnIndex("save_date");
        if (column != -1) {
            dto.saveDate = DateTimeUtil.toDate(cursor.getString(column), "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
        }

        column = cursor.getColumnIndex("delete_flg");
        if (column != -1) {
            dto.deleteFlg = toBool(cursor.getInt(column));
        }

        column = cursor.getColumnIndex("hotspot_changed_flg");
        if (column != -1) {
            dto.hotspotChangeFlg = toBool(cursor.getInt(column));
        }

        return dto;
    }

    public int getNewTaskReportSendId() {
        return rawQueryGetInt("select ifnull(max(task_report_send_id),0) + 1 from t_task_report_send", null);
    }

    public int getLastTaskReportSendId(String taskKey) {
        return rawQueryGetInt("select ifnull(max(task_report_send_id),0) from t_task_report_send where task_key = ?", new String[]{ taskKey });
    }

    public int getLastTaskReportSendId(String taskKey, int taskReportId, String reportStartDate) {
        return rawQueryGetInt("select ifnull(max(task_report_send_id),0) from t_task_report_send where task_key = ? and task_report_id = ? and report_start_date = ?", new String[]{ taskKey, "" + taskReportId, reportStartDate });
    }

    /**
     * 最新の送信データを取得
     * @param taskKey
     * @return
     */
    public TaskReportSendDto getLastTaskReportSend(String taskKey) {
        int lastSendId = getLastTaskReportSendId(taskKey);
        StringBuilder sb = new StringBuilder();
        sb.append(" select * ");
        sb.append(" from t_task_report_send ");
        sb.append(" where task_report_send_id = ? ");
        sb.append(" order by task_report_send_id asc");
        return rawQueryGetDto(sb.toString(), new String[]{ "" + lastSendId }, TaskReportSendDto.class);
    }

    public int insert(TaskReportSendDto dto) {
        dto.taskReportSendId = getNewTaskReportSendId();

        insert("insert into t_task_report_send "
                        + "(task_report_send_id, "
                        + "task_key, "
                        + "task_report_id, "
                        + "report_start_date, "
                        + "json_data, "
                        + "save_date, "
                        + "hotspot_changed_flg, "
                        + "delete_flg) "
                        + "values "
                        + "(?,?,?,?,?,?,?,?)",
                dto.getInsertValues());

        return dto.taskReportSendId;
    }

    public int update(TaskReportSendDto dto) {
        if (dto.taskReportId > 0 && dto.reportStartDate != null) {
            dto.taskReportSendId = getLastTaskReportSendId(dto.taskKey, dto.taskReportId, dto.reportStartDate);
        } else {
            dto.taskReportSendId = getLastTaskReportSendId(dto.taskKey);
        }
        long count = update("update t_task_report_send "
                        + "set "
                        + "json_data=?, "
                        + "save_date=?, "
                        + "hotspot_changed_flg=?, "
                        + "delete_flg=? "
                        + "where task_report_send_id = ?",
                dto.getUpdateValues());
        return count > 0 ? dto.taskReportSendId : 0;
    }

    public boolean deleteBySendId(int sendId) {
        String[] keyValues = new String[]{""+ sendId};
        long count = delete("t_task_report_send", "task_report_send_id=?", keyValues);
        return count > 0;
    }

    public boolean deleteByTaskKeyIdDate(String taskKey, int taskReportId, String reportStartDate) {
        String[] keyValues = new String[]{ taskKey, "" + taskReportId, reportStartDate };
        long count = delete("t_task_report_send", "task_key=? and task_report_id = ? and report_start_date = ?", keyValues);
        return count > 0;
    }

    public void deleteAll() {
        delete("t_task_report_send", null, null);
    }

    public List<TaskReportSendDto> getSendableTaskReportSendData(String taskKey) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select * ");
        sb.append(" from t_task_report_send ");
        sb.append(" where task_key = ? ");
        sb.append(" order by task_report_send_id asc");
        return rawQueryGetDtoList(sb.toString(), new String[]{ taskKey }, TaskReportSendDto.class);
    }

    /**
     * 送信可能なデータが存在するかチェック
     * @param taskKey
     * @return
     */
    public boolean isNotExistSendableData(String taskKey) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select count(task_report_send_id) ");
        sb.append(" from t_task_report_send ");
        sb.append(" where task_key = ? ");
        sb.append(" AND hotspot_changed_flg = 0");
        sb.append(" order by task_report_send_id asc");
        return rawQueryGetInt(sb.toString(), new String[]{ taskKey }) == 0;
    }

    /**
     * ホットスポット更新フラグが存在するかチェック
     * @param taskKey
     * @return
     */
    public TaskReportSendDto getHotspotChangedData(String taskKey) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select * ");
        sb.append(" from t_task_report_send ");
        sb.append(" where hotspot_changed_flg = 1 ");
        sb.append(" AND task_key = ?");
        sb.append(" order by task_report_send_id asc");
        return rawQueryGetDto(sb.toString(), new String[]{ taskKey }, TaskReportSendDto.class);
    }

    public List<TaskReportSendDto> getSendableTaskReportSendData(String taskKey, int taskReportId, String reportStartDate) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select * ");
        sb.append(" from t_task_report_send ");
        sb.append(" where task_key = ? and task_report_id = ? and report_start_date = ?");
        sb.append(" order by task_report_send_id asc");
        return rawQueryGetDtoList(sb.toString(), new String[]{ taskKey, "" + taskReportId, reportStartDate }, TaskReportSendDto.class);
    }

    public int getSendableTaskReportSendDataCount(Long operationId, String taskKey) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select count(ttrs.task_report_send_id) ");
        sb.append(" from t_task_report_send ttrs ");
        sb.append(" inner join ");
        sb.append("     t_task tt ");
        sb.append("         ON tt.task_key == ttrs.task_key ");
        sb.append("         AND tt.operation_id = ?");
        if (taskKey != null) {
            sb.append("         AND ttrs.task_key = ?");
            return rawQueryGetInt(sb.toString(), new String[]{ "" + operationId, "" + taskKey });
        }
        return rawQueryGetInt(sb.toString(), new String[]{ "" + operationId });
    }

    public int getSendableTaskReportSendDataCount(Long operationId, String taskKey, int taskReportId, String reportStartDate) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select count(ttrs.task_report_send_id) ");
        sb.append(" from t_task_report_send ttrs ");
        sb.append(" inner join ");
        sb.append("     t_task tt ");
        sb.append("         ON tt.task_key == ttrs.task_key ");
        sb.append("         AND tt.operation_id = ?");
        if (!StringUtil.isNullOrEmpty(taskKey) && taskReportId > 0 && !StringUtil.isNullOrEmpty(reportStartDate)) {
            sb.append("         AND ttrs.task_key = ? and task_report_id = ? and report_start_date = ?");
            return rawQueryGetInt(sb.toString(), new String[]{ "" + operationId, taskKey, "" + taskReportId, reportStartDate });
        }
        return rawQueryGetInt(sb.toString(), new String[]{ "" + operationId });
    }

    /**
     * ホットスポット更新フラグが存在すれば、削除
     * @param taskKey
     * @return
     */
    public boolean deleteHotspotChangedData(String taskKey) {
        TaskReportSendDto hotspotChangedData = getHotspotChangedData(taskKey);
        if (hotspotChangedData != null) {
            return deleteBySendId(hotspotChangedData.taskReportSendId);
        }
        return false;
    }
}
