package com.jsowell.netty.service.camera.impl;

import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.sign.MD5Util;
import com.jsowell.netty.server.mqtt.BootNettyMqttChannelInboundHandler;
import com.jsowell.netty.service.camera.CameraBusinessService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;

/**
 * 车位相机业务Service
 *
 * @author Lemon
 * @Date 2023/12/19 16:07:45
 */
@Service
@Slf4j
public class CameraBusinessServiceImpl implements CameraBusinessService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private BootNettyMqttChannelInboundHandler handler;

    /**
     * 解析channel中的ip地址， 并将 sn 和 channelId 进行绑定，存入缓存
     * @param channel
     * @throws UnknownHostException
     */
    public void processConnectMsg(Channel channel) throws UnknownHostException {
        // 解析 channel 中的 ip 地址
        String remoteAddress = channel.remoteAddress().toString();
        // System.out.println(ip);
        String[] parts = remoteAddress.substring(1).split(":");
        String ipAddress = parts[0]; // IP 地址部分
        String port = parts[1]; // 端口号部分
        // 使用 InetAddress 解析IP地址部分
        InetAddress inetAddress = InetAddress.getByName(ipAddress);

        // 输出标准的IP地址格式和端口号
        String standardIPAddress = inetAddress.getHostAddress();
        // System.out.println("端口号：" + port);

        // 获取相机心跳包的缓存信息，将 sn 和 channelId 进行绑定
        String redisKey = CacheConstants.CAMERA_HEARTBEAT + standardIPAddress;
        Object cacheObject = redisCache.getCacheObject(redisKey);
        if (cacheObject != null) {
            String sn = (String) cacheObject;
            // 将 sn 和 channelId 绑定关系存入缓存
            String mqttConnectRedisKey = CacheConstants.MQTT_CONNECT_SN + sn;
            redisCache.setCacheObject(mqttConnectRedisKey, channel.id().asShortText());
        }
    }


    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }



}
