package com.njzscloud.supervisory.device.drive.barrier.generic;

import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.mqtt.support.MqttMsg;
import com.njzscloud.common.mqtt.util.Mqtt;
import com.njzscloud.supervisory.device.drive.barrier.Barrier;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GenericBarrier extends Barrier {
    private static final String SUBSCRIBE_TOPIC = "device/{}/message/up/{}";
    private static final String PUBLISH_TOPIC = "device/{}/message/down/{}";
    private static final String REPLY_TOPIC = "device/{}/message/down/{}/reply";
    private final GenericBarrierConfig config;

    public GenericBarrier(GenericBarrierConfig config) {
        super(config.getSn());
        this.config = config;
        // MqttUtil.subscribe(topic(Fn.gpio_out_reply), this::openReply);
    }

    @Override
    public void open() {
        IoParam ioParam = IoParam.defaultParam().setSn(getSn());
        ioParam
                .getPayload()
                .getBody()
                .setIo(config.getIo())
                .setValue(1);
        Mqtt.publish(topic(Fn.gpio_out), ioParam);
    }

    private void openReply(MqttMsg msg) {
        IoResult ioResult = msg.getMsg(IoResult.class);
        log.info("道闸开门结果：{}、{}、{}、{}", config.getName(), config.getSn(), config.getCode().getTxt(), ioResult);
    }

    @Override
    public void close() {
        IoParam ioParam = IoParam.defaultParam().setSn(getSn());
        ioParam
                .getPayload()
                .getBody()
                .setIo(config.getIo())
                .setValue(0);
        Mqtt.publish(topic(Fn.gpio_out), ioParam);
    }

    @Override
    public void auto() {
        IoParam ioParam = IoParam.defaultParam().setSn(getSn());
        ioParam
                .getPayload()
                .getBody()
                .setIo(config.getIo())
                .setValue(2);
        Mqtt.publish(topic(Fn.gpio_out), ioParam);
    }

    private String topic(Fn fn) {
        return fn.topic(getSn());
    }

    @RequiredArgsConstructor
    public enum Fn {
        gpio_out(PUBLISH_TOPIC, "gpio_out"),
        gpio_out_reply(REPLY_TOPIC, "gpio_out"),
        ;

        private final String tpl;
        private final String name;

        public String topic(String sn) {
            return StrUtil.format(tpl, sn, name);
        }
    }
}
