package com.eactive.eai.rms.onl.adapter.sna;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
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.common.util.CharsetDecoderUtil;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.eactive.eai.rms.onl.adapter.socket2.vo.ErrorContentVO;
import com.eactive.eai.rms.onl.common.util.DateUtil;

@Controller
public class SnaLuLogController extends BaseController{
	
	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@Autowired
	@Qualifier("comboService")
	private ComboService comboService; 
	
	
	@RequestMapping(value= "/onl/adapter/sna/snaLuLogMan.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/adapter/sna/snaLuLogMan.json",params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo( HttpServletRequest request,HttpServletResponse response) throws Exception {
	  
	   String logType = request.getParameter("logType");
	   List serverList    = new ArrayList<HashMap<String,Object>>();
	   
	   if("SNA".equals(logType)){
//		   serverList    = comboService.selectListComboForTable("TSEAIAD13", "SNAADPTRSEVRNAME","SNAADPTRSEVRIPNAME", "", "SNAADPTRSEVRNAME");
	   }else{
		   serverList    = comboService.getFromEAIServerWithoutAll();
	   }
	   
	   List<ComboVo> loglevelList = comboService.getFromCode("SNA_SEARCH_LOGLEVEL");
	   
	   Map resultMap = new HashMap();
       resultMap.put("serverRows" , serverList);
       resultMap.put("logLevelRows" , loglevelList);
			
	   ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
	   return modelAndView;            
	} 
	
	@RequestMapping(value= "/onl/adapter/sna/snaLuLogMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		List list = execute(paramMap);
		
		for (int i = 0 ; i < list.size() ; i++)
		{
			//ErrorContentVO vo = (ErrorContentVO) list.get(i);

			//dataSet.put("sline", vo.getSline(), 500, GauceDataColumn.TB_NORMAL);
		}
		
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , list);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}	
	

	 public List execute(HashMap<String,Object> paramMap) throws Exception {
	            
	        String logLevel = (String)paramMap.get("searchLogLevel");
	        String logType = (String)paramMap.get("logType");
	        String searchText = (String)paramMap.get("searchText");

	        int count = 0;
	        //---------------------------------------------------------
	        // 대상 파일명
	        //---------------------------------------------------------

	        String fileName = "";

	        String lastLineText = null;
	        RandomAccessFile randomAccessFile = null;
	        //---------------------------------------------------------
	        // 버프의 내용을 라인씩 읽어 들인다.
	        //---------------------------------------------------------
	        ArrayList errorContentList = new ArrayList();
	        ErrorContentVO errorContent = null;
	        try {
	            //---------------------------------------------------------
	            // 대상 파일명
	            //---------------------------------------------------------
	            String defaultLogPath = monitoringContext.getStringProperty(
	                                    MonitoringContext.DEFAULT_LOG_PATH,
	                                    "/fslog/eai/");
	            String snaWcaLogFile  = monitoringContext.getStringProperty(
	                                    MonitoringContext.SNA_WCA_LOG_FILE,
	                                    "snaAdapter.log");
	            
	            logger.info("defaultLogPath : "+defaultLogPath);
	            logger.info("snaWcaLogFile : "+snaWcaLogFile);
	            
	            if (logType.equals("WCA")) {
	                // (Was 도메인 경로 + Was인스턴스명 + 파일경로) - 이동철
	                fileName = defaultLogPath
	                        + (String)paramMap.get("searchInstNm") + "/"
	                        + snaWcaLogFile;
	            } else {
	                fileName = snaWcaLogFile + "."
	                        + DateUtil.getDate();
	            }

	            logger.info("fileName : "+fileName);
	            
	            if (logLevel.equals("TOTAL"))
	                logLevel = "";

	            File file = new File(fileName);
	            randomAccessFile = new RandomAccessFile(file, "r");
	            
	            long currentPoint = randomAccessFile.getFilePointer();
	            do {
	                randomAccessFile.seek(currentPoint); // 마지막지점 검색
	                lastLineText = randomAccessFile.readLine(); // 마지막지점의 라인을 읽어온다.
	                currentPoint = randomAccessFile.getFilePointer();

	                count++;

	                if (lastLineText == null) 
	                    break;

	                // 만약 현 라인에 해당 로그 level 이 존재 하지 않거나
	                if (lastLineText.indexOf(logLevel) >= 0
	                        && lastLineText.indexOf(searchText) >= 0) {
	                    errorContent = new ErrorContentVO();

	                    lastLineText = CharsetDecoderUtil.toKor(lastLineText);
	                    errorContent.setSline(count + ":" + lastLineText);

	                    //가장 최근이 맨 상단으로 가기 위해(이동철)
	                    errorContentList.add(0, errorContent);
	                } else {
	                	// YUN_DEBUG
	                	logger.debug("lastLineText.indexOf(logLevel) < 0 ");
	                }
	            } while (lastLineText != null);

	        } catch (IOException e) {
	            logger.error(e);
	        } finally {
	            try {
	                randomAccessFile.close();
	            } catch (Exception e) {
	            }
	        }
	        
	        return errorContentList;
	    }



}
