package com.ruoyi.device.mqtt.handler.decoder.upgrade;

import com.ruoyi.device.mqtt.annotation.ConsumerHandler;
import com.ruoyi.device.mqtt.domain.decoder.upgrade.GetApkUrlMessage;
import com.ruoyi.device.mqtt.enums.MsgTypeEnum;
import com.ruoyi.device.mqtt.handler.decoder.AbstractDecoder;
import com.ruoyi.device.mqtt.util.TargetTypeConvertUtil;
import com.ruoyi.device.mqtt.vo.CommonHeader;
import com.ruoyi.device.mqtt.vo.CommonTopic;
import com.ruoyi.device.service.IDeviceUpgradePackageService;
import io.netty.buffer.ByteBuf;
import jakarta.annotation.Resource;

/**
 * 固件 URL 查询上行解码 GET_APK_URL_UP
 */
@ConsumerHandler(msgType = MsgTypeEnum.GET_APK_URL_UP)
public class GetApkUrlDecoder extends AbstractDecoder<Void>
{
    @Resource
    private IDeviceUpgradePackageService deviceUpgradePackageService;

    @Override
    protected Void decode(CommonTopic topic, CommonHeader header, ByteBuf body)
    {
        String deviceType = TargetTypeConvertUtil.convert(body.readUnsignedShortLE());
        Long deviceSn = body.readUnsignedIntLE();
        String targetDeviceType = TargetTypeConvertUtil.convert(body.readUnsignedShortLE());
        int firmwareType = body.readByte();
        body.readUnsignedIntLE();
        int length = body.readByte();
        byte[] content = new byte[length];
        body.readBytes(content);

        GetApkUrlMessage getApkUrlMessage = new GetApkUrlMessage();
        getApkUrlMessage.setDeviceSn(deviceSn);
        getApkUrlMessage.setDeviceType(deviceType);
        getApkUrlMessage.setTargetDeviceType(targetDeviceType);
        getApkUrlMessage.setFirmwareType(firmwareType);
        getApkUrlMessage.setVersion(new String(content));

        deviceUpgradePackageService.handleGetApkUrl(getApkUrlMessage);
        return null;
    }
}
