package batch.status;

import java.sql.Connection;
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
 */
public class JobMasterInfoImpl implements JobMasterInfo {

	/**
	 * ジョブ情報取得
	 *
	 * @param conn コネクション
	 * @param jobid ジョブID
	 * @return ジョブ情報
	 */
	@Override
	public JobMaster getJobMasterInfo(final Connection conn, final String jobid) {
		final var query = QueryUtil.getSqlFromFile("SelectJobInfo", this.getClass());
		try (var psmt = QueryUtil.createStatement(query, Collections.singletonMap("JobId", jobid),
				Jdbc.wrap(conn)::readonlyStatement)) {
			JobMaster ret = null;
			try (var 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) {
		final var query = QueryUtil.getSqlFromFile("SelectJobInfoList", this.getClass());
		try (var psmt = Jdbc.wrap(conn).readonlyStatement(query)) {
			final var ret = new ArrayList<JobMaster>();
			try (var 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 {
		final var 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;
	}
}
