package at.procon.eventhub.tachographfilesession.service;

import at.procon.eventhub.tachographfilesession.model.TachographCompositeSession;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.springframework.stereotype.Repository;

@Repository
public class InMemoryTachographCompositeSessionRepository implements TachographCompositeSessionRepository {

    private final Map<UUID, TachographCompositeSession> sessionsById = new LinkedHashMap<>();

    @Override
    public synchronized TachographCompositeSession save(TachographCompositeSession session) {
        TachographCompositeSession toSave = session.createdAt() == null
                ? new TachographCompositeSession(
                        session.compositeSessionId(),
                        session.tenantKey(),
                        session.label(),
                        session.memberSessionIds(),
                        Instant.now()
                )
                : session;
        sessionsById.put(toSave.compositeSessionId(), toSave);
        return toSave;
    }

    @Override
    public synchronized Optional<TachographCompositeSession> find(UUID compositeSessionId) {
        return Optional.ofNullable(sessionsById.get(compositeSessionId));
    }

    @Override
    public synchronized boolean delete(UUID compositeSessionId) {
        return sessionsById.remove(compositeSessionId) != null;
    }

    @Override
    public synchronized List<TachographCompositeSession> list() {
        List<TachographCompositeSession> result = new ArrayList<>(sessionsById.values());
        result.sort(Comparator.comparing(TachographCompositeSession::createdAt, Comparator.nullsLast(Comparator.naturalOrder()))
                .thenComparing(TachographCompositeSession::compositeSessionId));
        return List.copyOf(result);
    }
}
