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 CodecDraft(
        AssetReference assetReference,
        OutputCodecCatalog selectedCodec,
        Map<String, String> codecFieldValues) {

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

    public static CodecDraft 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 CodecDraft(
                details.summary().assetReference(),
                details.outputCodec(),
                codecFieldValues);
    }

    public CodecDraft withSelectedCodec(OutputCodecCatalog selectedCodec) {
        return new CodecDraft(assetReference, selectedCodec, codecFieldValues);
    }

    public CodecDraft 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 CodecDraft(assetReference, 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;
    }
}
