// Import the Lasal Runtime base element into your component
// Import SigPolymer to use Polymer methods: html, afterNextRender, beforeNextRender, debouncer, timeOut
// or if your component's getter template() returns a HTML literal
import { LasalRuntimeSigElement, SigPolymer } from '../../sigmatek/sig-element/sig-element.js';
//ColorpickerBase with functionality shared by all colorpickers
import LasalRuntimeSigControlColorpickerBase from './sig-control-colorpicker-base.js';
/****************************************************************************************************
 * @class LasalRuntimeSigControlColorpickerBar
 * @extends {LasalRuntimeSigControlColorpickerBase}
 ****************************************************************************************************/
export class LasalRuntimeSigControlColorpickerBar extends LasalRuntimeSigControlColorpickerBase {
    
    /****************************************************************************************************
     * When the element is loaded, importMeta() assigns reference to the path from 
     * which an element was imported to its importPath property. 
     * Relative URLs in styles are automatically re-written to be relative to the importPath property. 
     * You can use [[importPath]] in your component to load url resources
     * 
     * @readonly
     * @static
     ****************************************************************************************************/
    static get importMeta() {
        return import.meta;
    }

    /****************************************************************************************************
     * Return the component style and template as a template literal
     *
     * @readonly
     * @static
     ****************************************************************************************************/
    static get template() {
        return SigPolymer.html`
    <style include="sig-element-css">
            :host {
                /* Basic styling of the component */
                color: var(--theme-sig-control-colorpicker-bar-color, inherit);
                background-color: var(--theme-sig-control-colorpicker-bar-background-color, transparent);
                border-width: var(--theme-sig-control-colorpicker-bar-border-width, inherit);
                border-color: var(--theme-sig-control-colorpicker-bar-border-color, inherit);
                border-style: var(--theme-sig-control-colorpicker-bar-border-style, none);
                border-radius: var(--theme-sig-control-colorpicker-bar-border-radius, none);

                /* Basic box model settings */
                display: block;
                position: absolute;
                overflow: initial;

                height: auto;
                width: auto;

                z-index: 7;
            }

            :host * {
                /* Reset margin and paddings for child elements and turn of text selection */
                @apply --notextselect;
                margin: 0;
                padding: 0;
            }

            .clearfix:after {
                @apply --clearfix
            }

            .sig-control-colorpicker-bar {
                box-sizing: border-box;
                height: 100%;
                width: 100%;
                position: relative;
                border-width: var(--theme-sig-control-colorpicker-picker-border-width, 0px);
                border-style: var(--theme-sig-control-colorpicker-picker-border-style, none);
                border-color: var(--theme-sig-control-colorpicker-picker-border-color, transparent);
                border-radius: var(--theme-sig-control-colorpicker-picker-border-radius, 3px);
                background-color: var(--theme-sig-control-colorpicker-picker-background-color, rgba(255,255,255,1));
                padding-left: 10px;
                padding-right: 10px;
            }

            #colorSelectArea {
                display: flex;
                flex-wrap: wrap;
                justify-content: space-evenly;
            }

            .color {
                height: 30px;
                width: 50px;
                box-sizing: border-box;
                border: 1px solid black;
                margin: 1px
            }

            sig-control-input,
            sig-control-button {
                --theme-sig-element-top: 0;
                --theme-sig-element-left: 0;
                display: inline-block;
                position: relative;
            }

            sig-control-input {
                --theme-sig-element-height: var(--theme-sig-control-colorpicker-picker-input-height, 35px);
                --theme-sig-element-width: var(--theme-sig-control-colorpicker-picker-input-width, 80px);
                --theme-sig-control-input-background-color: var(--theme-sig-control-colorpicker-picker-input-background-color, rgba(255, 255, 255, 1));
                /*--theme-sig-control-input-value-background-color: var(--theme-sig-control-colorpicker-picker-input-value-background-color, rgba(215, 215, 215, 1));*/
                --theme-sig-control-input-value-active-color: var(--theme-sig-control-colorpicker-picker-input-value-active-color, rgba(40,50,45,1));
                --theme-sig-control-input-value-active-background-color: var(--theme-sig-control-colorpicker-picker-input-value-active-background-color, rgba(174, 200, 26, 1));
                --theme-sig-control-input-color: var(--theme-sig-control-colorpicker-picker-input-color, rgba(40,50, 45, 1));
                --theme-sig-control-input-border-color: var(--theme-sig-control-colorpicker-picker-input-border-color, rgba(40,50,45, 1));
                --theme-sig-control-input-border-width: var(--theme-sig-control-colorpicker-picker-input-border-width, 1px);
                --theme-sig-control-input-border-style: var(--theme-sig-control-colorpicker-picker-input-border-style, solid);
                --theme-sig-control-input-background-color-direction: var(--theme-sig-control-colorpicker-picker-input-background-color-direction, to bottom);
                --theme-sig-control-input-value-active-background-color-stop: var(--theme-sig-control-colorpicker-picker-input-value-active-background-color-stop
                    /* , rgba(174, 200, 26, 1) */
                    );
                --theme-sig-control-input-active-background-color-direction: var(--theme-sig-control-colorpicker-picker-input-active-background-color-direction, to bottom);
                --theme-sig-control-input-border-radius: var(--theme-sig-control-colorpicker-picker-input-border-radius, 3px);
                --theme-sig-control-input-border-color-direction: var(--theme-sig-control-colorpicker-picker-input-border-color-direction, to bottom);
                --theme-sig-control-input-shadow-size: var(--theme-sig-control-colorpicker-picker-input-shadow-size, 0px);
                --theme-sig-control-input-activ-border-color: var(--theme-sig-control-colorpicker-picker-input-activ-border-color
                    /* , inherit */
                    );
                --theme-sig-control-input-activ-border-color-direction: var(--theme-sig-control-colorpicker-picker-input-activ-border-color-direction, to bottom);
                --theme-sig-control-input-pressed-shadow-size: var(--theme-sig-control-colorpicker-picker-input-pressed-shadow-size, 0px);
                --theme-sig-control-input-value-text-align: var(--theme-sig-control-colorpicker-picker-input-value-text-align, center);
                --theme-sig-control-input-margin-leftright: var(--theme-sig-control-colorpicker-picker-input-margin-leftright, 0px);
                --theme-sig-control-input-margin-top: var(--theme-sig-control-colorpicker-picker-input-margin-top, 5px);
                --theme-sig-control-input-unit-text-align: var(--theme-sig-control-colorpicker-picker-input-unit-text-align, center);
                --theme-sig-control-input-unit-margin-leftright: var(--theme-sig-control-colorpicker-picker-input-unit-margin-leftright, 0px);
                --theme-sig-control-input-unit-margin-bottom: var(--theme-sig-control-colorpicker-picker-input-unit-margin-bottom, 5px);
                --theme-sig-control-input-unit-text-size: var(--theme-sig-control-colorpicker-picker-input-unit-text-size, inherit);
                --theme-sig-control-input-unit-color: var(--theme-sig-control-colorpicker-picker-input-unit-color, inherit);
            }
            #hexcontainer sig-control-input {
                --theme-sig-element-width: var(--theme-sig-control-colorpicker-picker-hex-input-width, var(--theme-sig-control-colorpicker-picker-input-width, 80px));
            }

            #colorpickermarker1 {
                position: absolute;
                box-sizing: border-box;
                background-color: blue;
                top: 50%;
                left: 0;
                transform: translate3d(calc(0px - 50%), -50%, 0);
                width: var(--theme-sig-control-colorpicker-bar-marker-width, 20px);
                height: var(--theme-sig-control-colorpicker-bar-marker-height, 20px);
                border: 1px solid black;
                border-radius: var(--theme-sig-control-colorpicker-picker-marker-border-radius, 999px);
            }

            #colorSelectArea {
                left: 50%;
                position: relative;
                transform: translateX(-50%);
            }

            #canvas {
                border-radius: 999px;
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
            }

            .hidden {
                display: none;
            }

            sig-control-button {
                margin-right: var(--theme-sig-control-colorpicker-picker-button-spacing, 10px) !important;
                --theme-sig-element-height: var(--theme-sig-control-colorpicker-picker-button-height, 50px);
                --theme-sig-element-width: var(--theme-sig-control-colorpicker-picker-button-width, 100px);
                --theme-sig-control-button-color: var(--theme-sig-control-colorpicker-picker-button-color, rgba(255, 255, 255, 1));
                --theme-sig-control-button-background-color: var(--theme-sig-control-colorpicker-picker-button-background-color, rgba(40, 50, 45, 1));
                --theme-sig-control-button-border-color: var(--theme-sig-control-colorpicker-picker-button-border-color, transparent);
                --theme-sig-control-button-border-width: var(--theme-sig-control-colorpicker-picker-button-border-width, 0px);
                --theme-sig-control-button-border-radius: var(--theme-sig-control-colorpicker-picker-button-border-radius, 3px);
                --theme-sig-control-button-border-style: var(--theme-sig-control-colorpicker-picker-button-border-style, none);
                --theme-sig-control-button-pressed-background-color: var(--theme-sig-control-colorpicker-picker-button-pressed-background-color, rgba(174, 200, 26, 1));
                --theme-sig-control-button-pressed-color: var(--theme-sig-control-colorpicker-picker-button-pressed-color, rgba(255, 255, 255, 1));
                --theme-sig-control-button-background-color-direction: var(--theme-sig-control-colorpicker-picker-button-background-color-direction, to bottom);
                --theme-sig-control-button-border-color-direction: var(--theme-sig-control-colorpicker-picker-button-border-color-direction, to bottom);
                --theme-sig-control-button-shadow-size: var(--theme-sig-control-colorpicker-picker-button-shadow-size, 0px);
                --theme-sig-control-button-text-align: var(--theme-sig-control-colorpicker-picker-button-text-align, center);
                --theme-sig-control-button-vertical-align: var(--theme-sig-control-colorpicker-picker-button-vertical-align, middle);
                --theme-sig-control-button-background-image: var(--theme-sig-control-colorpicker-picker-button-background-image, none);
                --theme-sig-control-button-background-repeat: var(--theme-sig-control-colorpicker-picker-button-background-repeat, no-repeat);
                --theme-sig-control-button-background-position-x: var(--theme-sig-control-colorpicker-picker-button-background-position-x, center);
                --theme-sig-control-button-background-position-y: var(--theme-sig-control-colorpicker-picker-button-background-position-y, center);
                --theme-sig-control-button-background-size: var(--theme-sig-control-colorpicker-picker-button-background-size, cover);
                --theme-sig-control-button-pressed-background-color-direction: var(--theme-sig-control-colorpicker-picker-button-pressed-background-color-direction, to bottom);
                --theme-sig-control-button-pressed-background-image: var(--theme-sig-control-colorpicker-picker-button-pressed-background-image, inherit);
                --theme-sig-control-button-pressed-border-color-direction: var(--theme-sig-control-colorpicker-picker-button-pressed-border-color-direction, to bottom);
                --theme-sig-control-button-pressed-shadow-size: var(--theme-sig-control-colorpicker-picker-button-pressed-shadow-size, 0px);
                --theme-sig-control-led-width: 10px;
                --theme-sig-control-led-height: 10px;
                --theme-sig-control-button-led-border-width: var(--theme-sig-control-colorpicker-picker-button-led-border-width, 1px);
                --theme-sig-control-button-led-border-color: var(--theme-sig-control-colorpicker-picker-button-led-border-color, rgba(0, 0, 0, 0));
                --theme-sig-control-button-led-border-radius: var(--theme-sig-control-colorpicker-picker-button-led-border-radius, 5px);
                --theme-sig-control-button-led-background-color: var(--theme-sig-control-colorpicker-picker-button-led-background-color, #ccc);
                --theme-sig-control-button-led-background-image: var(--theme-sig-control-colorpicker-picker-button-led-background-image, none);
                --theme-sig-control-button-led-pressed-background-color: var(--theme-sig-control-colorpicker-picker-button-led-pressed-background-color, #070);
                --theme-sig-control-button-led-pressed-background-image: var(--theme-sig-control-colorpicker-picker-button-led-pressed-background-image, none);
                --theme-sig-control-button-led-background-size: var(--theme-sig-control-colorpicker-picker-button-led-background-size, cover);
                --theme-sig-control-button-led-background-repeat: var(--theme-sig-control-colorpicker-picker-button-led-background-repeat, no-repeat);
                --theme-sig-control-button-led-margin-height: var(--theme-sig-control-colorpicker-picker-button-led-margin-height, 3px);
                --theme-sig-control-button-led-margin-width: var(--theme-sig-control-colorpicker-picker-button-led-margin-width, 3px);
            }

            sig-control-button:last-child {
                margin-right: 0 !important;
            }

            .table-cell label {
                color: var(--theme-sig-control-colorpicker-picker-label-color, rgba(40, 50, 45, 1));
                margin-right: var(--theme-sig-control-colorpicker-picker-label-margin, 5px);
            }

            .table-cell {
                box-sizing: border-box;
                display: inline-flex;
                width: 33%;
                justify-content: flex-end;
                align-items: center;
            }
            #hexcontainer .table-cell {
                width:100%;
            }

            #canvasContainer {
                position: relative;
                width: 100%;
                top: 50%;
                transform: translateY(-50%);
            }

            #controlButtons {
                white-space: nowrap;
            }
            #colorinputs {
                margin-bottom: var(--theme-sig-control-colorpicler-picker-colorinputs-margin-bottom, 10px);
            }

            #rgbcontainer,
            #hexcontainer, 
            #hslcontainer {
                white-space: nowrap;
                display: flex;
                justify-content: flex-end;
            }
        </style>
        <div class="sig-control-colorpicker-bar clearfix">
            <div id="colorSelectArea"></div>
            <div id="colorinputs">
                <div id="rgbcontainer">
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="rgbred" type="numeric" limit-low="0" limit-high="255"></sig-control-input>
                    </div>
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="rgbgreen" type="numeric" limit-low="0" limit-high="255"></sig-control-input>
                    </div>
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="rgbblue" type="numeric" limit-low="0" limit-high="255"></sig-control-input>
                    </div>
                </div>
                <div id="hslcontainer">
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="hslhue"  type="numeric" limit-low="0" limit-high="360"></sig-control-input>
                    </div>
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="hslsaturation" type="numeric" limit-low="0" limit-high="1"></sig-control-input>
                    </div>
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="hslvalue" type="numeric" limit-low="0" limit-high="1"></sig-control-input>
                    </div>
                </div>
                <div id="hexcontainer">
                    <div class="table-cell">
                        <label></label>
                        <sig-control-input id="hex" type="hex" limit-low="0" limit-high="255"></sig-control-input>
                    </div>
                </div>
            </div>
            <div id="controlButtons">
                <sig-control-button id="OK"></sig-control-button>
                <sig-control-button id="CANCEL"></sig-control-button>
                <sig-control-button id="SHOWCOLORINPUTS"></sig-control-button>
            </div>
        </div>
    `;
    }

