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

import java.math.BigDecimal;
import java.util.HashMap;

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.CommonUtil;
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.NewLogDailyBackupDAO;
import com.eactive.eai.rms.onl.statistics.backup.dao.Tseaist01DAO;
import com.eactive.eai.rms.onl.statistics.backup.vo.Tseaist01VO;
 
/**
 * <pre>
 * 1. 기능 : New Log Daily Backup의 비즈니스 로직이 담겨져 있다.
 * 2. 처리 개요 : 
 *     - 
 * 3. 주의사항 : 
 * </pre>
 * @author  : 
 * @version : 
 * @since : rts 1.0
 */
@Service("newLogDailyBackupService")
public class NewLogDailyBackupService extends BaseService{

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

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

    @Autowired
    @Qualifier("newLogDailyBackupDAO")
    private NewLogDailyBackupDAO 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이 시작하면 바꿀수 없음.
    	NewLogDailyBackupService self =(NewLogDailyBackupService)appContext.getBean("newLogDailyBackupService");    
    	if (logger.isInfoEnabled()){
    		logger.info("New Log Daily Backup Begin date="+date+" serviceType="+serviceType);
    	}
    	if(serviceType == null)
    	{
    		for (DataSourceType dataSourceType : DataSourceTypeManager.getOnlineDataSourceTypes())
    		{
    			DataSourceContextHolder.setDataSourceType(dataSourceType);
    			self.backup(date);
	    	}
    	}
    	else
    	{
    			DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(serviceType);
        		DataSourceContextHolder.setDataSourceType(dataSourceType);
        		self.backup(date);
    		
    	}
    	if (logger.isInfoEnabled()){
    		logger.info("New Log Daily Backup End date="+date+" serviceType="+serviceType);
    	}
    }
    public void doDelete(final String date, final String serviceType) throws Exception{
    	if(serviceType == null){
    		throw new Exception("서비스 타입 코드가 존재하지 않습니다.");
    	}
    	if ( BigDecimal.ZERO.compareTo(dao.selectLogCount(date))==0){
			throw new Exception("소스 데이터가 존재하지 않습니다.");
		}
    	if (logger.isInfoEnabled()){
    		logger.info("New Log Daily Backup Delete Begin date="+date+" serviceType="+serviceType);
    	}

		DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(serviceType);
		DataSourceContextHolder.setDataSourceType(dataSourceType);
		tseaist01DAO.deleteTseaist01(date, STATC_JOB_CYCL_DSTCD);
		try {
			dao.delete(new HashMap(){{put("date",date);}});
		} catch (Exception e) {
			logger.error("New Log Daily Data delete fail date ="+ date,e);
		}
    		
    	if (logger.isInfoEnabled()){
    		logger.info("New Log Daily Backup Delete End 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();

        try {
            Tseaist01VO tseaist01VO = tseaist01DAO.findTseaist01(date, statcJobCyclDstcd);

            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("date", date);
            paramMap.put("tableName", CommonUtil.getLogTable(date, true));
            
            
            if (tseaist01VO == null) {
            	// 백업로그 생성
            	backupResultService.requiresNewInsertBackupResult(date, statcJobCyclDstcd, statcJobStartHMS, " ", " ", " ");
                //내부일경우 제외 20201015
                if(!"NSG".equals(DataSourceContextHolder.getDataSourceType().getName())){
                	dao.insert(paramMap);
                }
                sucssYn = BACKUP_SUCCESS;
                errMsg = "정상";
            } else if (BACKUP_FAIL.equals(tseaist01VO.getSucssYn())) {
            	//내부일경우 제외 20201015
                if(!"NSG".equals(DataSourceContextHolder.getDataSourceType().getName())){
                	dao.insert(paramMap);
                }
                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(date, statcJobCyclDstcd, statcJobStartHMS, statcJobEndHMS, sucssYn, errMsg);
    	
    }
    
}
