package com.njzscloud.common.localizer;

import cn.hutool.core.collection.CollUtil;
import com.njzscloud.common.localizer.contant.LocalizerType;
import com.njzscloud.common.mqtt.util.Mqtt;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Slf4j
public class DeviceStore {
    private static final LinkedList<Localizer> localizers = new LinkedList<>();
    private static final ReadWriteLock localizersLock = new ReentrantReadWriteLock();
    private static final Lock localizersWriteLock = localizersLock.writeLock();
    private static final Lock localizersReadLock = localizersLock.readLock();

    public static void init() {
        Mqtt.publish("localizer/loader");
    }

    public static void setLocalizers(LinkedList<Localizer> list) {
        localizersWriteLock.lock();
        try {
            log.info("重新加载设备：{}", list.size());
            localizers.clear();
            if (CollUtil.isNotEmpty(list)) localizers.addAll(list);
        } finally {
            localizersWriteLock.unlock();
        }
    }

    public static Localizer determineLocalizer(String terminalId) {
        localizersReadLock.lock();
        try {
            for (Localizer localizer : localizers) {
                if (localizer.getTerminalId().equals(terminalId)) {
                    return localizer;
                }
            }
        } finally {
            localizersReadLock.unlock();
        }
        return null;
    }

    public static LocalizerType determineType(String terminalId) {
        localizersReadLock.lock();
        try {
            for (Localizer localizer : localizers) {
                if (localizer.getTerminalId().equals(terminalId)) {
                    return localizer.getLocalizerType();
                }
            }
        } finally {
            localizersReadLock.unlock();
        }
        return null;
    }

}