    /****************************************************************************************************
     * define the custom tag name
     *
     * @readonly
     * @static
     ****************************************************************************************************/
    static get is() {
        return "sig-control-colorpicker-bar";
    }

    /****************************************************************************************************
     * define the main properties of the component
     * reflected property names should always be lower case so it can be used directly on the element as an attribute
     *
     * @readonly
     * @static
     ****************************************************************************************************/
    static get properties() {
        // property names should always be lower case so we
        // can use them directly on the element as an attribute
        let props = {
            canvasheight: {
                type: String,
                value: "20",
            },
            markerwidth: {
                type: String,
                value: '20',
            },
            markerheight: {
                type: String,
                value: '20'
            },
        }
        return props;
    }

    /****************************************************************************************************
     * Called when the element has been created,
     * but before property values are set and local DOM is initialized.
     *Creates an instance of LasalRuntimeSigControlColorpickerBar.
     ****************************************************************************************************/
    constructor() {
        super();
        this.grid = null;
        this.colorinputs = null;
        this.busy = false;
        this.parent = null;
        this.canvasContext = null;
        this.marker = null;
        this.mousedown = false;

        this.queue = [];
        this.queueBusy = false;


        this.colormap = [];
        this.colorhash = {};

        this.options = {};
    }

    /****************************************************************************************************
     *Builds the bar to select the color
     *
     * @returns
     ****************************************************************************************************/
    _buildColorSelectArea() {
        const areaContainer = this.$.colorSelectArea;
        //Make sure the areaContainer is empty
        areaContainer.innerHTML = '';
        //Set the dimensions for the container
        areaContainer.style.height = this._calculateHeightForColorSelectArea() + 'px';
        areaContainer.style.width = Math.max(this.options.trackwidth, this.markerwidth) + 'px';
        areaContainer.style.paddingTop = `${this.options.areapaddingtop}px`;
        areaContainer.style.paddingBottom = `${this.options.areapaddingbottom}px`;

        //Set the colors
        this.colors = this.options.colors;
        if (this.isdesignmode) {
            this.colors = ['rgba(0,0,0,1)', 'rgba(255,255,255,1)'];
        }

        //stepSize is the space between the colors 
        //it is a value between 0 and 1
        //so basically how far along the bar should this color appear
        const stepSize = 1 / (this.colors.length - 1);

        //creating the canvas
        //_createElement is a shorthand to create elements found in the base class
        const canvas = this._createElement('canvas', 'canvas', [], {
            height: this.options.trackheight,
            width: this.options.trackwidth
        })
        this.canvasContext = canvas.getContext('2d');
        //The color gradient for the canvas
        const gradient = this.canvasContext.createLinearGradient(0, 0, this.options.trackwidth, 0);
        //Fill the gradient with colors
        for (let i = 0; i < this.colors.length; i++) {
            gradient.addColorStop('' + (i * stepSize), this.colors[i]);
        }
        //Draw the gradient on the canvas
        this.canvasContext.fillStyle = gradient;
        this.canvasContext.fillRect(0, 0, this.options.trackwidth, this.options.trackheight);

        //Create the marker element and set its dimensions
        this.marker = this._createElement('div', 'colorpickermarker1');
        this.marker.style.width = this.options.markerwidth + 'px';
        this.marker.style.height = this.options.markerheight + 'px';

        // Create a container for the canvas and the marker, and append the canvas and the marker
        const canvasContainer = this._createElement('div', 'canvasContainer', [], {}, [canvas, this.marker])
        canvasContainer.style.height = Math.max(this.options.trackheight, this.markerheight) + 'px';
        areaContainer.appendChild(canvasContainer);

        // Since the canvasContainer is created here,
        // the eventlisteners can only be added now

        this.sigAddEventListener('down', (e) => {
            this._convertGestureEventCoordsToUseableCoords(e);
            this.pointerDownHandler(e)
        }, 'polymerEvent', canvasContainer);
        this.sigAddEventListener('up', (e) => {
            this._convertGestureEventCoordsToUseableCoords(e);
            this.pointerUpHandler(e);
        }, 'polymerEvent', canvasContainer);
        this.sigAddEventListener('track', (e) => {
            this._convertGestureEventCoordsToUseableCoords(e);
            this.pointerMoveHandler(e);
        }, 'polymerEvent', canvasContainer);

        return areaContainer;


    }

