package com.yfd.monitor.gdw2019.transmit.event.request.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yfd.monitor.gdw2019.bean.CmdType;
import com.yfd.monitor.gdw2019.bean.ParentPlatform;
import com.yfd.monitor.gdw2019.bean.SubscribeHolder;
import com.yfd.monitor.gdw2019.bean.SubscribeInfo;
import com.yfd.monitor.gdw2019.transmit.SIPProcessorObserver;
import com.yfd.monitor.gdw2019.transmit.SIPSender;
import com.yfd.monitor.gdw2019.transmit.cmd.ISIPCommanderForPlatform;
import com.yfd.monitor.gdw2019.transmit.event.request.ISIPRequestProcessor;
import com.yfd.monitor.gdw2019.transmit.event.request.SIPRequestProcessorParent;
import com.yfd.monitor.gdw2019.utils.SipUtils;
import com.yfd.monitor.gdw2019.utils.XmlUtil;
import com.yfd.monitor.storager.IVideoManagerStorage;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.header.ExpiresHeader;
import javax.sip.message.Response;
import java.text.ParseException;
import java.util.Iterator;

/**
 * SIP命令类型： SUBSCRIBE请求
 */
@Component
public class SubscribeRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {

	private final Logger logger = LoggerFactory.getLogger(SubscribeRequestProcessor.class);
	private final String method = "SUBSCRIBE";

	@Autowired
	private SIPProcessorObserver sipProcessorObserver;

	@Autowired
	private IVideoManagerStorage storager;

	@Autowired
	private SubscribeHolder subscribeHolder;

	@Autowired
	private SIPSender sipSender;

	@Autowired
	ISIPCommanderForPlatform commanderForPlatform;

	@Override
	public void afterPropertiesSet() throws Exception {
		// 添加消息处理的订阅
		sipProcessorObserver.addRequestProcessor(method, this);
	}

	/**
	 * 处理SUBSCRIBE请求
	 *
	 * @param evt 事件
	 */
	@Override
	public void process(RequestEvent evt) {
		SIPRequest request = (SIPRequest) evt.getRequest();
		try {
			Element rootElement = getRootElement(evt);
			if (rootElement == null) {
				logger.error("处理SUBSCRIBE请求  未获取到消息体{}", evt.getRequest());
				return;
			}
			String name = rootElement.getName();
			if("SIP_XML".equals(name)){//来自上级系统
				String cmd = rootElement.attributeValue("EventType");
				if ("Subscribe_Alarm".equals(cmd)) {
					processNotifyAlarm(request, rootElement);
				} else if ("Subscribe_Status".equals(cmd)) {
					processNotifyStatus(request, rootElement);
				}

			}

		} catch (SipException | DocumentException e ) {
			logger.error("未处理的异常 ", e);
		}

	}



	public void processNotifyAlarm(SIPRequest request, Element rootElement)throws SipException {
		if (request == null) {
			return;
		}
		String platformId = SipUtils.getUserIdFromFromHeader(request);
		ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
		if (platform == null){
			return;
		}
		String EventType = rootElement.attributeValue("EventType");
		SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);
		subscribeInfo.setEventType(EventType);
		Iterator<Element> itemList = rootElement.elementIterator("Item");
		JSONArray jsonArray=new JSONArray();
		while (itemList.hasNext()) {
			Element itemElement = itemList.next();
			JSONObject job=new JSONObject();
			job.putOpt("code",itemElement.attributeValue("Code"));
			job.putOpt("type",itemElement.attributeValue("Type"));
			jsonArray.add(job);
		}
		subscribeInfo.setItems(JSONUtil.toJsonStr(jsonArray));
		try {
    		SIPResponse response = responseSubscribeAck(request, 200,subscribeInfo.getExpires());
			if (subscribeInfo.getExpires() == 0) {
				subscribeHolder.removeAlarmSubscribe(platformId);
			}else {
				subscribeInfo.setResponse(response);
				subscribeHolder.putAlarmSubscribe(platformId, subscribeInfo);
				commanderForPlatform.sendNotify(platform,subscribeInfo,null,null);//向上级发送订阅成功的通知
			}
		} catch (SipException | InvalidArgumentException | ParseException e) {
			logger.error("未处理的异常 ", e);
		}
	}

	private void processNotifyStatus(SIPRequest request, Element rootElement)throws SipException {
		if (request == null) {
			return;
		}
		String platformId = SipUtils.getUserIdFromFromHeader(request);
		ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
		if (platform == null){
			return;
		}
		String EventType = rootElement.attributeValue("EventType");
		SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);
		subscribeInfo.setEventType(EventType);
		Iterator<Element> itemList = rootElement.elementIterator("Item");
		JSONArray jsonArray=new JSONArray();
		while (itemList.hasNext()) {
			Element itemElement = itemList.next();
	    	JSONObject job=new JSONObject();
			job.putOpt("code",itemElement.attributeValue("Code"));
			jsonArray.add(job);
		}
		subscribeInfo.setItems(JSONUtil.toJsonStr(jsonArray));
		try {
			SIPResponse response = responseSubscribeAck(request, 200,subscribeInfo.getExpires());
			if (subscribeInfo.getExpires() == 0) {
				subscribeHolder.removeAlarmSubscribe(platformId);
			}else {
				subscribeInfo.setResponse(response);
				subscribeHolder.putAlarmSubscribe(platformId, subscribeInfo);
				commanderForPlatform.sendNotify(platform,subscribeInfo,null,null);//向上级发送订阅成功的通知
			}
		} catch (SipException | InvalidArgumentException | ParseException e) {
			logger.error("未处理的异常 ", e);
		}
	}

	private void processNotifyCatalogList(SIPRequest request, Element rootElement) throws SipException {
		if (request == null) {
			return;
		}
		String platformId = SipUtils.getUserIdFromFromHeader(request);
		String deviceId = XmlUtil.getText(rootElement, "DeviceID");
		ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
		if (platform == null){
			return;
		}
		SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);

		String sn = XmlUtil.getText(rootElement, "SN");
		logger.info("[回复上级的目录订阅请求]: {}/{}", platformId, deviceId);
		StringBuilder resultXml = new StringBuilder(200);
		resultXml.append("<?xml version=\"1.0\" ?>\r\n")
				.append("<Response>\r\n")
				.append("<CmdType>Catalog</CmdType>\r\n")
				.append("<SN>").append(sn).append("</SN>\r\n")
				.append("<DeviceID>").append(deviceId).append("</DeviceID>\r\n")
				.append("<Result>OK</Result>\r\n")
				.append("</Response>\r\n");

		if (subscribeInfo.getExpires() > 0) {
			subscribeHolder.putCatalogSubscribe(platformId, subscribeInfo);
		}else if (subscribeInfo.getExpires() == 0) {
			subscribeHolder.removeCatalogSubscribe(platformId);
		}
		try {
			ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(platformId);
			SIPResponse response = responseXmlAck(request, resultXml.toString(), parentPlatform, subscribeInfo.getExpires());
			if (subscribeInfo.getExpires() == 0) {
				subscribeHolder.removeCatalogSubscribe(platformId);
			}else {
				subscribeInfo.setResponse(response);
				subscribeHolder.putCatalogSubscribe(platformId, subscribeInfo);
			}
		} catch (SipException | InvalidArgumentException | ParseException e) {
			logger.error("未处理的异常 ", e);
		}
	}
}
