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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class WorkingReportDao extends AbstractDao {

    @Override
    protected WorkingReportDto convert(Cursor cursor) {
        return new WorkingReportDto(
                getLongOrNull(cursor, "operation_id"),
                getIntOrNull(cursor, "count")
        );
    }

    private Long getLongOrNull(Cursor cursor, String name) {
        int column = cursor.getColumnIndex(name);
        if (column < 0) {
            return null;
        } else {
            return cursor.getLong(column);
        }
    }

    private Integer getIntOrNull(Cursor cursor, String name) {
        int column = cursor.getColumnIndex(name);
        if (column < 0) {
            return null;
        } else {
            return cursor.getInt(column);
        }
    }

    public Map<Long, Integer> getWorkingTaskReportCounts() {
        StringBuilder sql = new StringBuilder();

        sql.append(" SELECT t_operation.operation_id AS operation_id, count(*) AS count  FROM t_task_report ");
        sql.append(" INNER JOIN t_task ON t_task_report.task_key = t_task.task_key ");
        sql.append(" INNER JOIN t_operation ON t_task.operation_id = t_operation.operation_id");
        sql.append(" WHERE t_task_report.local_saved_flg > 0");
        sql.append(" GROUP BY t_operation.operation_id");

        List<WorkingReportDto> list = rawQueryGetDtoList(sql.toString(), null, WorkingReportDto.class);

        Map<Long, Integer> map = new HashMap<Long, Integer>();

        for (WorkingReportDto dto : list) {
            Long id = dto.getOperationId();
            Integer cnt = dto.getCount();
            if (id != null && cnt != null) {
                map.put(id, cnt);
            }
        }
        return map;
    }
}
