package p.packer.services;

import p.packer.PackerWorkspacePaths;
import p.packer.messages.PackerProjectContext;
import p.packer.models.PackerRegistryEntry;
import p.packer.models.PackerRegistryState;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;

public final class PackerRegistryLookup {
    public Optional<PackerRegistryEntry> findByAssetId(PackerRegistryState state, int assetId) {
        Objects.requireNonNull(state, "state");
        return state.assets().stream().filter(entry -> entry.assetId() == assetId).findFirst();
    }

    public Optional<PackerRegistryEntry> findByAssetUuid(PackerRegistryState state, String assetUuid) {
        Objects.requireNonNull(state, "state");
        final String normalized = Objects.requireNonNull(assetUuid, "assetUuid").trim();
        return state.assets().stream().filter(entry -> entry.assetUuid().equals(normalized)).findFirst();
    }

    public Optional<PackerRegistryEntry> findByRoot(PackerProjectContext project, PackerRegistryState state, Path assetRoot) {
        Objects.requireNonNull(project, "project");
        Objects.requireNonNull(state, "state");
        final String relativeRoot = PackerWorkspacePaths.relativeAssetRoot(project, Objects.requireNonNull(assetRoot, "assetRoot"));
        return state.assets().stream().filter(entry -> entry.root().equals(relativeRoot)).findFirst();
    }

    public Path resolveExistingRoot(PackerProjectContext project, PackerRegistryEntry entry) {
        Objects.requireNonNull(project, "project");
        Objects.requireNonNull(entry, "entry");
        final Path assetRoot = PackerWorkspacePaths.assetRoot(project, entry.root());
        if (!Files.isDirectory(assetRoot)) {
            throw new p.packer.exceptions.PackerRegistryException("Registered asset root does not exist: " + entry.root());
        }
        return assetRoot;
    }
}
