package jp.terasoluna.batch.functionsample.b001;

import jp.terasoluna.fw.batch.blogic.BLogic;
import jp.terasoluna.fw.batch.blogic.vo.BLogicParam;
import jp.terasoluna.fw.batch.util.BatchUtil;
import jp.terasoluna.fw.dao.QueryDAO;
import jp.terasoluna.fw.dao.UpdateDAO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;

/**
 * DB関連ジョブのサンプル<br>
 * <br>
 * 
 * 事前準備：EMPLOYEEテーブルを作成しておくこと<br>
 * <br>
 * サンプル内容：参照・更新処理を行う。トランザクション管理はビジネスロジック内で制御するサンプル。
 */
public class B001002BLogic implements BLogic {

	private Log log = LogFactory.getLog(B001002BLogic.class);

	private static final int BATCH_NORMAL_END = 0;

	@Autowired
	@Qualifier("queryDAO")
	private QueryDAO queryDAO = null;

	@Autowired
	@Qualifier("updateDAO")
	private UpdateDAO updateDAO = null;

	@Autowired
	@Qualifier("transactionManager")
	private PlatformTransactionManager transactionManager = null;

	public int execute(BLogicParam arg0) {

		TransactionStatus stat = null;

		try {
			stat = BatchUtil.startTransaction(transactionManager);

			int count = queryDAO.executeForObject(
					"B001002.selectEmployeeCount", null, Integer.class);

			B001002Param newUser = new B001002Param();

			newUser.setId(count + 1);
			newUser.setFamilyName("山田");
			newUser.setFirstName("次郎");
			newUser.setAge(45);

			updateDAO.execute("B001002.insertEmployee", newUser);

			BatchUtil.commitTransaction(transactionManager, stat);

			log.info("以下のユーザをEMPLOYEEテーブルに追加しました");
			log.info("id : " + newUser.getId() + " familyName : "
					+ newUser.getFamilyName() + " firstName : "
					+ newUser.getFirstName() + " age : " + newUser.getAge());

		} finally {
			BatchUtil.endTransaction(transactionManager, stat);
		}

		return BATCH_NORMAL_END;

	}

}
