package com.njzscloud.common.localizer.tuqiang;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.localizer.jt808.JT808;
import com.njzscloud.common.localizer.jt808.message.JT808Message;
import com.njzscloud.common.localizer.tuqiang.listener.TuqiangListeners;
import com.njzscloud.common.localizer.tuqiang.support.TuqiangListener;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Tuqiang {
    public static void run(int port, int bossThreads, int workerThreads) {
        addListener(new TuqiangListeners());
        JT808.run(port, bossThreads, workerThreads);
    }

    public static void stop() {
        JT808.stop();
    }

    private static void addListener(Object object) {
        Method[] methods = object.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(TuqiangListener.class)) {
                TuqiangListener tuqiangListener = method.getAnnotation(TuqiangListener.class);
                String messageId = tuqiangListener.messageId();
                JT808.addListener(messageId, (msg) -> {
                    try {
                        method.invoke(object, msg);
                    } catch (Exception e) {
                        log.error("途强处理消息 {} 时出错", messageId, e);
                    }
                });
            }
        }
    }

    /**
     * 开启追踪
     *
     * @param terminalId 终端ID
     * @param interval   上报间隔，单位秒，0-3600秒，0表示不追踪
     */
    public static void track(String terminalId, int interval) {
        Assert.isTrue(interval >= 0 && interval <= 3600, "上报间隔必须为0-3600秒");
        JT808.sendTxtMessage(terminalId, StrUtil.format("<SPBSJ*P:BSJGPS*C:{}*H:300>", interval));
    }

    /**
     * 获取设备信息
     *
     * @param terminalId 终端ID
     */
    public static void obtainDeviceInfo(String terminalId) {
        JT808.sendTxtMessage(terminalId, "<CKBSJ>");
    }

    /**
     * 启用报警
     *
     * @param terminalId 终端ID
     */
    public static void enableWarn(String terminalId, boolean enable) {
        JT808.sendTxtMessage(terminalId, StrUtil.format("<SPBSJ*P:BSJGPS*6W:{}>", enable ? 1 : 0));
    }

    /**
     * 设置速度报警
     *
     * @param terminalId 终端ID
     * @param speed      速度，单位km/h
     */
    public static void speedThreshold(String terminalId, int speed) {
        JT808.sendTxtMessage(terminalId, StrUtil.format("<SPBSJ*P:BSJGPS*CS:{}*H:300>", speed));
    }

    /**
     * 获取当前位置
     *
     * @param terminalId 终端ID
     */
    public static void currentLocation(String terminalId) {
        JT808Message baseMessage = JT808.createBaseMessage(terminalId, 0x8201);
        JT808.sendMessage(baseMessage);
    }
}
