// 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.api.ProxySessionModel;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

public class SensLogSession extends ProxySessionModel {

    public static SensLogSession emptySession() {
        return new SensLogSession(false);
    }

    protected static class Info {
        OffsetDateTime lastFetch;

        Info() {
            this.lastFetch = OffsetDateTime.MIN;
        }
    }

    private OffsetDateTime globalFrom, globalTo;
    private Map<String, Info> data;

    public SensLogSession(boolean isActive) {
        super(isActive);
        this.data = new HashMap<>();
        this.globalFrom = OffsetDateTime.MAX;
        this.globalTo = OffsetDateTime.MIN;
    }

    private String createId(long unitId, long sensorId) {
        return String.format("%s/%s", unitId, sensorId);
    }

    public Info getLiveInfo(long unitId, long sensorId) {
        return getLiveInfo(createId(unitId, sensorId));
    }

    private Info getLiveInfo(String id) {
        return data.computeIfAbsent(id, k -> new Info());
    }


    public void updateLastFetch(long unitId, long sensorId, OffsetDateTime dateTime) {
        Info info = getLiveInfo(createId(unitId, sensorId));

        if (info.lastFetch.isBefore(dateTime)) {
            info.lastFetch = dateTime;
        }

        if (dateTime.isBefore(globalFrom)) {
            this.globalFrom = dateTime;
        }
        if (dateTime.isAfter(globalTo)) {
            this.globalTo = dateTime;
        }
    }

    public OffsetDateTime getGlobalFrom() {
        return globalFrom;
    }

    public OffsetDateTime getGlobalTo() {
        return globalTo;
    }
}
