package com.muyu.analysis.parsing.mqtt;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.w3c.dom.stylesheets.LinkStyle;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author：李庆帅
 * @Package：com.muyu.analysis.parsing.mqtt
 * @Project：cloud-server
 * @name：Test2
 * @Date：2024/10/6 20:36
 */
@Log4j2
public class Test2
{
    private static final int DURATION_SECONDS = 5;
    private static List<JSONObject> receivedStrings = new ArrayList<>();
    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private static int elapsedSeconds = 0;
    private static String file = "elapsed" ;

    public static void main(String[] args){
        //定义一个任务，每秒执行一次
        Runnable task = new Runnable() {
            @Override
            public void run() {
                JSONObject stringFromSource = getStringFromSource();
                receivedStrings.add(stringFromSource);
                System.out.println("Received："+stringFromSource);
                //清理超过的数据
                cleanUpOIdStrings();
                //检查超速条件
                checkForSpeeding();
            }
        };
        //每个1秒执行一次任务
        scheduler.scheduleAtFixedRate(task,0,1, TimeUnit.SECONDS);
    }
    //模拟从某个源获取字符串的方法
    private static JSONObject getStringFromSource(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message","Hello World");
        jsonObject.put("time",System.currentTimeMillis());
        jsonObject.put("elapsed",elapsedSeconds);
        return jsonObject;
    }

    //清理超过60秒的数据
    private static void cleanUpOIdStrings(){
        long currentTime = System.currentTimeMillis();
        receivedStrings.removeIf(jsonObject ->currentTime-jsonObject.getLong("time")>TimeUnit.SECONDS.toMicros(DURATION_SECONDS));
    }

    //检查是否有超速情况
    private static void checkForSpeeding()
    {
        if(receivedStrings.size() < 2)return;//如果数据不足，直接返回

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message","你好");
        jsonObject.put("time",System.currentTimeMillis());
        jsonObject.put("elapsed",10);

        for (int i = 0; i < receivedStrings.size(); i++) {
            JSONObject current = receivedStrings.get(i);
            JSONObject next = receivedStrings.get(i + 1);

            Short currentElapsed = current.getShort(file);
            Short nextElapsed = next.getShort(file);
            receivedStrings.add(jsonObject);
            //检查条件，如果相差大于12，则记录错误
            if (nextElapsed - currentElapsed > 12) {
                System.out.println("出错啦！出错啦！车子超速啦！！！");
            }
        }
    }


}
