package ru.yandex.canvas.service.color;

import java.awt.Color;

/**
 * @author skirsanov
 */
public final class WGAG20Distance {

    private WGAG20Distance() {
    }

    public static double compute(final String hexColor1, final String hexColor2) {
        return compute(ColorRepresentation.parseCSSColor(hexColor1), ColorRepresentation.parseCSSColor(hexColor2));
    }

    static double getLuminance(final Color color) {
        return 0.2126 * reduceColor(color.getRed() / 255.0)
                + 0.7152 * reduceColor(color.getGreen() / 255.0)
                + 0.0722 * reduceColor(color.getBlue() / 255.0);
    }

    static double compute(final Color color1, final Color color2) {
        double l1 = getLuminance(color1);
        double l2 = getLuminance(color2);

        if (l1 > l2) {
            return calculateContrast(l1, l2);
        } else {
            return calculateContrast(l2, l1);
        }
    }

    private static double calculateContrast(final double l1, final double l2) {
        return (l1 + 0.05) / (l2 + 0.05);
    }

    private static double reduceColor(final double color) {
        if (color <= 0.03928) {
            return color / 12.92;
        } else {
            return Math.pow((color + 0.055) / 1.055, 2.4);
        }
    }
}
