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

import com.yfd.monitor.gdw2019.SipLayer;
import com.yfd.monitor.gdw2019.bean.ParentPlatform;
import com.yfd.monitor.gdw2019.transmit.SIPProcessorObserver;
import com.yfd.monitor.gdw2019.transmit.SIPSender;
import com.yfd.monitor.gdw2019.transmit.cmd.SIPRequestHeaderProvider;
import com.yfd.monitor.gdw2019.transmit.event.response.ISIPResponseProcessor;
import com.yfd.monitor.storager.IVideoManagerStorage;
import gov.nist.javax.sip.ResponseEventExt;
import gov.nist.javax.sip.message.SIPResponse;
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 javax.sdp.SdpFactory;
import javax.sdp.SdpParseException;
import javax.sdp.SessionDescription;
import javax.sip.InvalidArgumentException;
import javax.sip.ResponseEvent;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.address.SipURI;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.text.ParseException;
import java.util.List;

/**
 * @description: 处理INVITE响应
 * @date: 2021年11月5日 16：40
 */
@Component
public class InviteResponseProcessor implements InitializingBean, ISIPResponseProcessor {

	private final static Logger logger = LoggerFactory.getLogger(InviteResponseProcessor.class);
	private final String method = "INVITE";

	@Autowired
	private SIPProcessorObserver sipProcessorObserver;

	@Autowired
	private SipLayer sipLayer;

	@Autowired
	private SIPSender sipSender;
	@Autowired
	private IVideoManagerStorage storager;

	@Autowired
	private SIPRequestHeaderProvider headerProvider;

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



	/**
	 * 处理invite响应
	 *
	 * @param evt 响应消息
	 * @throws ParseException
	 */
	@Override
	public void process(ResponseEvent evt ){
		logger.debug("接收到消息：" + evt.getResponse());
		try {
			SIPResponse response = (SIPResponse)evt.getResponse();
			logger.info("=====================接收到消息====================" +response);
			int statusCode = response.getStatusCode();
			// trying不会回复
			if (statusCode == Response.TRYING) {
			}
			// 成功响应
			// 下发ack
			if (statusCode == Response.OK) {
				ResponseEventExt event = (ResponseEventExt)evt;

				String contentString = new String(response.getRawContent());
				// jainSip不支持y=字段， 移除以解析。
				int ssrcIndex = contentString.indexOf("y=");
				// 检查是否有y字段
				SessionDescription sdp;
				if (ssrcIndex >= 0) {
					//ssrc规定长度为10字节，不取余下长度以避免后续还有“f=”字段
					String substring = contentString.substring(0, contentString.indexOf("y="));
					sdp = SdpFactory.getInstance().createSessionDescription(substring);
				} else {
					sdp = SdpFactory.getInstance().createSessionDescription(contentString);
				}
				if (sdp != null) {
					//注意解析----2024-02-13
					SipURI requestUri =
							SipFactory.getInstance().createAddressFactory().createSipURI(sdp.getOrigin().getUsername()
									, event.getRemoteIpAddress() + ":" + event.getRemotePort());
					Request reqAck = headerProvider.createAckRequest(response.getLocalAddress().getHostAddress(),
							requestUri, response);
					logger.info("[回复ack] {}-> {}:{} ", sdp.getOrigin().getUsername(), event.getRemoteIpAddress(),
							event.getRemotePort());
					sipSender.transmitRequest(response.getLocalAddress().getHostAddress(), reqAck);
//					if (response.toString().contains("Play")) {
//						List<ParentPlatform> parentPlatforms = storager.queryEnableParentPlatformList(true);
//						for (ParentPlatform parentPlatform : parentPlatforms) {
//							sipSender.transmitRequest(parentPlatform.getServerIP(), response);
//						}
//					}
				}

			}
		} catch (Exception e) {
			logger.info("[点播回复ACK]，异常：", e );
		}
	}

}
