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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

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

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.context.MonitoringContext;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;

@Controller
public class FirstAccountController extends BaseController{
	
	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@Autowired
    @Qualifier("firstAccountService")
    private FirstAccountService firstAccountService;
	
	
	@RequestMapping(value= "/onl/admin/service/firstAccountMan.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 defaultIp = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_IP,"");
		String defaultPort = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_PORT,"8888");
		
		HttpSession session = request.getSession();
		session.setAttribute("defaultIp", defaultIp);
		session.setAttribute("defaultPort", defaultPort);
		
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}   
	
	@RequestMapping(value= "/onl/admin/service/firstAccountMan.json", params = "cmd=DETAIL_ACCOUNT")
	private ModelAndView selectList(HttpServletRequest request,@RequestParam HashMap<String,Object> paramMap) throws Exception {
	
		Map resultMap = new HashMap();
		resultMap.put("message"   , firstAccountService.accountChkMsg());
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
	
	@RequestMapping(value= "/onl/admin/service/firstAccountMan.json",params = "cmd=INSERT")
	private ModelAndView insert(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		String message = "success";
		
		String ip = "";
		String port = "";
		String msg = "";
		
		ip = (String)paramMap.get("sendip");
		port = (String)paramMap.get("sendport");
		msg = (String)paramMap.get("sendmsg");
		
		if(logger.isInfoEnabled()) logger.info("ip : "+ip+" ,port : "+port +" ,msg : "+msg);
		
		//리턴값0:비정상, 1:정상
		int result = 0;
		result = sendMessageSync(ip, port, msg);
		
		if(logger.isInfoEnabled()) logger.info("result : "+result);
		
		if(result == 1){
			message = "failed";
		}
		
		
		Map resultMap = new HashMap();
		resultMap.put("message"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
	
	
	//Sync Client 소켓
	//LL 4자리 읽어서 길이 체크 (송신시에도 LL 4자리 붙여서 전송) 
	//리턴값0:비정상, 1:정상
	public int sendMessageSync(String ip, String port, String message)
	{
		
		Socket socket = null;
		InputStream is = null;
		OutputStream os = null;

		byte[] lengthBytes = new byte[4];
		try{
			socket = new Socket(ip, Integer.parseInt(port));
			is = socket.getInputStream();
			os = socket.getOutputStream();
			byte[] msgBytes = message.getBytes();
			byte[] sendLength = getLengthByte(msgBytes);
			
			os.write(sendLength);
			os.write(msgBytes);
			os.flush();
			if(logger.isInfoEnabled()) logger.info("request - length header : "+new String(sendLength) + "\n" +message);

			int read = is.read(lengthBytes);
			
			if(read == 4){
				int responseSize = toLength(lengthBytes);
				byte[] response = new byte[responseSize];
				
				String resultValue = new String(response);
				
				if(logger.isInfoEnabled()) logger.info("resultValue :"+resultValue);
				
				if(resultValue.equals("1")){
					return 1;
				}else{
					return 0;
				}
			}else{
				if(logger.isInfoEnabled()) logger.info("read length field failed -"+read);
				return 0;
			}
		}catch(Exception ex){
			;
			return 0;
		}finally{
			if(is != null){
				try{
					is.close();
					}catch(IOException e){
				}
			}
			if(os != null){
				try{
					os.close();
				}catch(IOException e){
					;
				}
			}
			if(socket != null){
				try{
					socket.close();
				}catch(IOException e){
					;
				}
			}
			
		}
	}

	private static String getLength(byte[] message){
		String length = "0000";
		length = String.format("%04d", message.length);
		return length;
	}
	
	private static byte[] getLengthByte(byte[] message){
		return getLength(message).getBytes();
	}

	private static int toLength(byte[] length){
		return Integer.parseInt((new String(length)).trim());
	}

}
