package com.eactive.eai.rms.onl.manage.rule.cm;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

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.OnlBaseService;
import com.eactive.eai.rms.common.context.MonitoringContext;
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.onl.loader.service.TransactionLoaderService;


/**
 * <pre>
 *     1. 기능 : CM 저장 취소, 원복하는 service
 * </pre>
 *
 */
@Service("cMCancelService")
public class CMCancelService extends OnlBaseService {
    
	@Autowired
	@Qualifier("monitoringContext")
	private MonitoringContext monitoringContext;

    @Autowired
    private TransactionLoaderService loaderService;
    
    @Autowired
    @Qualifier("cMCancelDao")
    private CmCancelDao dao;
	
	/**
	 * 1. 		다운로드
	 * 2-1. 	레이아웃이면 다운받은 자원을 DB에 업데이트(TR07,08) 
	 * 2-2-1. 	변환이면 다운받은 지원의 변환명을 (스테이징)HE02에서 검색 > EAI서비스코드추출 
	 * 2-2-2. 	서비스코드를 운영으로 HTTP 통신으로 운영으로 넘기기
	 * 2-2-3.	운영에서 해당 서비스코드(HE02)에 요청,응답,에러 변환명 추출 후 스테이징으로 추출결과 보냄
	 * 2-2-4.	운영에서 받은 데이터(요청,응답,에러 변환)로 HE02에 업데이트.
	 * 2-2-5.	다운로드 받은 자원 DB에 업데이트(TR01,02,03)
	 * 3.		api에 취소요청
	 * 
	 * **/
    
	public void transactionLout(String itemName ,String apCode, String pkgNum, String userId, String groupCoCd, String itemPath, int version) throws Exception {
		Properties prop = monitoringContext.getProperties();
		String auroraIni = (String)prop.getProperty(MonitoringContext.CM_AURORA_INI_PATH,"/fshome/greai/eaiadm/aurora/auroraApi_config.ini");
		String localPath     = prop.getProperty(MonitoringContext.CM_RESTORE_PATH     , "/fslog/eai/cmRestore/");
		
		String itemStr = itemName.replace(".txt","");
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		
		String path = localPath + pkgNum + File.separator+ format.format(System.currentTimeMillis()) + File.separator;
		String downloadPath = path;
//		AuroraUtil aurora = new AuroraUtil(auroraIni);
		// Aurora 에서 자원 다운로드 
		logger.info("Aurora FILE DOWN START********");
		
		String status = "";
		if(version>0){
//			HashMap map = aurora.downLoadCmFiles(userId, "KB0", apCode, pkgNum, auroraIni, itemName,downloadPath,itemPath);
//			status = (String)map.get("STATUS");
//			logger.info("Aurora FILE DOWN RETURN STATUS => "+status);
		}
		HashMap tmpMap = new HashMap();
		tmpMap.put("LOUTNAME", itemStr);
		dao.deleteTR07(tmpMap);
		dao.deleteTR08(tmpMap);
		
		
		if (status.equals("success")){	//success
			//List svrArr = new ArrayList();
			HashMap parseMap = convert(loaderService.parse(downloadPath+itemPath+itemName));
			if(parseMap!=null){
				List list = (ArrayList)parseMap.get("TSEAITR07");
				if(list!=null && list.size()>0){
					dao.insertTR07((HashMap)list.get(0));
				}
				List<HashMap> list2 = (ArrayList<HashMap>)parseMap.get("TSEAITR08");
				if(list2!=null && list2.size()>0){
					for(HashMap m : list2){
						dao.insertTR08(m);
					}
				}
			}
			//파일삭제
			fileDelete(path);
		}
		 //DB변경 했으면 CM 취소
//		 aurora.cancelCmSave(pkgNum, userId, apCode, itemName, auroraIni, itemPath);
	}
	public void transactionTran(String itemName ,String apCode, String pkgNum, String userId, String groupCoCd, List<HashMap> prodData,String itemPath ,int version) throws Exception {
		//update HE02
		if(prodData!=null && prodData.size()>0){
			for(HashMap m : prodData){
				dao.updateHE02(m);
			}
		}

		//HashMap retMap = new HashMap();
		Properties prop = monitoringContext.getProperties();
		String auroraIni = (String)prop.getProperty(MonitoringContext.CM_AURORA_INI_PATH,"/fshome/greai/eaiadm/aurora/auroraApi_config.ini");
		String localPath     = prop.getProperty(MonitoringContext.CM_RESTORE_PATH     , "/fslog/eai/cmRestore/");

		String itemStr = itemName.replace(".txt","");
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		
		String path = localPath + pkgNum + File.separator+ format.format(System.currentTimeMillis()) + File.separator;
		String downloadPath = path;
//		AuroraUtil aurora = new AuroraUtil(auroraIni);
		
		String status = "";
		// Aurora 에서 자원 다운로드 	버전 1이상은 운영적용 된적이쑴
		if(version>0){
			logger.info("Aurora FILE DOWN START********");
//			HashMap map = aurora.downLoadCmFiles(userId, "KB0", apCode, pkgNum, auroraIni, itemName,downloadPath,itemPath);
//			status = (String)map.get("STATUS");
//			logger.info("Aurora FILE DOWN RETURN STATUS => "+status);
		}
		
		HashMap tmpMap = new HashMap();
		tmpMap.put("CNVSNNAME", itemStr);
		dao.deleteTR03(tmpMap);
		dao.deleteTR02(tmpMap);
		dao.deleteTR01(tmpMap);
		
		if (status.equals("success")){	//success
			//List svrArr = new ArrayList();
			HashMap parseMap = convert(loaderService.parse(downloadPath+itemPath+itemName));
			if(parseMap!=null){
				List list = (ArrayList)parseMap.get("TSEAITR01");
				if(list!=null && list.size()>0){
					dao.insertTR01((HashMap)list.get(0));
				}
				List<HashMap> list2 = (ArrayList<HashMap>)parseMap.get("TSEAITR02");
				if(list2!=null && list2.size()>0){
					for(HashMap m : list2){
						dao.insertTR02(m);
					}
				}
				List<HashMap> list3 = (ArrayList<HashMap>)parseMap.get("TSEAITR03");
				if(list3!=null && list3.size()>0){
					for(HashMap m : list3){
						dao.insertTR03(m);
					}
				}
			}
			//파일삭제
			fileDelete(path);
		 }
		//DB변경 했으면 CM 취소
//		 aurora.cancelCmSave(pkgNum, userId, apCode, itemName, auroraIni, itemPath);
    }
	
