package com.xxxxxxx.drvpp.fw.batch.controller;

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

import org.apache.ibatis.session.SqlSession;
import org.springframework.context.ApplicationContext;

import com.xxxxxxx.drvpp.fw.batch.util.BatchParameter;
import com.xxxxxxx.drvpp.fw.batch.util.Business;
import com.xxxxxxx.drvpp.fw.common.log.Logger;
import com.xxxxxxx.drvpp.fw.common.log.LoggerFactory;
import com.xxxxxxx.drvpp.fw.common.log.LoggerFactoryBuilder;
import com.xxxxxxx.drvpp.fw.common.mybatis.MyBatisSessionFactory;
import com.xxxxxxx.drvpp.fw.common.util.BeanFactoryBuilder;

public class ApplicationControllerImpl implements ApplicationController {
    public int doExecute(String[] args) {
    	// ロガー取得
    	LoggerFactoryBuilder loggerFactoryBuilder = LoggerFactoryBuilder.getInstance();
    	LoggerFactory loggerFactory = loggerFactoryBuilder.getLoggerFactory();
    	Logger logger = loggerFactory.getLogger(this.getClass());
    	
		// DBセッション取得
		MyBatisSessionFactory sessionFactory = MyBatisSessionFactory.getInstance();
		SqlSession sqlSession = sessionFactory.openSession();
		
		// アプリケーションコンテキスト取得(Beanの生成に使用)
		BeanFactoryBuilder builder = BeanFactoryBuilder.getInstance();
		ApplicationContext applicationContext = builder.build();

		// フローの決定
		List<Business> flow = (List<Business>)applicationContext.getBean("businessList");

		// 実行
		BatchParameter parameter = null;
		for (Business b : flow){
			// パラメータ設定
			parameter = new BatchParameter();
			parameter.setSqlSession(sqlSession);
			Map<String, Object> input = new HashMap<String, Object>();
			Map<String, Object> output = new HashMap<String, Object>();
			parameter.setInput(input);
			parameter.setOutput(output);
//			parameter.setRequestParameter(requestParameter);
//			parameter.setRequest(request);
//			parameter.setModel(model);
//			parameter.setViewName("error");
			parameter.setArgs(args);
			int result = -1;
			try {
				// ビジネスロジック起動
				result = b.doExecute(parameter);
				
				input.clear();
				input.putAll(output);
				output.clear();
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				// 起動後処理
				if (result != 0){
					sqlSession.rollback();
					break;				
				}
				sqlSession.commit();
			}
		}
		
//    	return parameter.getViewName();
		return 0; // TODO
    }
}
