package com.ruoyi.iot.queue;

import com.ruoyi.iot.util.HutoolHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

@Component
@Slf4j
public class MsgQueue extends Thread implements ApplicationRunner {

    private BlockingQueue<String> queue = new ArrayBlockingQueue(1024);

    @Value("${receiveService}")
    private String receiveService;
    @Autowired
    private TaskRunner taskRunner;
    public void add(String object){
        try {
            queue.put(object);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
       while (true){
           try {
               String take = queue.take();
                taskRunner.handlerMsg(take);
           } catch (Exception e) {
               e.printStackTrace();
               log.error("执行异常",e);
           }
       }
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
            this.start();
            try {
                HutoolHttpUtil.get(receiveService+"/receive/reset",new HashMap<>());
            }catch (Exception e){
                log.error("连接消息接收服务器失败",e);
            }
            log.info("处理器启动");
    }
}