	public List searchEaiSvcName(String eaiSvcStr,String eaiSevrDstcd){
		String[] eaiSvcArr = eaiSvcStr.split(",");
		List eaiSvcList = new ArrayList();
		for(int i=0; i<eaiSvcArr.length; i++){
			String eaiSvcName = eaiSvcArr[i];
			
			logger.info("Server Info > " + eaiSevrDstcd);
			DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(eaiSevrDstcd);
			DataSourceContextHolder.setDataSourceType(dataSourceType);	
			logger.info("Set DataSourcer > " + dataSourceType);
			
			HashMap paramMap = new HashMap();
			paramMap.put("eaiSvcName", eaiSvcName);
			paramMap.put("svcPrcssNo", "1");
			
			HashMap svrMap = dao.selectEaiSvcNameForTranCd(paramMap);
			if(null!=svrMap){
				eaiSvcList.add(svrMap);
				logger.info("THIS SERVER DATA => "+svrMap);
			}
		}
		return eaiSvcList;
	}
	
	public List selectEaiSvcName(HashMap paramMap){
		List<HashMap> eaiSvcArr = dao.selectEaiSvcName(paramMap);
		return eaiSvcArr;
	}
	public List selectTrasnForm(String loutName){
		HashMap paramMap = new HashMap();
		paramMap.put("loutName", loutName);
		List<HashMap> transFromList = dao.selectTrasnForm(paramMap);
		return transFromList;
	}
	
	public static void fileDelete (String path){
		if(path != null && path.trim().length() > 0) {
			File ff = new File(path);
			if(ff.exists()){
				File[]subFile = ff.listFiles();
				if(subFile != null){//취약점소스 수정 2020.08.27
					for(int i=0; i<subFile.length; i++){
						if(subFile[i].isFile()){
							subFile[i].delete();
						}else{
							fileDelete(subFile[i].getPath());
						}
					}
				}
				ff.delete();
			}
		}
	}
	public static HashMap convert(HashMap map) throws Exception{
		for(Object t : map.keySet().toArray()){
			List<HashMap> list = (List<HashMap>)map.get(t);
			for(HashMap m : list){
				String firstCol = m.keySet().iterator().next().toString();
				int firstColSize = firstCol.length();
				boolean isAsis = false;
				for(int i=0; i<firstColSize; i++){
					char c =firstCol.charAt(i);
					if(Character.isLowerCase(c)){
						isAsis = true;
					}
				}
				if(isAsis){
					for(Object col : m.keySet().toArray()){
						if(t.equals("TSEAITR08")){
							if("LyoutItemRefPtrnIDName".equals(col)){
								m.put("LOUTITEMREFPTRNIDNAME",m.get("LyoutItemRefPtrnIDName"));
								m.remove("LyoutItemRefPtrnIDName");
								continue;
							}else if("LyoutDptCnt".equals(col)){
								m.put("LOUTDPTCNT",m.get("LyoutDptCnt"));
								m.remove("LyoutDptCnt");
								continue;
							}
						}else if(t.equals("TSEAITR01") || t.equals("TSEAITR07")){
							m.put("USEYN", 1);
						}
						m.put(col.toString().toUpperCase(), m.get(col)==null?"":m.get(col));
						m.remove(col);
					}
				}
			 }
		 }
		return map;
	}
}
