import QtQuick 2.0
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import QtQuick.Controls.Material 2.0

Rectangle {
    id: control

    property string value: ""
    property string currentColor: rgbToHex(redSlider.value, greenSlider.value, blueSlider.value)
    property bool isDarkColor: control.checkIsDarkColor(value)

    onValueChanged: {
        var rgb = hexToRgb(value)

        redSlider.value = rgb.r
        greenSlider.value = rgb.g
        blueSlider.value = rgb.b
    }

    onCurrentColorChanged: {
        value = currentColor
    }

    function rgbToHex(r, g, b) {
      return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }

    function hexToRgb(hex) {
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : null;
    }

    function checkIsDarkColor(color) {
        var rgb = hexToRgb(color)
        var luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; // per ITU-R BT.709

        return luma < 50
    }

    ColumnLayout {
        anchors.fill: parent

        Pane {
            Layout.fillWidth: true
            Layout.preferredHeight: parent.height * 0.5
            Material.background: control.currentColor
            Material.elevation: 5
        }

        Slider {
            id: redSlider
            Layout.fillWidth: true
            Layout.fillHeight: true

            from: 0
            to: 255
            stepSize: 1

            Material.accent: Material.Red
        }

        Slider {
            id: greenSlider
            Layout.fillWidth: true
            Layout.fillHeight: true

            from: 0
            to: 255
            stepSize: 1

            Material.accent: Material.Green
        }

        Slider {
            id: blueSlider
            Layout.fillWidth: true
            Layout.fillHeight: true

            from: 0
            to: 255
            stepSize: 1

            Material.accent: Material.Blue
        }

    }
}
