package at.procon.eventhub.processing.driverworkingtime.model;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public record DriverWorkingTimeActivityInterval(
        UUID sessionId,
        String driverKey,
        String intervalId,
        String activityType,
        String cardSlot,
        String cardStatus,
        String drivingStatus,
        String registrationKey,
        String vehicleKey,
        String sourceKind,
        String firstSourceIntervalId,
        String lastSourceIntervalId,
        OffsetDateTime startedAt,
        OffsetDateTime endedAt,
        long startedAtEpochSecond,
        long endedAtEpochSecond,
        long durationSeconds,
        List<String> sourceIntervalIds,
        boolean synthetic,
        boolean clippedToRequestedPeriod,
        String level
) {
    public DriverWorkingTimeActivityInterval {
        sourceIntervalIds = sourceIntervalIds == null ? List.of() : List.copyOf(sourceIntervalIds);
    }

    public static DriverWorkingTimeActivityInterval fromMap(Map<String, Object> values) {
        if (values == null) {
            return null;
        }
        return new DriverWorkingTimeActivityInterval(
                (UUID) values.get("sessionId"),
                (String) values.get("driverKey"),
                (String) values.get("intervalId"),
                (String) values.get("activityType"),
                (String) values.get("cardSlot"),
                (String) values.get("cardStatus"),
                (String) values.get("drivingStatus"),
                (String) values.get("registrationKey"),
                (String) values.get("vehicleKey"),
                (String) values.get("sourceKind"),
                (String) values.get("firstSourceIntervalId"),
                (String) values.get("lastSourceIntervalId"),
                (OffsetDateTime) values.get("startedAt"),
                (OffsetDateTime) values.get("endedAt"),
                asLong(values.get("startedAtEpochSecond")),
                asLong(values.get("endedAtEpochSecond")),
                asLong(values.get("durationSeconds")),
                castStringList(values.get("sourceIntervalIds")),
                asBoolean(values.get("synthetic")),
                asBoolean(values.get("clippedToRequestedPeriod")),
                (String) values.get("level")
        );
    }

    @SuppressWarnings("unchecked")
    private static List<String> castStringList(Object value) {
        return value instanceof List<?> list ? (List<String>) list : List.of();
    }

    private static long asLong(Object value) {
        return value instanceof Number number ? number.longValue() : 0L;
    }

    private static boolean asBoolean(Object value) {
        return value instanceof Boolean booleanValue && booleanValue;
    }
}
