package com.muyu.vehiclegateway.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.muyu.common.core.utils.uuid.UUID;
import com.muyu.common.redis.service.RedisService;
import com.muyu.vehiclegateway.domain.AuthCar;
import com.muyu.vehiclegateway.domain.Instance;
import com.muyu.vehiclegateway.domain.MqttServerModel;
import com.muyu.vehiclegateway.domain.req.VehicleConnectionReq;
import com.muyu.vehiclegateway.mapper.AuthCarMapper;
import com.muyu.vehiclegateway.service.AuthCarService;
import com.muyu.vehiclegateway.service.VehicleGatewayService;
import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: WangXin
 * @name：VehicleGatewayControllerServiceImpl
 * @Date：2024/9/25 21:07
 */
@Log4j2
@Service
public class VehicleGatewayServiceImpl implements VehicleGatewayService {
    @Autowired
    private RedisService redisService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AuthCarService authCarService;

    @Autowired
    private AuthCarMapper authCarMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static int currentIndex = 0;

    @Override
    public MqttServerModel receiveMsg(VehicleConnectionReq vehicleConnectionReq) {

        List<Instance> instanceList = redisService.getCacheList("instanceList");
        String username = vehicleConnectionReq.getUsername();
        String password = vehicleConnectionReq.getVehicleVin() + vehicleConnectionReq.getTimestamp() + vehicleConnectionReq.getNonce();
        String vin = vehicleConnectionReq.getVehicleVin();

            AuthCar authCar = AuthCar.builder()
                    .vin(vin)
                    .userName(username)
                    .password(password).build();
            authCarService.save(authCar);

        currentIndex = currentIndex % instanceList.size();

        for (int i = 0; i < instanceList.size(); i++) {
            Instance instance = instanceList.get((currentIndex + i) % instanceList.size());
            String status = instance.getStatus();

            if (status.equals("Running")) {
                MqttServerModel model = MqttServerModel.builder()
                        .broker(instance.getIpAddress().replace("[", "").replace("]", ""))
                        .topic("car")
                        .build();

                // 更新当前索引
                currentIndex = (currentIndex + i + 1) % instanceList.size();

                return model;
            }
        }

        return null;
    }

}
