package kr.co.i4way.genesys.controller;

import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Node;

import com.genesyslab.platform.applicationblocks.com.CfgObject;
import com.genesyslab.platform.applicationblocks.com.objects.CfgAgentGroup;
import com.genesyslab.platform.applicationblocks.com.objects.CfgAgentInfo;
import com.genesyslab.platform.applicationblocks.com.objects.CfgAgentLogin;
import com.genesyslab.platform.applicationblocks.com.objects.CfgAgentLoginInfo;
import com.genesyslab.platform.applicationblocks.com.objects.CfgPerson;
import com.genesyslab.platform.applicationblocks.com.objects.CfgSkillLevel;
import com.genesyslab.platform.commons.collections.KeyValueCollection;
import com.genesyslab.platform.commons.collections.KeyValuePair;
import com.genesyslab.platform.commons.protocol.ChannelState;
import com.genesyslab.platform.configuration.protocol.types.CfgFlag;

import kr.co.i4way.common.util.JsonUtil;
import kr.co.i4way.genesys.cfgserver.ConfigAgentGroup;
import kr.co.i4way.genesys.cfgserver.ConfigAgentLogin;
import kr.co.i4way.genesys.cfgserver.ConfigPerson;
import kr.co.i4way.genesys.cfgserver.initConfigService;
import kr.co.i4way.genesys.model.GenesysInfoVo;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

