package p.studio.compiler.source.tables;

import p.studio.compiler.models.ProjectDescriptor;
import p.studio.compiler.source.identifiers.ProjectId;

import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class ProjectTable extends DenseTable<ProjectId, ProjectDescriptor> implements ProjectTableReader {

    private final Map<Path, ProjectId> projectIdByPath = new HashMap<>();

    public ProjectTable() {
        super(ProjectId::new);
    }

    @Override
    public ProjectId register(final ProjectDescriptor value) {
        return projectIdByPath.computeIfAbsent(value.getRootPath(), ignored -> super.register(value));
    }

    @Override
    public void clear() {
        super.clear();
        projectIdByPath.clear();
    }

    @Override
    public Optional<ProjectDescriptor> optional(final Path pathCanon) {
        return optionalId(pathCanon).map(this::get);
    }

    @Override
    public Optional<ProjectId> optionalId(final Path pathCanon) {
        return Optional.ofNullable(projectIdByPath.get(pathCanon));
    }
}
