package jp.terasoluna.batch.functionsample.b001;

import java.util.Random;

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.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>
 * サンプル内容：100件毎にコミットするサンプル。
 * 
 * 
 */
public class B001003BLogic implements BLogic {

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

	private static final int BATCH_NORMAL_END = 0;

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

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

	public int execute(BLogicParam arg0) {

		Random rnd = new Random();

		TransactionStatus stat = null;
		int max_count = 1000;
		int commitTimes = 100;

		if (arg0 != null && arg0.getJobArgNm1() != null) {
			max_count = Integer.parseInt(arg0.getJobArgNm1());
		}

		if (arg0 != null && arg0.getJobArgNm2() != null) {
			commitTimes = Integer.parseInt(arg0.getJobArgNm2());
		}

		try {
			stat = BatchUtil.startTransaction(transactionManager);

			int count = updateDAO.execute("B001003.deleteEmployee", null);

			log.info("削除したレコード数:" + count);
			
			for (int i = 1; i <= max_count; i++) {

				B001003Param newUser = new B001003Param();

				newUser.setId(i);
				newUser.setFamilyName("木村");
				newUser.setFirstName("太郎");
				newUser.setAge(rnd.nextInt(99) + 1);

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

				if (i % commitTimes == 0) {
					BatchUtil.commitTransaction(transactionManager, stat);
					log.info(i + "件コミット完了");
					stat = BatchUtil.startTransaction(transactionManager);
				}
			}

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

}
