package me.koba1.led.utils;

import me.koba1.led.model.colors.KobaColor;
import me.koba1.led.model.colors.KobaOutputColor;

import java.util.Map;

public class ColorUtils {

    public static KobaOutputColor getDifference(KobaOutputColor previous, KobaOutputColor current) {
        if(previous == null) return current;
        if(previous.isEquals(current)) {
            return null;
        }

        KobaOutputColor difference = new KobaOutputColor();
        for (Map.Entry<Integer, KobaColor> currentEntry : current.getColors().entrySet()) {
            if(previous.getColors().containsKey(currentEntry.getKey()) && previous.getColors().get(currentEntry.getKey()).isEquals(currentEntry.getValue())) continue;

            difference.set(currentEntry.getKey(), currentEntry.getValue());
        }

        if(difference.getColors().isEmpty()) {
            return null;
        }
        return difference;
    }

    public static double[] hexToRgb(String hex) {
        return new double[]{
                Integer.valueOf(hex.substring(1, 3), 16) / 255.0,
                Integer.valueOf(hex.substring(3, 5), 16) / 255.0,
                Integer.valueOf(hex.substring(5, 7), 16) / 255.0
        };
    }

    public static int getAlphaFromHex(String hex) {
        if (hex.length() != 9) return 255;
        return Integer.parseInt(hex.substring(7, 9), 16);
    }

    public static String getHex(String hex) {
        if (hex.length() < 7) return "#FF0000";
        if (hex.length() == 7) return hex;
        return hex.substring(0, 7);
    }

    /**
     *
     * @param hex - #rrggbb and #rrggbbaa format are supported
     * @return
     */
    public static KobaColor getColorFromHex(String hex) {
        KobaColor color = new KobaColor("#FF0000"); // default color
        if (!hex.startsWith("#")) return color;

        // #rrggbb
        if (hex.length() == 7) {
            return new KobaColor(hex, 255);
        } else if (hex.length() == 9) { // #rrggbbaa
            int alpha = Integer.parseInt(hex.substring(7, 9), 16);
            return new KobaColor(hex, alpha);
        }

        return color;
    }
}