package batch.status;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import common.db.jdbc.Jdbc;
import common.sql.QueryUtil;
import core.exception.PhysicalException;
import core.exception.ThrowableUtil;

/**
 * ジョブ管理マスタクラス
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class JobMasterInfoImpl implements JobMasterInfo {

	/**
	 * ジョブ情報取得
	 *
	 * @param conn コネクション
	 * @param jobid ジョブID
	 * @return ジョブ情報
	 */
	@Override
	public JobMaster getJobMasterInfo(final Connection conn, final String jobid) {
		String query = QueryUtil.getSqlFromFile("SelectJobInfo", this.getClass());
		try (PreparedStatement psmt = QueryUtil.createStatement(
				query, Collections.singletonMap("JobId", jobid),
				Jdbc.wrap(conn)::readonlyStatement)) {
			JobMaster ret = null;
			try (ResultSet rs = psmt.executeQuery()) {
				if (rs.next()) {
					ret = toJobMasterObject(rs);
				}
			}
			return ret;

		} catch (final SQLException ex) {
			ThrowableUtil.error(ex);
			throw new PhysicalException(ex);
		}
	}

	/**
	 * ジョブ管理マスタ取得
	 *
	 * @param conn コネクション
	 * @return マスタリスト
	 */
	@Override
	public List<JobMaster> getJobMasterInfoAll(final Connection conn) {
		String query = QueryUtil.getSqlFromFile("SelectJobInfoList", this.getClass());
		try (PreparedStatement psmt = Jdbc.wrap(conn).readonlyStatement(query)) {
			List<JobMaster> ret = new ArrayList<>();
			try (ResultSet rs = psmt.executeQuery()) {
				while (rs.next()) {
					ret.add(toJobMasterObject(rs));
				}
			}
			return ret;
		} catch (final SQLException ex) {
			ThrowableUtil.error(ex);
			throw new PhysicalException(ex);
		}
	}

	/**
	 * ジョブ情報オブジェクト取得
	 *
	 * @param rs 結果セット
	 * @return ジョブ情報オブジェクト
	 * @throws SQLException SQL例外
	 */
	private JobMaster toJobMasterObject(final ResultSet rs) throws SQLException {
		JobMaster ret = new JobMaster();
		ret.setJobId(rs.getString("JOB_ID"));
		ret.setMultiplicity(rs.getInt("MULTIPLICITY"));
		ret.setCancelType(rs.getString("CANCEL_TYPE"));
		ret.setRunnableBegin(rs.getString("RUNNABLE_BEGIN_HHMM"));
		ret.setRunnableEnd(rs.getString("RUNNABLE_END_HHMM"));
		return ret;
	}
}
