package com.eactive.eai.rms.bat.extransinfo;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
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.servlet.View;

import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;

@Controller
public class ExTransInfoController extends OnlBaseAnnotationController implements InterceptorSkipController {

    private static final Logger logger = Logger.getLogger(ExTransInfoController.class);

    @Autowired
    @Qualifier("exTransInfoService")
    private ExTransInfoService service;
    
    public String reqEncoding = null;
    public PrintWriter out = null;
    
    /**
     * 외부 솔루션 거래에 대한 EAI DB INSERT,UPDATE,DELETE 요청
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping(value= "/exTransInfo.file", method=RequestMethod.POST)
    public View selectList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
    	logger.info("ExTransaction Message Selecting .......");
    	try {
    		
            HashMap<String,Object> paramap = getParams(request, response);
            logger.info("### request paramap -->" + paramap);
            
        	// select Request Data into DB Table
        	int selectCount = service.selectListCount(paramap);
        	logger.info("### select count -->" + selectCount);

        	List<Map<String,Object>> resultList = service.selectList(paramap);
        	logger.info("### select list -->" + resultList);
            
        	response.setCharacterEncoding(reqEncoding);
    		out.print(resultList);
        	
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setStatus(500);
            try {
            	out.println(ex.getMessage());
                throw ex;
            } catch (Exception e) {
            	logger.error("ExTransaction response getWriter error",e);
            }
        } 
    	
    	return null;
    }
    
    @RequestMapping(value= "/exTransInfo.file", params = "cmd=insert", method=RequestMethod.POST)
    public View insert(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
    	logger.info("ExTransaction Message Insert starting .......");
        try {
        	
            HashMap<String,Object> paramap = getParams(request, response);
            
            // Check input data field length limit
            String checkresult = null; 
            if(paramap != null){  //취약점소스 수정 2020.08.26
            	 checkresult = service.checkFieldLength(paramap); 
            }
            if (checkresult != null && (!checkresult.isEmpty())) {
            	out.print(checkresult);
            	return null;
            }
            
            // Check duplication to insert data
            int selectCount = service.selectListCount(paramap);
            if (selectCount > 0) {
            	out.print("fail - Duplicate for request data");
            	return null;
            } 
            
        	// Insert Request Data into DB Table
            service.insert(paramap);
        	int insertCount = service.selectListCount(paramap);
        	logger.info("### insert count -->" + insertCount);
        	
        	// Select inserted Data in DB Table
        	List<Map<String, Object>> resultMapList = service.selectList(paramap);
        	logger.info("### insert list-->" + resultMapList);
        	
        	response.setCharacterEncoding(reqEncoding);
        	if (insertCount > 0) {
        		out.print("success to insert data : "+insertCount);
        	} else {
        		out.print("fail to insert data");
        	}
                      
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setStatus(500);
            try {
                out.println(ex.getMessage());
                throw ex;
            } catch (Exception e) {
            	logger.error("ExTransaction response getWriter error",e);
            }
        }    	

    	return null;
    }
    
    @RequestMapping(value= "/exTransInfo.file", params = "cmd=update", method=RequestMethod.POST)
    public View update(HttpServletRequest request, HttpServletResponse response) throws Exception {
 
    	logger.info("ExTransaction Message Updating .......");
        try {

            HashMap<String,Object> paramap = getParams(request, response);
            
            // Check update data field length limit
            String checkresult = null; //취약점소스 수정 2020.08.25
            if(paramap != null) {
            	checkresult = service.checkFieldLength(paramap); 
            }
            		
            if (checkresult != null && (!checkresult.isEmpty())) { //취약점소스 수정 2020.08.26
            	out.print(checkresult);
            	return null;
            }
            
            // Check empty to update data
            int selectCount = service.selectListCount(paramap);
            if (selectCount == 0) {
            	out.print("fail - No Data to update data");
            	return null;
            } 
            
        	// Update DB Table to set request Data 
        	service.update(paramap);
        	int updateCount = service.selectListCount(paramap);
        	logger.info("### update count-->" + updateCount);
        	
        	// Select updated Data in DB Table
        	List<Map<String, Object>> resultMapList = service.selectList(paramap);
        	logger.info("### update list-->" + resultMapList);
        	
        	response.setCharacterEncoding(reqEncoding);
        	if (updateCount > 0) {
        		out.print("success to update data : "+updateCount);
        	} else {
        		out.print("No data is updated");
        	}
                      
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setStatus(500);
            try {
                out.println(ex.getMessage());
                throw ex;
            } catch (Exception e) {
            	logger.error("ExTransaction response getWriter error",e);
            }
        } 

    	return null;
    }
    
    @RequestMapping(value= "/exTransInfo.file", params = "cmd=delete", method=RequestMethod.POST)
    public View delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
    	logger.info("ExTransaction Message deleting .......");
        try {

        	HashMap<String,Object> paramap = getParams(request, response);
        	 String checkresult = null;
            // Check input data field length limit
        	if(paramap != null){  //취약점소스 수정 2020.08.24
        		checkresult = service.checkFieldLength(paramap); 
        	           
	            if (!checkresult.isEmpty()) {
	            	out.print(checkresult);
	            	return null;
	            }
	            
	            // Check duplication to insert data
	            int selectCount = service.selectListCount(paramap);
	            if (selectCount == 0) {
	            	out.print("No data to delete");
	            	return null;
	            } 
	            
	        	// Delete Request Data in DB Table
	        	service.delete(paramap);
	        	int deleteCount = service.selectListCount(paramap);
	        	logger.info("### delete count -->" + selectCount);
	        	
	        	response.setCharacterEncoding(reqEncoding);
	        	if (deleteCount == 0) {
	        		out.print("success to delete data : "+selectCount);
	        	} else {
	        		out.print("fail to delete data");
	        	}
        	}
                      
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setStatus(500);
            try {
                out.println(ex.getMessage());
                throw ex;
            } catch (Exception e) {
            	logger.error("ExTransaction response getWriter error",e);
            }
        }
    	
    	return null;
    }
    
    private HashMap<String,Object> getParams(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
        reqEncoding = request.getHeader("encoding");

        request.setCharacterEncoding(reqEncoding);
        response.setCharacterEncoding(reqEncoding);
//        response.setContentType("application/json");
        
        out = response.getWriter();
        logger.info("### request Encoding : "+reqEncoding);
        
        StringBuffer reqJsonBuf = new StringBuffer();
        String line = null;
        BufferedReader reqReader = request.getReader();
        while ((line = reqReader.readLine()) != null) {
        	reqJsonBuf.append(line);
        }
        String reqJsonStr = reqJsonBuf.toString();
        logger.info("### request JSON : "+reqJsonStr);
        
        if (reqJsonStr == null || reqJsonStr.isEmpty()) {
        	out.print("fail - request data is empty.");
        	return null;
        }
        
        JSONObject reqJsonObj = (JSONObject)JSONValue.parse(reqJsonStr);
        if (reqJsonObj == null) {
        	out.print("fail - JsonValue data is null.");
        	return null;
        } 
        
        HashMap<String,Object> paramap = new HashMap<String,Object>();
        for (Object key : reqJsonObj.keySet()) {
        	paramap.put(key.toString(), reqJsonObj.get(key));
        }
                      
        reqReader.close();
        
        return paramap;
    }

}
