package com.kym.service.utils;

import com.kym.entity.admin.AdminUserStation;
import com.kym.entity.admin.EquipmentRelation;
import com.kym.entity.admin.Station;
import com.kym.service.admin.AdminUserStationService;
import com.kym.service.admin.EquipmentRelationService;
import com.kym.service.admin.StationService;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author skyline
 * @description
 * @date 2023-08-25 22:58
 */
@Component
@Data
public class KymCache {

    private static Map<String, String> SHORT_ID_MAPPING;
    private static Map<String, String> CONNECTOR_STATION_MAPPING;
    private static Map<String, String> STATION_MAPPING;
    private static Map<Long, String> ADMIN_USER_STATION;

    public KymCache(EquipmentRelationService relationService, StationService stationService, AdminUserStationService adminUserStationService) {
        SHORT_ID_MAPPING = relationService.list().stream().collect(Collectors.toMap(EquipmentRelation::getEquipmentId, EquipmentRelation::getShortId));
        CONNECTOR_STATION_MAPPING = relationService.list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getStationId));
        STATION_MAPPING = stationService.list().stream().collect(Collectors.toMap(Station::getStationId, Station::getStationName));
        ADMIN_USER_STATION = adminUserStationService.list().stream().collect(Collectors.toMap(AdminUserStation::getAdminUserId, AdminUserStation::getStationId));
    }

    public String getShortId(String equipmentId) {
        if (equipmentId.length() == 17) {
            equipmentId = equipmentId.substring(0, 16);
        }
        return SHORT_ID_MAPPING.get(equipmentId);
    }

    public String getConnectorId(String equipmentId) {
        return switch (equipmentId.length()) {
            case 17 -> equipmentId;
            case 16 -> equipmentId.concat("1");
            case 6 ->  SHORT_ID_MAPPING.entrySet().stream().filter(entry -> equipmentId.equals(entry.getValue())).map(Map.Entry::getKey).findFirst().get();
            default -> null;
        };
    }


    public String getStationId(String connectorId) {
        return CONNECTOR_STATION_MAPPING.get(connectorId);
    }

    public String getStationNameByConnectorId(String connectorId) {
        var stationId = CONNECTOR_STATION_MAPPING.get(connectorId);
        return getStationName(stationId);
    }

    public String getStationName(String stationId) {
        return STATION_MAPPING.get(stationId);
    }

    public String getAdminUserStationId(Long adminUserId) {
        return ADMIN_USER_STATION.get(adminUserId);
    }

}