    /****************************************************************************************************
      * Sig element function
     ****************************************************************************************************/
    connectedCallback() {
        super.connectedCallback();
        const canvasContainer = this.$.colorSelectArea.querySelector('#canvasContainer');
        if (!this.isdesignmode && canvasContainer) {
            this.sigAddEventListener('down', (e) => {
                this._convertGestureEventCoordsToUseableCoords(e);
                this.pointerDownHandler(e)
            }, 'polymerEvent', canvasContainer);
            this.sigAddEventListener('up', (e) => {
                this._convertGestureEventCoordsToUseableCoords(e);
                this.pointerUpHandler(e);
            }, 'polymerEvent', canvasContainer);
            this.sigAddEventListener('track', (e) => {
                this._convertGestureEventCoordsToUseableCoords(e);
                this.pointerMoveHandler(e);
            }, 'polymerEvent', canvasContainer);
        }
    }

    /****************************************************************************************************
     * Sets the marker to the position where the event occured
     * sets the input values to the new color
     * @param {*} e
     * @returns
     ****************************************************************************************************/
    _setColor(e) {
        if (!this.canvasContext) {
            return;
        }
        // Get Pos
        let pos = {};
        let x = e.offsetX;
        let y = e.offsetY

        pos.x = String(x);
        pos.y = String(y);

        if (pos.x > Number(this.options.trackwidth) || pos.x < 0) return;
        if (pos.y > Number(this.options.trackheight) || pos.y < 0) return;
        this.parent.markerpos.colorpicker1last = pos;
       // change color on click
        let colorCanv = this.canvasContext.getImageData(pos.x, pos.y, 1, 1).data.slice(0,4);
        let color = this._getRGBA(colorCanv);
        this._updateInputs(colorCanv);
       //Move Marker
        this.marker.style.transform = 'translate3d(-50%, -50%, 0)';
        this.marker.style.top = '50%';
        this.marker.style.left = pos.x + 'px';

        this.marker.style.backgroundColor = color;
    }


}
customElements.define(LasalRuntimeSigControlColorpickerBar.is, LasalRuntimeSigControlColorpickerBar);