@RestController
@CrossOrigin(origins = "*")
public class GroupController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
	@Autowired
	private GenesysInfoVo genesysinfovo;
	initConfigService initconfigservice = initConfigService.getInstance();
	ConfigAgentGroup cfg = new ConfigAgentGroup();
	ConfigPerson ps = new ConfigPerson();
	
	@RequestMapping("/group/getAgentGroupInfo")
	public JSONObject getAgentGroupInfo(HttpServletRequest request) throws Exception{
		CfgAgentGroup agentgroup = null;
		JSONObject rtnobj = new JSONObject();
		Map<String, Object> map = new HashMap<>(); 
		String rtnStr = "";

		try {
			//DBID로 조회
			//int group_dbid = request.getParameter("group_dbid") != null ? Integer.parseInt(request.getParameter("group_dbid")) : 0;
			//그룹명으로 조회
			String group_name = request.getParameter("group_name") != null ? request.getParameter("group_name") : "";
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				cfg = new ConfigAgentGroup();
				//agentgroup = cfg.getAgentGroupInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_dbid);
				agentgroup = cfg.getAgentGroupInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_name);
				rtnobj = convertGroupInfo_jsonObj(agentgroup);
			}			
			rtnobj.put("command", "getAgentGroupInfo");
		}catch(Exception e) {
			logger.error("Exception", e);
		}finally {
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/getAllAgentGroupInfo")
	public JSONObject getAgentGroupInfoAll(HttpServletRequest request) throws Exception{
		Collection<CfgAgentGroup> agentgroups = null;
		JSONObject rtnobj = new JSONObject();
		Map<String, Object> map = new HashMap<>(); 
		String rtnStr = "";

		try {
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				cfg = new ConfigAgentGroup();
				agentgroups = cfg.getAgentGroupInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid());
				rtnobj = convertGroupInfo_jsonObj(agentgroups);
			}			
			rtnobj.put("command", "getAgentGroupInfoAll");
		}catch(Exception e) {
			logger.error("Exception", e);
		}finally {
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/getAssignGroupInfo")
	public JSONObject getAssignGroupInfo(HttpServletRequest request) throws Exception{
		Collection<CfgAgentGroup> agentgroups = null;
		CfgPerson person = null;
		JSONObject rtnobj = new JSONObject();
		Map<String, Object> map = new HashMap<>(); 
		String rtnStr = "";

		try {
			String employee_id = request.getParameter("employee_id") != null ? request.getParameter("employee_id") : "";
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				ps = new ConfigPerson();
				person = ps.getPersonInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), "emp", employee_id);

				cfg = new ConfigAgentGroup();
				agentgroups = cfg.getAssignAgentGroup(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), person.getDBID());

				rtnobj = convertGroupInfo_jsonObj(agentgroups);
			}			
			rtnobj.put("command", "getAssignGroupInfo");
		}catch(Exception e) {
			logger.error("Exception", e);
		}finally {
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/createAgentGroup")
	public JSONObject createAgentGroup(HttpServletRequest request) throws Exception{
		JSONObject rtnobj = new JSONObject();
		CfgAgentGroup agentgroup = null;

		try {
			String group_name = request.getParameter("group_name") != null ? request.getParameter("group_name") : "";
			cfg = new ConfigAgentGroup();
			
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				agentgroup = cfg.getAgentGroupInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_name);
				
				if(agentgroup == null) {
					logger.info("Create Person~");
					agentgroup = cfg.createAgentGroup(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_name);
					rtnobj = convertGroupInfo_jsonObj(agentgroup);
				}
			}		
			rtnobj.put("command", "createAgentGroup");
		}catch(Exception e) {
			logger.error("Exception", e);
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/modifyAgentGroup")
	public JSONObject modifyAgentGroup(HttpServletRequest request) throws Exception{
		CfgAgentGroup agentgroup = null;
		JSONObject rtnobj = new JSONObject();
		try {
			String before_group_name = request.getParameter("before_group_name") != null ? request.getParameter("before_group_name") : "";
			String after_group_name = request.getParameter("after_group_name") != null ? request.getParameter("after_group_name") : "";
			cfg = new ConfigAgentGroup();
			
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				agentgroup = cfg.getAgentGroupInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), before_group_name);
				
				if(agentgroup != null) {	//수정모드
					agentgroup = cfg.modifyAgentGroup(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), agentgroup.getDBID(), after_group_name);
					logger.info("Modify AgentGroup~");
				}
				rtnobj = convertGroupInfo_jsonObj(agentgroup);
			}		
			rtnobj.put("command", "modifyAgentGroup");
		}catch(Exception e) {
			logger.error("Exception", e);
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/deleteAgentGroup")
	public JSONObject deleteAgentGroup(HttpServletRequest request) throws Exception{
		JSONObject rtnobj = new JSONObject();
		boolean del_agentgroup_result =  false;
		CfgAgentGroup agentgroup = null;

		try {
			String group_name = request.getParameter("group_name") != null ? request.getParameter("group_name") : "";
			cfg = new ConfigAgentGroup();
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				agentgroup = cfg.getAgentGroupInfo(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_name);
				
				if(agentgroup != null) {	//삭제모드
					del_agentgroup_result = cfg.deleteAgentGroup(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), agentgroup.getDBID());
					logger.info("delete AgentGroup~");
				}
			}		
			rtnobj.put("command", "deleteAgentGroup");
			rtnobj.put("result_delete_agentgroup", del_agentgroup_result);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/assignPersonToAgentGroup")
	public JSONObject assignPersonToAgentGroup(HttpServletRequest request) throws Exception{
		JSONObject rtnobj = new JSONObject();
		boolean del_agentgroup_result =  false;
		CfgAgentGroup agentgroup = null;

		try {
			String group_name = request.getParameter("group_name") != null ? request.getParameter("group_name") : "";
			String employee_ids = request.getParameter("employee_ids") != null ? request.getParameter("employee_ids") : "";
			cfg = new ConfigAgentGroup();
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				agentgroup = cfg.assignPersonToAgentGroup(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_name, employee_ids);
				rtnobj = convertGroupInfo_jsonObj(agentgroup);
			}		
			rtnobj.put("command", "assignPersonToAgentGroup");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/removePersonFromAgentGroup")
	public JSONObject removePersonFromAgentGroup(HttpServletRequest request) throws Exception{
		JSONObject rtnobj = new JSONObject();
		boolean del_agentgroup_result =  false;
		CfgAgentGroup agentgroup = null;

		try {
			String group_name = request.getParameter("group_name") != null ? request.getParameter("group_name") : "";
			String employee_ids = request.getParameter("employee_ids") != null ? request.getParameter("employee_ids") : "";
			cfg = new ConfigAgentGroup();
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				agentgroup = cfg.removePersonFromAgentGroup(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), group_name, employee_ids);
				rtnobj = convertGroupInfo_jsonObj(agentgroup);
			}		
			rtnobj.put("command", "removePersonFromAgentGroup");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return rtnobj;
	}	
	
	@RequestMapping("/group/movePersonFromAgentGroup")
	public JSONObject movePersonFromAgentGroup(HttpServletRequest request) throws Exception{
		JSONObject rtnobj = new JSONObject();
		boolean del_agentgroup_result =  false;
		CfgAgentGroup agentgroup = null;

		try {
			String src_group_name = request.getParameter("src_group_name") != null ? request.getParameter("src_group_name") : "";
			String tgt_group_name = request.getParameter("tgt_group_name") != null ? request.getParameter("tgt_group_name") : "";
			String employee_id = request.getParameter("employee_id") != null ? request.getParameter("employee_id") : "";
			String delete_yn = request.getParameter("delete_yn") != null ? request.getParameter("delete_yn") : "";
			cfg = new ConfigAgentGroup();
			if(initconfigservice.openConfigService(genesysinfovo) == ChannelState.Opened) {
				agentgroup = cfg.movePerson2(initconfigservice.service, genesysinfovo.getCfg_tenant_dbid(), src_group_name, tgt_group_name, employee_id, delete_yn);
				rtnobj = convertGroupInfo_jsonObj(agentgroup);
			}		
			rtnobj.put("command", "movePersonFromAgentGroup");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return rtnobj;
	}	
	
	private JSONObject convertGroupInfo_jsonObj(CfgAgentGroup group) {
		JSONObject jsonObj = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		JSONObject finalJsonObj = new JSONObject();      
		
		if(group != null) {
			Collection<CfgPerson> persons = group.getAgents();
			if(persons != null) {
				finalJsonObj.put("agents", getCfgPersonCollectionInfo(persons));
			}
			
			finalJsonObj.put("dbid", group.getDBID());
			finalJsonObj.put("name", group.getGroupInfo().getName());
			finalJsonObj.put("folderDbid", group.getFolderId());
		}
		return finalJsonObj;
	}
	
	private JSONObject convertGroupInfo_jsonObj(Collection<CfgAgentGroup> groups) {
		JSONObject jsonObj = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		JSONObject finalJsonObj = new JSONObject();      
		Collection<CfgPerson> persons;
		String warpuptm = "";
		
		if(groups != null) {
			for (CfgAgentGroup agentgroup : groups) {
				warpuptm = "";
				persons = null;
				jsonObj = new JSONObject();
				jsonObj.put("dbid", agentgroup.getDBID());
				jsonObj.put("name", agentgroup.getGroupInfo().getName());
				jsonObj.put("folderDbid", agentgroup.getFolderId());
				persons = agentgroup.getAgents();
				if(persons != null) {
					jsonObj.put("agents", getCfgPersonCollectionInfo(persons));
				}
				jsonArray.add(jsonObj);
			}
			finalJsonObj.put("agentGroups", jsonArray);
		}else {
			finalJsonObj.put("agentGroups", null);
		}
		return finalJsonObj;
	}
	
	private JSONArray getCfgPersonCollectionInfo(Collection<CfgPerson> coll) {
		JSONArray rtnArray = new JSONArray();
		JSONObject jsonObj;
		for (CfgPerson person : coll) {
			jsonObj = new JSONObject();
			jsonObj.put("dbid", person.getDBID());
			jsonObj.put("firstName", person.getFirstName());
			jsonObj.put("lastName", person.getLastName());
			jsonObj.put("userName", person.getUserName());
			jsonObj.put("employeeId", person.getEmployeeID());
			jsonObj.put("isAgent", person.getIsAgent().ordinal());
			jsonObj.put("state", person.getState().ordinal());
			rtnArray.add(jsonObj);
		}
		return rtnArray;
	}
}
