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

import p.packer.messages.AssetReference;
import p.packer.messages.assets.OutputCodecCatalog;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public record AssetContractDraft(
        AssetReference assetReference,
        boolean preload,
        String bank,
        OutputCodecCatalog selectedCodec,
        Map<String, String> codecFieldValues) {

    public AssetContractDraft {
        Objects.requireNonNull(assetReference, "assetReference");
        bank = Objects.requireNonNullElse(bank, "unknown");
        selectedCodec = Objects.requireNonNullElse(selectedCodec, OutputCodecCatalog.UNKNOWN);
        codecFieldValues = Map.copyOf(Objects.requireNonNull(codecFieldValues, "codecFieldValues"));
    }

    public static AssetContractDraft fromDetails(AssetWorkspaceAssetDetails details) {
        final Map<String, String> codecFieldValues = new LinkedHashMap<>();
        details.codecConfigurationFieldsByCodec().forEach((codec, fields) ->
                fields.forEach(field -> codecFieldValues.put(keyOf(codec, field.key()), field.value())));
        return new AssetContractDraft(
                details.summary().assetReference(),
                details.summary().preload(),
                details.outputFormat(),
                details.outputCodec(),
                codecFieldValues);
    }

    public AssetContractDraft withPreload(boolean preload) {
        return new AssetContractDraft(assetReference, preload, bank, selectedCodec, codecFieldValues);
    }

    public AssetContractDraft withSelectedCodec(OutputCodecCatalog selectedCodec) {
        return new AssetContractDraft(assetReference, preload, bank, selectedCodec, codecFieldValues);
    }

    public AssetContractDraft withCodecFieldValue(OutputCodecCatalog codec, String fieldKey, String value) {
        final Map<String, String> nextValues = new LinkedHashMap<>(codecFieldValues);
        nextValues.put(keyOf(codec, fieldKey), Objects.requireNonNullElse(value, ""));
        return new AssetContractDraft(assetReference, preload, bank, selectedCodec, nextValues);
    }

    public String codecFieldValue(OutputCodecCatalog codec, String fieldKey, String fallback) {
        return codecFieldValues.getOrDefault(keyOf(codec, fieldKey), Objects.requireNonNullElse(fallback, ""));
    }

    private static String keyOf(OutputCodecCatalog codec, String fieldKey) {
        return codec.name() + ":" + fieldKey;
    }
}
