package com.atlassian.bitbucket.mesh.repository;

import javax.annotation.Nonnull;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

public class SimpleWorkTreeStateDao implements WorkTreeStateDao {

    private AtomicLong idGenerator;
    private Map<Long, WorkTreeState> states;

    public SimpleWorkTreeStateDao() {
        this.states = new ConcurrentHashMap<>();
        this.idGenerator = new AtomicLong(0);
    }

    @Override
    public long create(@Nonnull Instant expiry, boolean hasAlternates, @Nonnull String repositoryId) {
        long id = idGenerator.incrementAndGet();
        states.put(id, new WorkTreeState.Builder()
                .id(id)
                .expiry(expiry)
                .hasAlternates(hasAlternates)
                .repositoryId(repositoryId)
                .build());
        return id;
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        ids.forEach(states::remove);
    }

    @Override
    public int deleteById(long id) {
        return states.remove(id) == null ? 0 : 1;
    }

    @Override
    @Nonnull
    public List<Long> getAllIds() {
        return states.values().stream().map(WorkTreeState::getId).collect(Collectors.toList());
    }

    @Override
    public WorkTreeState findById(long id) {
        return states.get(id);
    }

    @Override
    public List<WorkTreeState> findByRepository(@Nonnull String repositoryId) {
        return states.values().stream()
                .filter(state -> repositoryId.equals(state.getRepositoryId()))
                .collect(Collectors.toList());
    }
}
