// Copyright (c) 2020 UWB & LESP.
// The UWB & LESP license this file to you under the MIT license.

package cz.senslog.connector.fetch.senslog.v1;

import cz.senslog.connector.model.config.PropertyConfig;

import java.util.*;

class AllowedStation {

    private final Map<Long, Set<Long>> stations;

    AllowedStation(PropertyConfig config) {
        Set<String> attributes = config.getAttributes();
        Map<Long, Set<Long>> stations = new HashMap<>(attributes.size());
        for (String stationId : attributes) {
            long unitId = Long.parseLong(stationId);
            Object attrValue = config.getProperty(stationId);
            if (attrValue instanceof List) {
                List<?> sensors = (List<?>)attrValue;
                for (Object sensor : sensors) {
                    if (sensor instanceof Integer || sensor instanceof Long) {
                        Long sensorId = Long.parseLong(sensor.toString());
                        stations.computeIfAbsent(unitId, k -> new HashSet<>()).add(sensorId);
                    }
                }
            }
        }

        this.stations = stations;
    }

    public boolean isAllowed(long unitId) {
        return stations.containsKey(unitId);
    }

    public boolean isAllowed(long unitId, long sensorId) {
        return stations.containsKey(unitId) && stations.get(unitId).contains(sensorId);
    }
}
