package com.eactive.eai.rms.onl.statistics.backup.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.onl.common.util.DateUtil;
import com.eactive.eai.rms.onl.statistics.backup.AlreadyBackupException;
import com.eactive.eai.rms.onl.statistics.backup.BackupException;
import com.eactive.eai.rms.onl.statistics.backup.dao.MonthlyBackupDAO;
import com.eactive.eai.rms.onl.statistics.backup.dao.Tseaist01DAO;
import com.eactive.eai.rms.onl.statistics.backup.vo.Tseaist01VO;

/**
 * <pre>
 * 1. 기능 : Daily Backup의 비즈니스 로직이 담겨져 있다.
 * 2. 처리 개요 : 
 *     - 
 * 3. 주의사항 : 
 * </pre>
 * @author  : 박기섭
 * @version : $Revision: 1.5 $
 * @since : rts 1.0
 */
@Service("monthlyBackupService")
public class MonthlyBackupService extends BaseService{

    /**
     * Logger for this class
     */
	private static final Logger logger = Logger.getLogger(MonthlyBackupService.class);

    private static final String STATC_JOB_CYCL_DSTCD = "M";
    private static final String BACKUP_SUCCESS = "1";
    private static final String BACKUP_FAIL = "0";

    @Autowired
    @Qualifier("monthlyBackupDAO")
    private MonthlyBackupDAO dao = null;
    
    @Autowired
    @Qualifier("tseaist01DAO")
    private Tseaist01DAO tseaist01DAO = null;
    
    @Autowired
    private BackupResultService backupResultService;
    
    public void doAction(final String date){
		doAction(date, null);
    }
    
    public void doAction(final String date, final String serviceType){
    	//self 로 하는 이유는 proxy를 설정해서 transaction을 삽입하기 위해서
    	//datasource는 transaction이 시작하면 바꿀수 없음.
    	MonthlyBackupService self =(MonthlyBackupService)appContext.getBean("monthlyBackupService");  	
    	if (logger.isInfoEnabled()){
    		logger.info("Monthly Backup Begin date="+date +" serviceType="+serviceType);
    	}
    	if(serviceType == null)
    	{
    		for (DataSourceType dataSourceType : DataSourceTypeManager.getOnlineDataSourceTypes())
    		{
    			if(DataSourceTypeManager.APIGW.equals(dataSourceType.getName())) {	  		
	    			DataSourceContextHolder.setDataSourceType(dataSourceType);
	    			self.backup(date);
    			}
	    	}
    	}
    	else
    	{
    		DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(serviceType);
    		DataSourceContextHolder.setDataSourceType(dataSourceType);
    		self.backup(date);
    	}
    	if (logger.isInfoEnabled()){
    		logger.info("Monthly Backup Begin date="+date +" serviceType="+serviceType);
    	}
    }
    public void doDelete(final String date, final String serviceType) throws Exception{
    	if(serviceType == null){
    		throw new Exception("서비스 타입 코드가 존재하지 않습니다.");
    	}

    	if (logger.isInfoEnabled()){
    		logger.info("Monthly Backup Delete Begin date="+date +" serviceType="+serviceType);
    	}
    	String month = date.substring(0,6);
    	String month00 = month+"00";
    	
    	
		DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(serviceType);
		DataSourceContextHolder.setDataSourceType(dataSourceType);
		tseaist01DAO.deleteTseaist01(month00, STATC_JOB_CYCL_DSTCD);
		dao.deleteMonthlyData(month);
    	if (logger.isInfoEnabled()){
    		logger.info("Monthly Backup Delete Begin date="+date +" serviceType="+serviceType);
    	}
    }

    public void backup(String date ){
    	
        String sucssYn = BACKUP_FAIL;
        String errMsg = "";
        String statcJobCyclDstcd = STATC_JOB_CYCL_DSTCD;
        String statcJobStartHMS = DateUtil.getDateTimeMilliSecound();
        String year = date.substring(0, 4);
        String month = date.substring(0, 6);
        String backupDate = month + "00";

        try {
        	//String schemaId = dataSourceType.getSchema();
            List list = dao.findMonthlyTseaist03(month);
            if (list == null || list.size() < 1) {
                throw new BackupException("백업할 데이터가 없습니다.");
            }

            Tseaist01VO tseaist01VO = findTseaiSt01(backupDate,statcJobCyclDstcd);

            if (tseaist01VO == null) {
            	// 백업로그 생성
            	backupResultService.requiresNewInsertBackupResult(backupDate, statcJobCyclDstcd, statcJobStartHMS, " ", " ", " ");
                
                dao.insertMonthlyBackupData(list);
                List yearList = dao.findYearlyTseaist04(year);
                dao.insertYearlyBackupData(yearList, year);

                sucssYn = BACKUP_SUCCESS;
                errMsg = "정상";
            } else if (BACKUP_FAIL.equals(tseaist01VO.getSucssYn())) {
                dao.insertMonthlyBackupData(list);
                List yearList = dao.findYearlyTseaist04(year);
                dao.insertYearlyBackupData(yearList, year);
                sucssYn = BACKUP_SUCCESS;
                errMsg = "정상";
            } else {
            	logger.info("백업 진행을 중단합니다.");
            	return;
            }
        } catch (AlreadyBackupException e) {
            sucssYn = BACKUP_SUCCESS;
            errMsg = StringUtils.cutting(e.getMessage(), 2000, "");
        } catch (BackupException e) { // 백업할 데이터가 없습니다.
            sucssYn = BACKUP_SUCCESS;
            errMsg = StringUtils.cutting(e.getMessage(), 2000, "");
        } catch (Exception e) {
            sucssYn = BACKUP_FAIL;
            errMsg = StringUtils.cutting(e.getMessage(), 2000, "");
        }

        String statcJobEndHMS = DateUtil.getDateTimeMilliSecound();

        backupResultService.requiresNewInsertBackupResult(backupDate, statcJobCyclDstcd, statcJobStartHMS, statcJobEndHMS, sucssYn, errMsg);
    	
    }
    

    public Tseaist01VO findTseaiSt01(String date,String statcJobCyclDstcd) {
        if (date.length() > 6) {
            date = date.substring(0, 6) + "00";
        }
        return tseaist01DAO.findTseaist01(date, statcJobCyclDstcd);

    }
}
