package p.studio.workspaces.assets.details.bank;

import p.packer.messages.assets.AssetFamilyCatalog;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;
import p.studio.workspaces.assets.messages.AssetWorkspaceBankCompositionFile;

import java.util.List;
import java.util.Map;

final class AssetDetailsGlyphBankCompositionFamilySupport extends AssetDetailsAbstractBankCompositionFamilySupport {
    private final AssetBankCapacityService capacityService = new AssetBankCapacityService();

    private int maxSlots = capacityService.maxArtifactsForGlyphBank(Map.of());
    private Map<String, String> outputMetadata = Map.of();

    @Override
    public boolean supports(AssetFamilyCatalog assetFamily) {
        return assetFamily == AssetFamilyCatalog.GLYPH_BANK;
    }

    @Override
    public AssetDetailsBankCompositionDraft createDraft(AssetWorkspaceAssetDetails details) {
        outputMetadata = metadataMap(details);
        maxSlots = capacityService.maxArtifactsForGlyphBank(outputMetadata);
        return super.createDraft(details);
    }

    @Override
    protected boolean canAdd(
            AssetDetailsBankCompositionDraft currentDraft,
            List<AssetWorkspaceBankCompositionFile> accepted,
            AssetWorkspaceBankCompositionFile candidate) {
        return currentDraft.selectedFiles().size() + accepted.size() < maxSlots;
    }

    @Override
    public AssetDetailsBankCompositionCapacityState evaluate(AssetDetailsBankCompositionDraft draft) {
        return capacityService.evaluate(
                AssetFamilyCatalog.GLYPH_BANK,
                draft.selectedFiles().size(),
                outputMetadata,
                Map.of(),
                0L);
    }

    private Map<String, String> metadataMap(AssetWorkspaceAssetDetails details) {
        final String tileSize = details.metadataFields().stream()
                .filter(field -> field.key().equals("tile_size"))
                .map(field -> field.value())
                .findFirst()
                .orElse("16x16");
        return Map.of("tile_size", tileSize);
    }
}
