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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
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 javax.servlet.http.HttpServletResponse;

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.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.acl.user.BizService;
import com.eactive.eai.rms.common.base.BaseAnnotationController;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;

@Controller
public class CmResultController extends BaseAnnotationController  {

	@Autowired
	@Qualifier("bizService")
	private BizService bizService;
	
	@RequestMapping(value= "/onl/transaction/tracking/cmResultMan.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;
	}
	@RequestMapping(value= "/onl/transaction/tracking/cmResultMan.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initBizCombo( HttpServletRequest request,
            HttpServletResponse response,@RequestParam HashMap paramMap) throws Exception {
    	
		String filePath = (String)paramMap.get("filePath"); 
		if(logger.isInfoEnabled()) logger.info("filePath : " + filePath);
		File f = new File(filePath);
		List dirList = new ArrayList();	//디렉토리 리스트
		List bizList = new ArrayList();	//권한 있는 업무코드 리스트
		//HashMap dirMap = new HashMap();	//업무코드의 패키지명
		
		if(f.listFiles() != null){
			for(File info : f.listFiles()){
				if(info.isDirectory()){
					dirList.add(info.getName().trim());
				}
			}
		}
		String userId = SessionManager.getUserId(request);
		 //취약점소스 수정 2020.08.25
		paramMap.put("userId", userId);
		paramMap.put("searchBzwkName", "");
		paramMap.put("targetGridYn", "Y");
		List<HashMap<String,Object>> bizListTmp = bizService.selectUserBizList(paramMap);
		for(HashMap m : bizListTmp){
			bizList.add(m.get("BIZCODE").toString().trim());
		}
		//업무코드, 디렉토리 중복값 리스트만들기
		for(int i=0; i<dirList.size(); i++){
			if(!bizList.contains(dirList.get(i))){
				dirList.remove(i);
			}
		}
		List<HashMap<String,Object>> pkgList = new ArrayList<HashMap<String,Object>>();	//패키지명 리스트 
		for(int i=0; i<dirList.size(); i++){
			String dirPath = filePath+File.separator+(String)dirList.get(i);	// C:/fscm/iomap\EAI
			HashMap<String,Object> pkgMap = new HashMap<String,Object>();
			pkgMap.put("dir",dirList.get(i));
			List<String> pkgList2 = new ArrayList<String>();
			for(File info : new File(dirPath).listFiles()){
				if(info.isDirectory()){
					pkgList2.add(info.getName());
				}
			}
			pkgMap.put("pkgDir", pkgList2);
			pkgList.add(pkgMap);
		}
		Map resultMap = new HashMap();
		resultMap.put("dirList", dirList);
		resultMap.put("pkgList", pkgList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;            
    } 
	
	@RequestMapping(value= "/onl/transaction/tracking/cmResultMan.json",params = "cmd=LIST")
	private ModelAndView getFileList(HttpServletRequest request, 
			HttpServletResponse response, @RequestParam HashMap paramMap) throws Exception {
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		
		String logPath = (String)paramMap.get("logPath");
		String pkgName = (String)paramMap.get("pkgName");
		String mode = (String)paramMap.get("mode");
		
		List<HashMap<String, Object>> cmList = new ArrayList<HashMap<String, Object>>();
				
    	//download folder select
		if(mode.equals("cmFile")){
			logPath = logPath+File.separator+pkgName;
			cmList = subDirList(logPath);
		}else{
			File file = new File(logPath);
			if(file != null){
				for(File f : file.listFiles()){
					if(f.getName().indexOf(pkgName)>=0){
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("FILENAME", f.getName());
						map.put("FILEPATH", f.getPath());
						cmList.add(map);
					}
				}
			}
		}
		resultMap.put("cmList", cmList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value= "/onl/transaction/tracking/cmResultMan.json", params = "cmd=DETAIL")
	private ModelAndView getFileView(HttpServletRequest request, 
			HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String logPath = (String)map.get("logPath");
		
		if(logger.isInfoEnabled()) logger.info("DETAIL logPath : " + logPath);
		
		File txtfile = new File(logPath);

		if(!txtfile.exists()) {
			resultMap.put("status", "fail");
			resultMap.put("errorMsg","file Not Found");
			return new ModelAndView("jsonView", resultMap);
		}
		
		FileReader fr = null;		
		BufferedReader br = null;
		String fileView = "";
		try {
			fr = new FileReader(txtfile); // FileNotFoundException
			br = new BufferedReader(fr); // IOException		
			String line = null;
			while((line=br.readLine()) !=null) {
				fileView = fileView.concat(line+"\n");
			}
			
			resultMap.put("fileView" , fileView);
			
		} catch (Exception e) {
			//e.printStackTrace();
			//취약점소스 수정 2020.08.24
			logger.error(" error", e); 
		} finally {
			try {
				if (br != null) {br.close();}
			} catch (IOException e) {
				//e.printStackTrace();
				//취약점소스 수정 2020.08.24
				logger.error(" error", e); 
			}
		}
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	
	private static List subDirList (String dirPath){
		List result = new ArrayList();
		//List svrList = null;
		
		// [ 업무코드/패키지명/서버구분코드/타입/파일 ] <= 경로순서
		File f = new File(dirPath);
		if(f.listFiles()!=null){
			for(File fileList : f.listFiles()){
				if(fileList.isDirectory()){
					//서버구분코드 추출
					DataSourceType svrDstcd = DataSourceTypeManager.getDataSourceType(fileList.getName());
					String svrStr = "";
					if(svrDstcd!=null){
						svrStr = svrDstcd.getName();
					}
					//타입 추출
					for(File type : new File(fileList.getPath()).listFiles()){
						if(type.isDirectory()){
							if(type.getName().equals("layout") || type.getName().equals("transform")){
								//파일명 추출
								for(File files : new File(type.getPath()).listFiles()){
									if(files.isFile()){
										HashMap resMap = new HashMap();
										resMap.put("SVRDSTCD", svrStr);				//서버구분코드
										resMap.put("TYPE", type.getName());			//타입
										resMap.put("FILENAME", files.getName());	//파일명
										resMap.put("FILEPATH", files.getPath());	//파일경로
										result.add(resMap);
									}
								}
							}
						}
					}
				}
			}
		}
		return result;
	}
}