package com.seer.teach.netty.im.handler.im.singlechat;

import cn.hutool.json.JSONUtil;
import com.seer.teach.iot.api.DeviceInfoServiceApi;
import com.seer.teach.iot.api.UserDeviceServiceApi;
import com.seer.teach.netty.common.annotation.ImMessageContentType;
import com.seer.teach.netty.common.proto.MessageProtobuf;
import com.seer.teach.netty.im.handler.im.ImMessageContentHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * TV屏幕状态处理器
 */
@Service
@Slf4j
@ImMessageContentType(13)
@RequiredArgsConstructor
public class TvStatusHandlerImpl implements ImMessageContentHandler {

    private final DeviceInfoServiceApi deviceInfoServiceApi;

    private final UserDeviceServiceApi userDeviceServiceApi;

    @Override
    public void handle(ChannelHandlerContext ctx, MessageProtobuf.Msg msg) {
        String device = msg.getHead().getDevice();
        Map<String, Object> map = JSONUtil.toBean(msg.getBody(), Map.class);
        Integer screenStatus = getStatus(map, "screenStatus");
        Integer volumeStatus = getStatus(map, "volumeStatus");

        Integer deviceId = deviceInfoServiceApi.getDeviceIdByDevice(device);
        Integer userId = getUserId(deviceId);

    }

    /**
     * 从 Map 中获取状态值，若为空返回默认值
     */
    private Integer getStatus(Map<String, Object> map, String key) {
        return map.containsKey(key) ? Integer.parseInt(map.get(key).toString()) : 0;
    }

    /**
     * 获取用户 ID
     */
    private Integer getUserId(Integer deviceId) {
        return userDeviceServiceApi.getUserIdByDeviceId(deviceId);
    }

}
