package p.studio.compiler.source.tables;

import org.apache.commons.collections4.CollectionUtils;
import p.studio.compiler.models.SourceHandle;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.source.identifiers.ProjectId;
import p.studio.utilities.structures.ReadOnlyList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileTable extends InternTable<FileId, SourceHandle> implements FileTableReader {

    private final FileIds[] projectFiles;

    public FileTable(int projectCapacity) {
        super(FileId::new);
        projectFiles = new FileIds[projectCapacity];
        Arrays.setAll(projectFiles, ignored -> new FileIds());
    }

    @Override
    public FileId register(final SourceHandle value) {
        final var fileId = super.register(value);
        projectFiles[value.getProjectId().getIndex()].collection.add(fileId);
        return fileId;
    }

    @Override
    public ReadOnlyList<FileId> getFiles(final ProjectId projectId) {
        final var fileIds = projectFiles[projectId.getIndex()];
        if (CollectionUtils.isEmpty(fileIds.collection)) {
            return ReadOnlyList.empty();
        }
        return ReadOnlyList.wrap(fileIds.collection);
    }

    private static class FileIds {
        public final List<FileId> collection = new ArrayList<>();
    }
}