package com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.log4j.helpers.LogLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.common.util.UUID;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.excel.ExcelSheet;
import com.eactive.eai.rms.common.excel.ExcelUtil;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.ContainerUtil;
import com.eactive.eai.rms.onl.common.exception.BizException;

//import SCSL.SLDsFile;

/**
 * <pre>
 *     1. 기능 : EAI 메시지 관리 화면의 컨트롤러
 * </pre>
 *
 * @author : music75
 * @version : $Revision: 1.7.2.5 $
 * @since : rts 1.0
 */
@Controller
public class IfUploadForStgCopyController extends BaseController{

    private static final Logger logger = Logger.getLogger(IfUploadForStgCopyController.class);
    /** The service info service. */
    @Autowired
    private EaiMsgManService eaiMsgManService;
    
    @Autowired
    @Qualifier("ifUploadForStgCopyService")
    private IfUploadForStgCopyService service; 
    
    @Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@RequestMapping(value= "/onl/admin/service/ifUploadforStgCopyMan.view")
	private String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd ) throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())){
			cmd = "";
		}else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	
	@RequestMapping(value="/onl/admin/service/ifUploadforStgCopyMan.json", params="cmd=CLONETOPROD")
	private ModelAndView cloneToProd(HttpServletRequest request, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		if (!SystemUtil.isDevServer()){
    		throw new Exception("only support dev server ");
    	}
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String userId = SessionManager.getUserId(request);
		String cmDate = StringUtil.getNullStr(paramMap.get("CmDate"));
		String cmTime = StringUtil.getNullStr(paramMap.get("CmTime"));
		String chgSvcName = StringUtil.getNullStr(paramMap.get("ChgSvcName"));
		String chgFlowControl = StringUtil.getNullStr(paramMap.get("ChgFlowControl"));
		String listSvcName = StringUtil.getNullStr(paramMap.get("ListSvcName"));
		
		try {
			boolean ret = eaiMsgManService.extractInterface(userId, listSvcName, cmDate, cmTime, chgSvcName, chgFlowControl);
			if (!ret) {
				throw new Exception("CM대상 자원의 운영적용에 있어 에러가 발생했습니다.");
			}
			resultMap.put("message", "적용이 완료되었습니다.");
		} catch (BizException be) {
			throw new Exception(be.getMessage(),be);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(e.getMessage());
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value= "/onl/admin/service/ifUploadforStgCopyMan.file", params = "cmd=UPLOAD", method=RequestMethod.POST)
    public ModelAndView handleFileUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file)throws Exception{
		HashMap resultMap = upload( request,  file);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	private HashMap<String,Object> upload(HttpServletRequest request,MultipartFile file) throws Exception{
		String srcFilePath ="";  
    	String dstFilePath ="";
    	String PropPath  ="";
    	String keyFilePath ="";
    	String orgFileNm = "";
		String fileExtension = "";
		String srcFile  = "";
		String dstFile  = "";
		String name = "";
		HashMap<String,Object> resultMap = new HashMap<String,Object>();
		
		///////////////////////////
		srcFilePath = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_SFPATH);
		dstFilePath = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_DFPATH); 
		PropPath  = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_PROP);
		keyFilePath = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_KEY);

		if(srcFilePath != null && srcFilePath.equals("") || dstFilePath != null && dstFilePath.equals("") || 
  		   PropPath != null && PropPath.equals("") || keyFilePath != null && keyFilePath.equals("") ) {			
			resultMap.put("message"  , "[ERRROR] 문서암호화 해제 property를 확인해주세요.");
			logger.error("[ERRROR] 문서암호화 해제 property를 확인해주세요.");
			return resultMap;
		}
		
 		String message = "";
 		
 		//LOG 파일 위치 프라퍼티로 
        String defaultLogPath = monitoringContext.getStringProperty(
                MonitoringContext.DEFAULT_LOG_PATH, "/fslog/eai/");
    	
        srcFilePath = defaultLogPath + ContainerUtil.getInstanceName()+srcFilePath;
        dstFilePath = defaultLogPath + ContainerUtil.getInstanceName()+dstFilePath;
        
        logger.info("srcFilePath : "+srcFilePath);
    	logger.info("dstFilePath : "+dstFilePath);
    	
    	File sdir = new File(srcFilePath);
    	if (sdir != null && !sdir.exists()) {
            boolean success = sdir.mkdirs();
            if (!success) {
                LogLog.error("Failed to create srcFilePath directory structure: " + 
                             sdir);
                message = "문서암호화 해제 property를 확인해주세요.";
    			resultMap.put("message"  , message);
    			logger.error(message);
    			return resultMap;
            }
        }
    	
    	File tdir = new File(dstFilePath);
    	if (tdir != null && !tdir.exists()) {
            boolean success = tdir.mkdirs();
            if (!success) {
                LogLog.error("Failed to create dstFilePath directory structure: " + 
                		tdir);
                message = "문서암호화 해제 property를 확인해주세요.";
    			resultMap.put("message"  , message);
    			logger.error(message);
    			return resultMap;
            }
        }
 		
 		
 		int idx = 0;
 		
 		
		//1.file upload 
 		if(file != null){
			orgFileNm = file.getOriginalFilename();
			idx = orgFileNm.lastIndexOf(".");
			//파일 확장자
			fileExtension = "."+orgFileNm.substring(idx+1);
			
			UUID uuid = UUID.randomUUID();
	 		name = uuid.toString();
			BufferedOutputStream stream = null;
            try {
            	
                byte[] bytes = file.getBytes();
                stream =new BufferedOutputStream(new FileOutputStream(new File(srcFilePath +name+fileExtension)));
//                stream =new BufferedOutputStream(new FileOutputStream(new File(dstFile)));
                stream.write(bytes);
                message = "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                message = "You failed to upload " + name + " => " + e.getMessage();
            } finally{
            	if (stream != null)try {stream.close();} catch (IOException e) {}
            }
       
       
	        srcFile= srcFilePath +name+fileExtension;
	 		dstFile= dstFilePath +name+"_Dec"+fileExtension;
	 		
	 		logger.info("srcFile : "+srcFile);
	 		logger.info("dstFile : "+dstFile);
		
 			//문서복호화   0:성공   -36:원본파일이 비암호화문서 성공과 동일적용
 			int decRtn = DecFile(PropPath,keyFilePath,srcFile,dstFile);
		
			if(!(decRtn == 0 || decRtn == -36) ){
				if(decRtn == 1000){
					message = "[ERRROR] 문서보안 에러코드 : "+decRtn+" \n에러내용 : 원본파일이 없습니다";
				}else if(decRtn == 3000){
					message = "[ERRROR] 문서보안 에러코드 : "+decRtn+" \n에러내용 : 키 파일이 없습니다";
				}else{
					message = "[ERRROR] 문서보안 에러코드 : "+decRtn+" \n에러내용 : 복호화 실패하였습니다.";
				}
				logger.error(message);
                resultMap.put("message"  , message);
    			return resultMap;
			}
			
		} else {
            message = "You failed to upload " + name + " because the file was empty.";
        }
		
		String [] sheetNames = {"시스템인터페이스목록"};

	    //3. sheet to memory
	    List<Map<String,Object>> mSheet = new ArrayList<Map<String,Object>>();
	    
		 try{
	    	ExcelSheet[] sheets = (ExcelSheet[])ExcelUtil.loadExcelFile(dstFile); //복호화된 파일명
	    	
	        for (int i=0;i<sheets.length;i++){
	        	String[][] data = null;
	        	for(int j=0;j<sheetNames.length;j++){
	        		if (sheetNames[j].equals(sheets[i].getName())){
	        			int index = 0;
        				int maxcolumn = 35;
						while (sheets[i].existsRowForXlsx(index)) {
							index++;
						}
						data = new String[index][maxcolumn];
						for(int row=0;row<index;row++){
							for(int col=0;col<maxcolumn;col++){
								String dataStr = sheets[i].getCellStringForXlsx(row, col);
								if(col==0 && dataStr.equals("")){
									continue;
								}
								data[row][col]=dataStr;
							}
						}
						Map<String,Object> h = new HashMap<String,Object>();
						h.put("sheetName", sheets[i].getName());
						h.put("data", data);
						mSheet.add(h);
	        		}else{
	        			//sheet 명명규칙 오류
	        		}
	        	}
	        }
	    }catch(Exception e){
	    	message = "[ERRROR] 형식에 맞지않는 자료 입니다. ";
	    	logger.error(message+e.getMessage());
	    	resultMap.put("message"  , message);
			return resultMap;
	    }
		 
	    if(mSheet.size()==0){
	    	message = "[ERRROR] 유효한 시트명이 존재 하지 않습니다.";
	    	logger.error(message);
	    	resultMap.put("message"  , message);
			return resultMap;
	    }
	    
	  
	    List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
    	List<HashMap<String,Object>> list = null;
    	//String msg = "";
    	//String status = "성공";
    	try {
        	String[][] arrData = (String[][])mSheet.get(0).get("data");
        	String sheetName = (String)mSheet.get(0).get("sheetName");
        	try{
        		list = service.uploadFull(arrData,request,sheetName);
        	}catch(Throwable e){
        		list = new ArrayList<HashMap<String,Object>>();
        		HashMap<String,Object> row = new HashMap<String,Object>();
				row.put("SHEETNAME" , sheetName);
				row.put("RESULT"    , "X");
				row.put("MESSAGE"   , e.getMessage());
				list.add(row);
        	}
        	result.addAll(list);
    	} catch (Throwable e) {
			message = e.getMessage();
		}
		resultMap.put("message"  , message);
		resultMap.put("rows"     , result);
		return resultMap;
	}
	public int DecFile(String prop,String keyFilePath,String srcFile,String dstFile) throws Exception{

//		SLDsFile sFile = new SLDsFile();
//
//		sFile.SettingPathForProperty(prop); 
//		
//		int retVal = sFile.CreateDecryptFileDAC (
//		keyFilePath,
//		"SECURITYDOMAIN",
//		srcFile,
//		dstFile);
//		logger.info( " CreateDecryptFileDAC [" + retVal + "]");
		int retVal =0;
		return retVal;
	}
}
