package p.studio.workspaces.editor;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public final class EditorOpenFileSession {
    private final List<EditorOpenFileBuffer> openFiles = new ArrayList<>();
    private Path activePath;

    public void open(final EditorOpenFileBuffer fileBuffer) {
        final var buffer = Objects.requireNonNull(fileBuffer, "fileBuffer");
        final var existingIndex = indexOf(buffer.path());
        if (existingIndex < 0) {
            openFiles.add(buffer);
        } else {
            openFiles.set(existingIndex, buffer);
        }
        activePath = buffer.path();
    }

    public void activate(final Path path) {
        final var normalizedPath = normalize(path);
        if (find(normalizedPath).isPresent()) {
            activePath = normalizedPath;
        }
    }

    public List<EditorOpenFileBuffer> openFiles() {
        return List.copyOf(openFiles);
    }

    public Optional<EditorOpenFileBuffer> activeFile() {
        if (activePath == null) {
            return Optional.empty();
        }
        return find(activePath);
    }

    public boolean isEmpty() {
        return openFiles.isEmpty();
    }

    private Optional<EditorOpenFileBuffer> find(final Path path) {
        final int index = indexOf(path);
        if (index < 0) {
            return Optional.empty();
        }
        return Optional.of(openFiles.get(index));
    }

    private int indexOf(final Path path) {
        final var normalizedPath = normalize(path);
        for (int index = 0; index < openFiles.size(); index++) {
            if (openFiles.get(index).path().equals(normalizedPath)) {
                return index;
            }
        }
        return -1;
    }

    private Path normalize(final Path path) {
        return Objects.requireNonNull(path, "path").toAbsolutePath().normalize();
    }
}
