package p.studio.workspaces.assets.metadata;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public record AssetStudioGlyphMaterialPalette(
        String paletteId,
        String displayName,
        String schemaId,
        int version,
        List<String> colors) {

    public AssetStudioGlyphMaterialPalette(String paletteId, String schemaId, int version, List<String> colors) {
        this(paletteId, null, schemaId, version, colors);
    }

    public AssetStudioGlyphMaterialPalette {
        paletteId = Objects.requireNonNull(paletteId, "paletteId").trim();
        displayName = displayName == null || displayName.trim().isBlank() ? null : displayName.trim();
        schemaId = Objects.requireNonNull(schemaId, "schemaId").trim();
        if (paletteId.isBlank()) {
            throw new IllegalArgumentException("paletteId must not be blank");
        }
        if (schemaId.isBlank()) {
            throw new IllegalArgumentException("schemaId must not be blank");
        }
        if (version <= 0) {
            throw new IllegalArgumentException("version must be positive");
        }
        colors = List.copyOf(Objects.requireNonNull(colors, "colors"));
    }

    public List<Integer> convertedRgb565Colors() {
        final List<Integer> converted = new ArrayList<>(colors.size());
        for (String color : colors) {
            converted.add(convertHtmlRgbToRgb565(color));
        }
        return List.copyOf(converted);
    }

    static int convertHtmlRgbToRgb565(String htmlRgb) {
        final String value = Objects.requireNonNull(htmlRgb, "htmlRgb").trim();
        if (!value.matches("^#[0-9A-Fa-f]{6}$")) {
            throw new IllegalArgumentException("htmlRgb must use #RRGGBB format");
        }
        final int rgb = Integer.parseInt(value.substring(1), 16);
        final int red = (rgb >> 16) & 0xFF;
        final int green = (rgb >> 8) & 0xFF;
        final int blue = rgb & 0xFF;
        return ((red >> 3) << 11) | ((green >> 2) << 5) | (blue >> 3);
    }
}
