package com.ai.da.common.utils;

public class PantoneUtils {

    public static int[] rgbToHsv(int[] rgb) {
        //切割rgb数组
        int red = rgb[0];
        int green = rgb[1];
        int blue = rgb[2];

        float r = (float) red / 255;
        float g = (float) green / 255;
        float b = (float) blue / 255;

        float min = Math.min(Math.min(r, g), b);

        float[] hsv = {60, 0, Math.max(Math.max(r, g), b)};

        hsv[1] = (hsv[2] == 0) ? 0 : 1 - min / hsv[2];

        hsv[0] = 60 * (
                (hsv[2] == min) ? Float.NaN :
                        (hsv[2] == r) ? (g - b) / (hsv[2] - min) + ((g < b) ? 6 : 0) :
                                (hsv[2] == g) ? (b - r) / (hsv[2] - min) + 2 :
                                        (r - g) / (hsv[2] - min) + 4
        );

        return new int[]{Math.round(hsv[0]), Math.round(hsv[1] * 100), Math.round(hsv[2] * 100)};
    }

    public static int[] hsvToRgb(int h, int s, int v) {
        // 确保 h 在 [0, 360) 范围内
        h = h % 360;
        if (h < 0) {
            h += 360;
        }

        // 确保 s 和 v 在 [0, 100] 范围内
        s = Math.max(0, Math.min(100, s));
        v = Math.max(0, Math.min(100, v));

        // 将 s 和 v 映射到 [0, 1] 范围
        float sNorm = s / 100.0f;
        float vNorm = v / 100.0f;

        // 计算色相所在的区间
        int hi = (h / 60) % 6;
        float f = (h / 60.0f) - hi;
        float p = vNorm * (1 - sNorm);
        float q = vNorm * (1 - f * sNorm);
        float t = vNorm * (1 - (1 - f) * sNorm);

        float r, g, b;
        switch (hi) {
            case 0:
                r = vNorm;
                g = t;
                b = p;
                break;
            case 1:
                r = q;
                g = vNorm;
                b = p;
                break;
            case 2:
                r = p;
                g = vNorm;
                b = t;
                break;
            case 3:
                r = p;
                g = q;
                b = vNorm;
                break;
            case 4:
                r = t;
                g = p;
                b = vNorm;
                break;
            case 5:
                r = vNorm;
                g = p;
                b = q;
                break;
            default:
                throw new RuntimeException("Invalid HSV values");
        }

        // 将 RGB 值从 [0, 1] 转换为 [0, 255]
        int red = Math.round(r * 255);
        int green = Math.round(g * 255);
        int blue = Math.round(b * 255);

        return new int[]{red, green, blue};
    }

}
