package com.eactive.eai.rms.onl.admin.websocket;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.eactive.eai.common.util.HttpUtil;
import com.eactive.eai.data.entity.onl.server.EAIServer;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.onl.server.EAIServerService;

@Service
public class WebSocketService extends BaseService {
	
	private EAIServerService eaiServerService;
	
	@Autowired
	public WebSocketService(EAIServerService eaiServerService) {
		this.eaiServerService = eaiServerService;
	}

	public HashMap<String, Object> selectList(int startNum, int endNum, HashMap paramMap) throws Exception {
		
		HashMap<String, Object> result = new HashMap<>();
		List<HashMap<String, String>> list = new ArrayList<>();

		String[] keyArray = { 
				"wsInstId", 
				"wsAdapterGroupName", 
				"loginUserId", 
				"localSocketAddress",
				"remoteSocketAddress", 
				"socketStatus" 
				};

		/** search parameter **/
		boolean searchConditionMatched = true;
		String remoteSocketAddressParam = (String) paramMap.get("remoteSocketAddress");
		String loginUserId 				= (String) paramMap.get("loginUserId");
		
		int totalCount = 0;
		
		/** 해당 startNum endNum serverList가져오는 정보로 검색결과와 상관없음 **/
		paramMap.put("startNum", 1);
		paramMap.put("endNum", 100);
		List<EAIServer> serverList = eaiServerService.findAll();

		for(EAIServer m : serverList) {

			String serverIp = m.getEaisevrip();
			if(serverIp.contains("*")) {
				continue;
			}
			
			String url = buildUrl(m, paramMap);
			
			logger.debug("HttpCall : " + url);
			String xmlString = HttpUtil.httpCall(url, "GET");
			if(xmlString == null) {
				continue;
			}
			logger.debug("XmlResponseReturn : " + xmlString);
			
			Document doc = parseXmlStringToDocument(xmlString);
			Element root = doc.getDocumentElement();
			NodeList children = root.getElementsByTagName("Rows");
	
			//<Rows>
			for (int i = 0; i < children.getLength(); i++) {
	
				NodeList rowList = ((Element)children.item(i)).getElementsByTagName("Row");
	
				//<Row>
				for (int j = 0; j < rowList.getLength(); j++) {
	
					HashMap<String, String> rowUnit = new HashMap<>();
					NodeList dataList = ((Element)rowList.item(j)).getElementsByTagName("Data");
					
					//<Data>
					for (int k = 0; k < dataList.getLength(); k++) {
						
						Element data = (Element) dataList.item(k);
						rowUnit.put(keyArray[k], data.getTextContent());
						
						if(loginUserId != null && k == 2) {
							searchConditionMatched = data.getTextContent().contains(loginUserId);
							if(!searchConditionMatched) { break; }
						}
						if(remoteSocketAddressParam != null && k == 4) {
							searchConditionMatched = data.getTextContent().contains(remoteSocketAddressParam);
							if(!searchConditionMatched) { break; }
						}
						
					}//</Data>
					if(searchConditionMatched) {
						list.add(rowUnit);
						totalCount++;
					}
				}//</Row>
			}//</Rows>
		}//server
		
		list = paging(startNum, endNum, list);
		for(HashMap m : list) {
			logger.debug(m.toString());
		}

		result.put("totalCount", totalCount);
		result.put("list", list);

		return result;
	}

	private String buildUrl(EAIServer m, HashMap paramMap) {
		
		String prepend = "http://";
		String suppend = "/session/websocketConnections.jsp";
		
		StringBuilder reqUrl = new StringBuilder();
		reqUrl.append(prepend);
		reqUrl.append((String) m.getEaisevrip());
		reqUrl.append(":");
		reqUrl.append((String) m.getSevrlsnportname());
		reqUrl.append(suppend);
		
		return reqUrl.toString();
	}

	private Document parseXmlStringToDocument(String xmlString) throws Exception {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
		
		return doc;
	}
	
	private List<HashMap<String, String>> paging(int startNum, int endNum, List<HashMap<String, String>> list) {
		if(list.size() > endNum) {
			return list.subList(startNum-1, endNum);
		} else {
			return list.subList(startNum-1, list.size());
		}
	}

}
