package com.eactive.eai.rms.onl.loader.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
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.servlet.ModelAndView;

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;
import com.eactive.eai.rms.common.util.CommonConstants;
import com.eactive.eai.rms.onl.loader.service.HistoryService;

@Controller
public class HistoryController implements InterceptorSkipController {
 
    private static final Logger logger = Logger.getLogger(HistoryController.class);

   
    @Autowired
    private MonitoringContext monitoringContext;

    @Autowired
    @Qualifier("historyService")
    private HistoryService historyService;
    
    
    /**
     * 형상관리에서 userId 별로 처리 대상 조회 -> file down -> filePath 송신
     * delemeter : \t
     * id.csv
     * 
     * id : userId
     * serviceType : EAI/FEP
     * 
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping("/historyList.do")
    public ModelAndView historyList(HttpServletRequest request, HttpServletResponse response , String id, String serviceType ) throws Exception {
    	String view ="common/jsp/loadResult";
		String folder = "LIST";
		FileOutputStream os = null;
		BufferedOutputStream bos = null;
		
        try{
//	        if (!(DataSourceTypeManager.EAI.equals(serviceType)
//	        		|| DataSourceTypeManager.FEP.equals(serviceType))){
//	        	throw new Exception("정의 되지 않은 서비스 타입입니다(EAI|FEP) 받은 서비스 타입="+ serviceType);
//	        }
//	        if (!(DataSourceTypeManager.EAI.equals(serviceType))){
//	        	throw new Exception("정의 되지 않은 서비스 타입입니다(EAI) 받은 서비스 타입="+ serviceType);
//	        }        	
	        if (StringUtils.isEmpty(id)){
		    	throw new Exception("id는 필수 값입니다.");
	        }
	        
	        HashMap<String, ArrayList<HashMap<String, String>>> list = new HashMap<String, ArrayList<HashMap<String, String>>>();
	        if (serviceType != null) {
	        	request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
	        	DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
	        	if(dt != null){//취약점소스 수정 2020.08.27
	        		DataSourceContextHolder.setDataSourceType(dt);
	        		list = historyService.userHistoryList(dt, id );
	        	}
	        }
        	
        	if( list.isEmpty() ) {
        		throw new Exception("no data!!!");
        	}
            String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
            String path = iomapPath + serviceType + File.separator + folder + File.separator ;

        	String buffer = historyService.parse(serviceType, iomapPath, id, list);

    		File directory = new File(path);
    		if (!directory.exists()){
    			if (!directory.mkdirs()){
    				throw new Exception("디렉토리 생성 오류입니다."+path);
    			}
    		}
    		
    		path = path +id+".csv";
    		File file = new File(path);
    		os = new FileOutputStream(file);
			bos = new BufferedOutputStream(os); 
    			
    		bos.write(buffer.getBytes());
    		bos.flush();
    		
    		file.setWritable(true,false);
    		file.setReadable(true,false);
    		file.setExecutable(true,true);
    		
    		
    		logger.info("download success file [" + path +"]");
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("result", "Y");
	    	result.put("file", path);
	        return new ModelAndView(view, "result", result);
        }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	logger.error("HistoryController - " + e.getMessage());
	    	result.put("result", "N");
	    	result.put("errMsg", e.getMessage());
	    	return new ModelAndView(view, "result", result);
        }
        finally {
			try { if(bos != null) bos.close(); } catch(Exception e) {}
			try { if(os != null) os.close(); } catch(Exception e) {}
		}
    }
}
