package com.yfd.monitor.gdw2019.transmit.event.request.impl.message.query.cmd_parent;


import com.yfd.monitor.gdw2019.bean.Device;
import com.yfd.monitor.gdw2019.bean.ParentPlatform;
import com.yfd.monitor.gdw2019.bean.SipTransactionInfo;
import com.yfd.monitor.gdw2019.transmit.SIPSender;
import com.yfd.monitor.gdw2019.transmit.cmd.impl.SIPCommanderFroPlatform;
import com.yfd.monitor.gdw2019.transmit.event.request.SIPRequestProcessorParent;
import com.yfd.monitor.gdw2019.transmit.event.request.impl.message.IMessageHandler;
import com.yfd.monitor.gdw2019.transmit.event.request.impl.message.query.QueryMessageByparentHandler;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
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 javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.header.FromHeader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class SnapImageByParentMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {

    private Logger logger = LoggerFactory.getLogger(SnapImageByParentMessageHandler.class);
    private final String cmdType = "Camera_Snap";

    @Autowired
    private QueryMessageByparentHandler queryMessageHandler;


    @Autowired
    private SIPCommanderFroPlatform cmderFroPlatform;



    @Autowired
    private SIPSender sipSender;

    @Override
    public void afterPropertiesSet() throws Exception {
        queryMessageHandler.addHandler(cmdType, this);
    }

    @Override
    public void handForDevice(RequestEvent evt, Device device, Element element) {

    }

    @Override
    public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) throws InvalidArgumentException, ParseException, SipException {
        //（1）回复上级系统200 ok
        SIPRequest request = (SIPRequest) evt.getRequest();
        SIPResponse response = this.responseAck(request, 200);
        sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);

        //（2）获取请求参数，并调用截图功能
        FromHeader fromHeader = (FromHeader) evt.getRequest().getHeader(FromHeader.NAME);
        Element itemElement = rootElement.element("Item");
        String deviceid = itemElement.attributeValue("Code");
        String PicServer = itemElement.attributeValue("PicServer");
        String SnapType = itemElement.attributeValue("SnapType");
        String Range = itemElement.attributeValue("Range");
        String Interval = itemElement.attributeValue("Interval");//抓拍间隔，单位秒
        SipTransactionInfo sipTransactionInfo = new SipTransactionInfo(response);
        if(SnapType.equals("0")){ //0 单次推送方式，设备抓拍当前图片且推送
            cmderFroPlatform.snapImageAndsendNoticeMsg(deviceid,PicServer,parentPlatform,sipTransactionInfo);
        }else {//1 多次推送方式，设备以一定时间间隔
            String[] jobtimes={};
            if(Range.contains(","))jobtimes=Range.split(",");
            if(Range.contains("-"))jobtimes=Range.split("-");
            int startTime= Integer.parseInt(jobtimes[0]);
            int endTime= Integer.parseInt(jobtimes[1]);
            int intervalInSeconds=Integer.parseInt(Interval);
            executeDailyTask(startTime,endTime,intervalInSeconds,deviceid,PicServer,parentPlatform,sipTransactionInfo);
        }
    }


    private  void executeDailyTask(int startTime, int endTime, int intervalInSeconds,String deviceid,String PicServer,ParentPlatform parentPlatform, SipTransactionInfo sipTransactionInfo) {
        int interval=endTime-startTime;
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.SECOND, startTime);
        Date startDate = calendar.getTime();
        calendar.add(Calendar.SECOND, interval);
        Date endDate = calendar.getTime();

        // 计算首次执行的延迟时间
        long initialDelay = startDate.getTime() - System.currentTimeMillis();

        // 如果开始时间已过，则计算下一个执行时间
        if (initialDelay < 0) {
            initialDelay = intervalInSeconds - (Math.abs(initialDelay) % intervalInSeconds);
        }
        // 执行任务
        scheduler.scheduleAtFixedRate(() -> {            // 执行你的任务逻辑
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("snap image Task executed at " + sdf.format(new Date()));
            try {
                cmderFroPlatform.snapImageAndsendNoticeMsg(deviceid,PicServer,parentPlatform,sipTransactionInfo);
            } catch (SipException e) {
                e.printStackTrace();
            } catch (InvalidArgumentException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }, initialDelay, intervalInSeconds, TimeUnit.SECONDS);

        // 设置定时任务结束时间
        scheduler.schedule(() -> scheduler.shutdown(), endDate.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }



}
