package com.eactive.eai.rms.ext.cm.epb;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.common.util.DatetimeUtil;
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.common.interceptor.InterceptorSkipController;

@Controller
@RequestMapping(value={"/epb/cmBAP.do","/epb/cmBAP.json"})
public class CmBAPController implements InterceptorSkipController{
	
	private static final Logger logger = Logger.getLogger(CmBAPController.class);
	private static final String resultView ="common/loadResult";

	@Autowired
	private MonitoringContext monitoringContext; 

	@Autowired
    private CmBAPService cmBAPService;    
	
//	@Autowired
//	@Qualifier("onlAgentUtilService")
//    public AgentUtilService agentUtilService;
	
	@RequestMapping(params = { "cmd=load" })
	public ModelAndView load(HttpServletRequest request, String deployId, String serviceType, String appCode, String rollbackYn) throws Exception {
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
		try {
			Properties prop = monitoringContext.getProperties();
			String uploadPath   = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, 	"/dat/eaiData/upload/");
			String afterPath    = prop.getProperty(MonitoringContext.CM_DEVELOPER_AFTER_PATH, 	"/dat/eaiData/after/");
			String backupPath   = prop.getProperty(MonitoringContext.CM_DEVELOPER_BACKUP_PATH, 	"/dat/eaiData/backup/");
			
			run(uploadPath, afterPath, backupPath, serviceType, appCode, deployId, rollbackYn );
			
	    	HashMap result = new HashMap();
	    	result.put("status", "success");
	    	result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
			
		} catch (Exception e) {
			logger.error("CmController: property module error", e);
			//throw new Exception(e);
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
		}
		
	}
	/**
	 * path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
	 * 1. 배포 id 추출
	 * 2. 배포 id 기준으로 목록 수집
	 * 3. 배포 id 기준으로 layout, transform, interface 로딩
	 * 
	 * @throws Exception
	 */
	private void run(String uploadPath, String afterPath, String backupPath, String serviceType, String appCode, String deployId, String rollbackYn ) throws Exception {
		
		String path = uploadPath + serviceType + File.separator + deployId + File.separator + appCode;
		
		File uploadDir = new File(path);
		if (!uploadDir.exists()){
			throw new Exception("폴더존재안함 +" + uploadDir.getAbsolutePath());
		}
		
		// 시스템셋팅(datasourceType)
		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
		if (dt == null){
			logger.info("not support serviceType : "+ serviceType);
			return;
		}
		
		DataSourceContextHolder.setDataSourceType(dt);
				
		ArrayList<String> fileinfoSync = new ArrayList<String>();
		String fileinfoPath = path + File.separator + "fileinfo";
		//fileinfo 식별
		File fileinfoDir = new File(fileinfoPath);
		if (fileinfoDir.exists()){
			//DB 적재하는 부분
			fileinfoSync = cmBAPService.insertFIleInfoFile(dt,fileinfoDir);
		}
		
		//메모리 동기화
		//TODO HD : 검토 필요: 프라퍼티 정보 관리
		//fileinfo
		if (fileinfoSync != null && fileinfoSync.size() > 0){
			cmBAPService.fileInfoMemorySync();
		}
		
		//폴더 이동
		// 5. after 경로로 이동
		//after folder check & move
		// 이동순서 uploadFolder => afterFolder => backupFolder
		// uploadFolder는 원본데이터, afterFolder는 적용된 데이터(최근꺼만 존재), backupFolder 은 적용된게 여러개일경우(히스토리성)
		
		//afterfolder에 존재하면 backupFolder로 이관 중복안나게 폴더에 날짜포맷추가
    	File afterFolder = new File(afterPath + File.separator + serviceType + File.separator + deployId);
    	logger.info("afterFolder : " + afterFolder.getAbsolutePath() + " , " + afterFolder.exists());
    	if (afterFolder.exists()){
    		File backupFolder = new File(backupPath+ File.separator + serviceType + File.separator+ deployId + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
    		logger.info("backupFolder : " + backupFolder.getAbsolutePath());
    		if (backupFolder.exists() && backupFolder.isDirectory()){
    			FileUtils.deleteDirectory(backupFolder);
    		}
    		boolean result = afterFolder.renameTo(backupFolder);
    		logger.info("rename "+afterFolder.getAbsolutePath()+" to   " + backupFolder.getAbsolutePath() + " result=" + result);
    	}
    	//upload folder to after folder (적용된거 이동)
    	File uploadFolder = new File(uploadPath + File.separator + serviceType + File.separator + deployId );
    	logger.info("uploadFolder : " + uploadFolder.getAbsolutePath() + " , "+uploadFolder.exists() );
    	if (uploadFolder.exists()){
    		boolean result = uploadFolder.renameTo(afterFolder);
    		logger.info("rename "+uploadFolder.getAbsolutePath()+" to   " + afterFolder.getAbsolutePath() + " result=" + result);
    	}
		
	}
}
