// 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';
//Import the colorpicker controls
import './sig-control-colorpicker-circle.js';
import './sig-control-colorpicker-area.js';
import './sig-control-colorpicker-bar.js';
import './sig-control-colorpicker-bar-area.js';
import './sig-control-colorpicker-grid.js';

import "../sig-control-button/sig-control-button.js"
import "../sig-control-input/sig-control-input.js"


/****************************************************************************************************
 * @class LasalRuntimeSigControlColorpickerInput
 * @extends {LasalRuntimeSigElement}
 ****************************************************************************************************/
export class LasalRuntimeSigControlColorpickerInput extends LasalRuntimeSigElement {
    
    /****************************************************************************************************
     * 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-color, rgba(160, 160, 160, 1));

                border-width: var(--theme-sig-control-colorpicker-border-width, 2px);
                border-color: var(--theme-sig-control-colorpicker-border-color, inherit);
                border-style: var(--theme-sig-control-colorpicker-border-style, solid);

                border-radius: var(--theme-sig-control-colorpicker-border-radius, 3px);
                /* border-top-left-radius: var(--theme-sig-control-colorpicker-border-radius-tl, var(--theme-sig-control-colorpicker-border-radius, 3px)); */
                border-top-left-radius: calc(var(--theme-sig-control-colorpicker-border-radius-tl, var(--theme-sig-control-colorpicker-border-radius, 3px)) - var(--theme-sig-control-colorpicker-border-width, 2px));
                /* border-top-right-radius: var(--theme-sig-control-colorpicker-border-radius-tr, var(--theme-sig-control-colorpicker-border-radius, 3px)); */
                border-top-right-radius: calc(var(--theme-sig-control-colorpicker-border-radius-tr, var(--theme-sig-control-colorpicker-border-radius, 3px)) - var(--theme-sig-control-colorpicker-border-width, 2px));
                /* border-bottom-right-radius: var(--theme-sig-control-colorpicker-border-radius-br, var(--theme-sig-control-colorpicker-border-radius, 3px)); */
                border-bottom-right-radius: calc(var(--theme-sig-control-colorpicker-border-radius-br, var(--theme-sig-control-colorpicker-border-radius, 3px)) - var(--theme-sig-control-colorpicker-border-width, 2px));
                /* border-bottom-left-radius: var(--theme-sig-control-colorpicker-border-radius-bl, var(--theme-sig-control-colorpicker-border-radius, 3px)); */
                border-bottom-left-radius: calc(var(--theme-sig-control-colorpicker-border-radius-bl, var(--theme-sig-control-colorpicker-border-radius, 3px)) - var(--theme-sig-control-colorpicker-border-width, 2px));


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

            :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-input {
                background-color: var(--theme-sig-control-colorpicker-background-color, inherit);
                box-sizing: border-box;
                height: 100%;
                width: 100%;
                position: relative;
            }

            #selectedcolor {
                background-color: var(--theme-sig-control-colorpicker-background-color, inherit);
                height: 100%;
                width: 100%;
                box-sizing: border-box;
                background-clip: content-box;
            }
        </style>
        <div class="sig-control-colorpicker-input">
            <div id="selectedcolor"></div>
        </div>
        `;
    }


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

    /****************************************************************************************************
     * 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() {
        let props = {
            value: {
                type: Number,
                value: 0,
                notify: true,
                observer: '_valueChanged'
            },
            showvalue: {
                type: String,
                value: 'rgba(255,255,255,1)',
                observer: '_showValueChanged'
            },
            preview: {
                type: String,
                value: 'rgba(255,255,255,1)',
                observer: '_previewChanged'
            },
            colorpickerwindow: {
                type: Object,
                value: null
            },
            colorsscheme: {
                type: String,
                value: ''
            },
            colors: {
                type: Array,
                value: () => { return [] }
            },
            type: {
                type: String,
                value: 'window'
            },
            colorpickertype: {
                type: String,
                value: 'bar-area',
                observer: '_typeChanged'
            },
            colorpickerwidth: {
                type: String,
                value: '350'
            },
            colorpickerheight: {
                type: String,
                value: '400'
            },
            markerheight: {
                type: String,
                value: '30'
            },
            markerwidth: {
                type: String,
                value: '30'
            },
            previewcolorpicker: {
                type: Boolean,
                value: false,
                observer: '_previewColorpicker'
            },
            previewcolorpickerinputs: {
                type: Boolean,
                value: false,
                observer: '_previewColorpickerInputs'
            },
            controlTexts: {
                type: Array,
                value: () => { return [] }
            },
            trackheight: {
                type: Number,
                value: 25
            },
            barpaddingtop: {
                type: Number,
                value: 10
            },
            areapaddingbottom: {
                type: Number,
                value: 10
            },
            areapaddingtop: {
                type: Number,
                value: 10
            },
            windowtop: {
                type: Number,
                value: 0
            },
            windowleft: {
                type: Number,
                value: 0
            },
            inputfont: {
                type: Object,
                value: () => { return {} },
            },
            buttonfont: {
                type: Object,
                value: () => { return {} },
            },
            labelfont: {
                type: Object,
                value: () => { return {} },
            },
            markerpos: {
                type: Object,
                value: () => { return {} }
            },
            closingcolorpicker: {
                type: Boolean,
                value: false
            },
            colorpickeropen: {
                type: Boolean,
                value: false
            },
            btnInheritBgImgFromInactive: {
                type: Boolean,
                value: true
            },
            hdrbgcolor: {
                type: String,
                value: 'rgba(11,104,182,1)',
                observer: "_typeChanged"
            },
            hdrcolor: {
                type: String,
                value: 'rgba(255,255,255,1)'
            },
            panelcontentbgcolor: {
                type: String,
                value: 'rgba(255,255,255,1)'
            },
            hdrheight:{
                type: String,
                value: ""
            },
            hdrtextalign: {
                type: String,
                value: ""
            },
            windowbordercolor: {
                type: String,
                value: ""
            },
            windowborderwidth: {
                type: String,
                value: ""
            },
            windowborderstyle: {
                type: String,
                value: ""
            },
            windowborderradius: {
                type: String,
                value: ""
            },
            windowiconsize: {
                type: String,
                value: ""
            },
            windowiconpaddinghorizontal: {
                type: String,
                value: ""
            },
            windowboxshadow: {
                type: Number,
                value: 3,
            },
            windowtitle: {
                type: String,
                value: ""
            },
            windowheaderlogo: {
                type: String,
                value: ""
            },
            showinputs: {
                type: Boolean,
                value: true
            }
        }

        return props;
    }

    /****************************************************************************************************
     *Observer for the colorpicker type
     *if it changes the current colorpicker is removed, and the renderCallback is called
     * this creates a new colorpicker of the correct type
     ****************************************************************************************************/
    _typeChanged() {
        if(this.rendered) {
            if(this.colorPicker) {
                this.colorPicker.remove();
                this.colorPicker = undefined;
            }
            if(this.colorpickerwindow) {
                this.colorpickerwindow.remove();
                this.colorpickerwindow = undefined;
            }
            this._rendered();
        }
    }

    /****************************************************************************************************
     * Called when the element has been created,
     * but before property values are set and local DOM is initialized.
     *Creates an instance of LasalRuntimeSigControlColorpickerInput.
     ****************************************************************************************************/
    constructor() {
        super();
        this.wmApi = window.sigApi.windowManager;
        this.evtMedApi = window.sigApi.eventMediator;
        this.evtApi = window.sigApi.events;
        this.textApi = window.sigApi.textManager;
        this.vmApi = window.sigApi.vm;
        this.propApi = window.sigApi.properties;

        this.colorPicker = null;

        this.controlTextList = this.getControlTextListName();;

        this.rendered = false;

        // we need to know if we have to addEventListeners or not to avoid multiple event registrations
        this.firstOpened = false;

        this.pickerProps = [
            "--theme-sig-control-colorpicker-picker-border-style",
            "--theme-sig-control-colorpicker-picker-border-width",
            "--theme-sig-control-colorpicker-picker-border-color",
            "--theme-sig-control-colorpicker-picker-border-radius",
            "--theme-sig-control-colorpicker-picker-background-color",
            "--theme-sig-control-colorpicker-picker-input-width",
            "--theme-sig-control-colorpicker-picker-input-height",
            "--theme-sig-control-colorpicker-picker-input-background-color",
            "--theme-sig-control-colorpicker-picker-input-value-active-color",
            "--theme-sig-control-colorpicker-picker-input-value-active-background-color",
            "--theme-sig-control-colorpicker-picker-input-color",
            "--theme-sig-control-colorpicker-picker-input-border-color",
            "--theme-sig-control-colorpicker-picker-input-border-width",
            "--theme-sig-control-colorpicker-picker-input-border-style",
            "--theme-sig-control-colorpicker-picker-input-border-radius",
            "--theme-sig-control-colorpicker-picker-input-activ-border-color",
            "--theme-sig-control-colorpicker-picker-input-value-text-align",
            "--theme-sig-control-colorpicker-picker-hex-input-width",
            "--theme-sig-control-colorpicker-picker-button-width",
            "--theme-sig-control-colorpicker-picker-button-height",
            "--theme-sig-control-colorpicker-picker-button-color",
            "--theme-sig-control-colorpicker-picker-button-background-color",
            "--theme-sig-control-colorpicker-picker-button-border-color",
            "--theme-sig-control-colorpicker-picker-button-border-width",
            "--theme-sig-control-colorpicker-picker-button-border-style",
            "--theme-sig-control-colorpicker-picker-button-border-radius",
            "--theme-sig-control-colorpicker-picker-button-spacing",
            "--theme-sig-control-colorpicker-picker-button-pressed-background-color",
            "--theme-sig-control-colorpicker-picker-button-pressed-color",
            "--theme-sig-control-colorpicker-picker-button-text-align",
            "--theme-sig-control-colorpicker-picker-button-vertical-align",
            "--theme-sig-control-colorpicker-picker-button-background-image",
            "--theme-sig-control-colorpicker-picker-button-background-repeat",
            "--theme-sig-control-colorpicker-picker-button-background-position-x",
            "--theme-sig-control-colorpicker-picker-button-background-position-y",
            "--theme-sig-control-colorpicker-picker-button-background-size",
            "--theme-sig-control-colorpicker-picker-button-pressed-background-image",
            "--theme-sig-control-colorpicker-picker-label-color",
            "--theme-sig-control-colorpicker-picker-label-margin",
            "--theme-sig-control-colorpicker-picker-color-grid-cell-height",
            "--theme-sig-control-colorpicker-picker-color-grid-cell-width",
            "--theme-sig-control-colorpicker-picker-grid-cell-active-border-color",
            "--theme-sig-control-colorpicker-picker-marker-border-radius"
        ];
    }

    /****************************************************************************************************
     * Observer for the value property
     * @param {*} newVal
     ****************************************************************************************************/
    _valueChanged(newVal) {
        if (typeof newVal === 'number') {
            const colorArray = [];
            let r = 0, g = 0, b = 0, a = 0;

            let calcVal = newVal;

            //Since the value is an integer
            //it we convert it here, first to variables, then to an array
            a = calcVal % 256;
            calcVal = Math.floor(calcVal / 256);
            b = calcVal % 256;
            calcVal = Math.floor(calcVal / 256);
            g = calcVal % 256;
            calcVal = Math.floor(calcVal / 256);
            r = calcVal % 256;
            calcVal = Math.floor(calcVal / 256);

            //set the showvalue
            this.showvalue = [r, g, b, a];
            //Set the preview
            this.preview = `rgba(${this.showvalue.join(',')})`;
        }
    }

    /****************************************************************************************************
     * observer for the showvalue property
     *
     * @param {*} newVal the new value for this.showValue
     * @param {*} oldVal the old value of this.showValue
     ****************************************************************************************************/
    _showValueChanged(newVal, oldVal) {
        //if the newVal isn't useable fall back to the old one
        if (newVal === undefined) {
            this.showvalue = oldVal;
        } else {
            let valStr = '';
            // Convert the array to a hex string
            for (let val of newVal) {
                let hexVal = Number(val).toString(16).trim();
                if (hexVal.length === 1) {
                    hexVal = '0' + hexVal;
                }
                valStr += hexVal;
            }
            //If no value for the opacity was set, add FF (100%)
            if (valStr.length === '6') {
                valStr += 'FF'
            }
            //convert the hex string to an integer
            this.value = parseInt(valStr, 16);
        }
    }

    /****************************************************************************************************
     * Called after property default values are set and local DOM is initialized.
     ****************************************************************************************************/
    ready() {
        super.ready();
        if (!this.isdesignmode) {
            this._addEventListeners();
            this.style.visibility = 'hidden';
        }
       
    }

    /****************************************************************************************************
     * Called when the component is disconnected from the DOM
     ****************************************************************************************************/
    disconnectedCallback() {
        super.disconnectedCallback();
        this._closeColorpicker();
        this.firstOpened = false;
    }

    /****************************************************************************************************
     * The Eventlisteners are added here
     ****************************************************************************************************/
    _addEventListeners() {

        this.sigAddEventListener('tap', (e) => {
            this._handlePointerdown(e);
        }, 'polymerEvent', this);

        this.vmApi.addRenderCallback(this, this._rendered.bind(this), this._errorRender.bind(this));

        // Bind the event mediator for language change
        this.sigAddEventListener('LANGUAGE_CHG', (majorId, minorId, msg) => {
            this._onLangChg();
        }, 'runtimeEvent');

        this.sigAddEventListener('APPROUTE_CHG', () => {
            this._closeColorpicker();
        }, 'runtimeEvent');
    }

    /****************************************************************************************************
     * Is called from the LANGUAGE_CHG listener
     * Updates the texts,
     * opens and closes the colorpicker
     ****************************************************************************************************/
    async _onLangChg() {
        try {
            await this._setControlTexts();
            //colorpicker is closed and reopened
            //because opening it sets some properties, and that is the easiest way to do so
            if (this.colorpickeropen) {
                this._closeColorpicker();
                this._openColorpicker();
            }            
        }
        catch(error) {
            this._log('_onLangChg(): failed to set control texts -> ' + error, 'ERROR');
        }

    }

    /****************************************************************************************************
     * Callback for the addRenderCallback function
     * Now the control has a useable width and height
     ****************************************************************************************************/
    _rendered() {
        //If there isn't a colorpicker, create one
        if (!this.colorPicker) {
            this.colorPicker = document.createElement('sig-control-colorpicker-' + this.colorpickertype);
            this.colorPicker.reqNames = [];
            this.colorPicker.id = `colorpicker-${parseInt(Math.random() * 1000000)}`;
            const pickerCSSText = this._getPickerCSS();
            this.colorPicker.style.cssText = pickerCSSText;
        }
        //Get the colors from the scheme
        this._getColorsFromScheme().then((res) => {
            this.colors = res;
            //init the colorpicker
            //setTimeout(this._initColorPicker.bind(this));
            this._initColorPicker();
        })

    }

    /****************************************************************************************************
     * Initializes the colorpicker
     ****************************************************************************************************/
    _initColorPicker() {
        this._setControlTexts();
        //Open to set some settings that require control bounds
        // this._openColorpicker();
        //Close again, because the colorpicker shouldn't be open on start
        // this._closeColorpicker();
        this.rendered = true;
        this.style.removeProperty('visibility');
    }

    /****************************************************************************************************
     * Error callback for the renderCallback
     ****************************************************************************************************/
    _errorRender() {
        this.vmApi.addRenderCallback(this, this._rendered.bind(this), this._errorRender.bind(this));
    }

    /****************************************************************************************************
     * Handles the pointerdown event
     * @param {*} e
     ****************************************************************************************************/
    _handlePointerdown(e) {
        this._openColorpicker();
    }
    
    /****************************************************************************************************
     * Opens the colorpicker
     ****************************************************************************************************/
    _openColorpicker() {
        switch (this.type) {
            case 'dropdown':
                this._addColorPicker();
                break;
            case 'window':
                if(this.isdesignmode) {
                    this._addColorPicker();
                }
                this._openColorPickerWindow();
                break;
        }
        this.colorpickeropen = true;
    }

    /****************************************************************************************************
     * creates the colorpicker window if not there yet
     ****************************************************************************************************/
    _openColorPickerWindow() {
        if (!this.colorpickerwindow) {
            let windowProps = {
                events: {
                    jspanelbeforeclose: () => {
                        //The event listener here is needed to reset the preview
                        if (!this.closingcolorpicker) {
                            this._closeColorpicker();
                        }

                    }
                },
                window: {
                    resizeit: false
                },
                css: {
                    '--theme-sig-window-panel-hdr-background-color': this.hdrbgcolor,
                    '--theme-sig-window-panel-content-background-color': this.panelcontentbgcolor,
                    '--theme-sig-window-panel-hdr-color': this.hdrcolor,
                    '--theme-sig-window-panel-hdr-height': this.hdrheight,
                    '--theme-sig-window-panel-hdr-text-align': this.hdrtextalign,
                    '--theme-sig-window-panel-border-color': this.windowbordercolor,
                    '--theme-sig-window-panel-border-width': this.windowborderwidth,
                    '--theme-sig-window-panel-border-style': this.windowborderstyle,
                    '--theme-sig-window-panel-border-radius': this.windowborderradius,
                    '--theme-sig-window-panel-icon-size': this.windowiconsize,
                    '--theme-sig-window-panel-icon-padding-horizontal': this.windowiconpaddinghorizontal,
                },
                window: {
                    'boxShadow': this.windowboxshadow,
                    'headerTitle': this.windowtitle,
                    'headerLogo': this.windowheaderlogo
                }
            };
            let windowId = `colorpicker-window-${parseInt(Math.random() * 1000000)}`
            //API call to create the window
            let borderWidth = parseFloat(this.windowborderwidth);
            if(isNaN(borderWidth)) {
                borderWidth = 0;
            }
            const windowWidth = parseFloat(this.colorpickerwidth) + 2 * borderWidth;
            const windowHeight = parseFloat(this.colorpickerheight) + 2 * borderWidth;
            this.wmApi.createWindow(this.windowtop, this.windowleft, windowWidth, windowHeight, (win) => {

                this.colorpickerwindow = win;
                //disable resizing
                this.colorpickerwindow.resizeit('disable');
                this.colorpickerwindow.style.transform = `rotate(${this.rotation}deg)`
                //Add the colorpicker to the window
                this._addColorPickerToContainer(this.colorpickerwindow.content);
            }, windowProps, windowId);
        } else {
            if(this.type == 'window' && this.context.type == 'window'){
                const container = document.querySelector(`#${this.context.instanceId}`);
                const containerZIdx = container.style.zIndex;
                this.colorpickerwindow.style.zIndex = containerZIdx + 1;
            }
            //open the window
            this.colorpickerwindow.open();
            //add the colorpicker to the window
            this._addColorPickerToContainer(this.colorpickerwindow.content)
        }
    }

    /****************************************************************************************************
     * Closes the colorpicker
     ****************************************************************************************************/
    _closeColorpicker() {
        if (this.isdesignmode) {

        } else if (!this.showvalue || !this.showvalue.join) {
            this.preview = this.showvalue;
        } else {
            this.preview = `rgba(${this.showvalue.join(',')})`;
        }

        //variable needed otherwise the jspanelbeforeclose event listener is called in an endless loop
        this.closingcolorpicker = true;
        if (this.type === 'dropdown' && this.colorPicker) {
            this.colorPicker.style.display = 'none';
        } else if (this.type === 'window' && !this.isdesignmode && this.colorpickerwindow !== null) {
            this.colorpickerwindow.close();
        }
        this.closingcolorpicker = false;
        this.colorpickeropen = false;
        if(this.isdesignmode && this.colorPicker) {
            this.colorPicker.parentElement.removeChild(this.colorPicker);
            this.colorPicker = undefined;
        }
    }

    /****************************************************************************************************
     * Adds a color Picker
     ****************************************************************************************************/
    _addColorPicker() {

        let container;
       
        // Find out if we are in a window or dashboard
        if (!this.isdesignmode) {
            switch (this.context.type) {
                case 'window':
                    // container = document.querySelector(`#${this.context.instanceId} .${this.windowContainerClass}`);
                    container = document.querySelector(`#${this.context.instanceId}`);
                    break;
                case 'dashboard':
                    container = document.getElementsByTagName('sig-app')[0];
                    break;
                default:
                    this._log(`Unspported context type "${this.context.type}"`, 'ERROR');
                    break;
            }
        } else { // In designmode we never run inside a window
            container = document.getElementsByTagName('sig-app')[0];
        }
        //Add the colorpicker to the container
        this._addColorPickerToContainer(container);

    }


    /**
     
     * */
    /****************************************************************************************************
     * Adds the colorpicker to a container
     * (either the dropdown menu or the window)
     * @param {*} container - the container to which the colorpicler should be added
     * @returns
     ****************************************************************************************************/
    _addColorPickerToContainer(container) {
        if (container instanceof HTMLElement) {
            if (this.isdesignmode) {
                if (!this.colorPicker) {
                    this.colorPicker = document.createElement('sig-control-colorpicker-' + this.colorpickertype);
                    this.colorPicker.id = `colorpicker-${parseInt(Math.random() * 1000000)}`;
                }
            }

            if (this.type === 'dropdown') {
                this.colorPicker.rotation = this.rotation;
            }
            //Adds the colorpicker to the container
            // if(!(container.querySelector(this.colorPicker.tagName)  instanceof HTMLElement) || this.type === 'dropdown') {
            if(!(document.getElementById(this.colorPicker.id) instanceof HTMLElement)) {
                this.firstOpened = true;
                container.appendChild(this.colorPicker);
                this.colorPicker.parent = this;
            }else{
                this.firstOpened = false;
            }

            //Show the colorpicker
            this._showColorpicker();
            return true;
        } else {
            this._log(`Could not find container to add list for "${this.id}"`, 'ERROR');
            return false;
        }
    }

    /****************************************************************************************************
     * Shows the colorpicker
     ****************************************************************************************************/
    async _showColorpicker() {
        try {
            await this._setControlTexts();
            if ((this.colorPicker !== null) && (this.colorPicker !== undefined)) {
                this.colorPicker._show(
                    {
                        parent: this,
                        width: this.colorpickerwidth,
                        height: this.colorpickerheight,
                        markerwidth: this.markerwidth,
                        markerheight: this.markerheight,
                        trackwidth: this.colorpickerwidth * 0.95,
                        trackheight: this.trackheight,
                        controlTexts: this.controlTexts,
                        type: this.isdesignmode ? 'dropdown' : this.type,
                        buttonfont: this.buttonfont,
                        labelfont: this.labelfont,
                        inputfont: this.inputfont,
                        barpaddingtop: this.barpaddingtop,
                        areapaddingbottom: this.areapaddingbottom,
                        areapaddingtop: this.areapaddingtop,
                        colors: this.colors,
                        btnInheritBgImgFromInactive: this.btnInheritBgImgFromInactive,
                        firstOpened: this.firstOpened,
                        showInputs: this.showinputs
                    }
                ); 
            }    
        }
        catch(error) {
            this._log('_showColorpicker(): failed to set control texts -> ' + error, 'ERROR');
        }
    }

    /**
     
     * */
    /****************************************************************************************************
     * Observer for the preview property
     * The preview property is the color that is shown on the colorpicker input
     * @param {*} newVal
     * @param {*} oldVal
     * @returns
     ****************************************************************************************************/
    _previewChanged(newVal, oldVal) {
        if (this.isdesignmode) {
            return;
        }
        if (newVal === undefined) {
            this.preview = oldVal;
        } else {
            this.$.selectedcolor.style.backgroundColor = newVal;
        }

    }

    /****************************************************************************************************
     * Shows the colorpicker in the design mode
     * @returns
     ****************************************************************************************************/
    _previewColorpicker() {
        if (!this.isdesignmode) {
            return;
        }
        if (this.previewcolorpicker) {
            this._openColorpicker();
            if(this.previewcolorpickerinputs) {
                this._previewColorpickerInputs();
            }
            this.colorPicker.style.setProperty('z-index', 1000);
        } else {
            this._closeColorpicker();
        }
    }

    /****************************************************************************************************
     * Another preview in the design mode,
     * this time the inputs are shown as well
     * @returns
     ****************************************************************************************************/
    _previewColorpickerInputs() {
        if (!this.isdesignmode || !(this.colorPicker instanceof HTMLElement)) {
            return;
        }
        if (!this.previewcolorpicker) {
            return;
        }
        if (this.previewcolorpickerinputs) {
            this.colorPicker.$.colorinputs.classList.remove('hidden');
            this.colorPicker._setControlPosition();
        } else {
            this.colorPicker.$.colorinputs.classList.add('hidden');
            this.colorPicker._setControlPosition();
        }
    }

    /****************************************************************************************************
     * Gets the Control Texts from the controlTexts_sig_conrol_colorpicker textlist
     * @returns
     ****************************************************************************************************/
    async _setControlTexts() {
        try {
            //get control textlist
            const texts = await this.textApi.getTextsAsync(this._getTextsObject()); 
            this.controlTexts = texts[this.controlTextList];            
        }
        catch(error) {
            this._log('_setControlTexts(): failed to get textlist -> ' + error, 'ERROR');
        }
    }

    /****************************************************************************************************
     * method is used to get the textobject for default texts
     *
     * @memberof LasalRuntimeSigControlColorpickerInput
     ****************************************************************************************************/
    _getTextsObject() {
        return {
            [this.controlTextList]: {
                Ok: "Ok",
                Cancel: "Cancel",
                Inputs: "Inputs",
                rgbred: "R",
                rgbgreen: "G",
                rgbblue: "B",
                hex: "HEX #",
                hslhue: "H",
                hslsaturation: "S",
                hslvalue: "V",
            }
        }
    }

    /****************************************************************************************************
     * Gets the colors from a color scheme
     * @returns
     ****************************************************************************************************/
    async _getColorsFromScheme() {
        let color = '';
        let colors = [];
        if (this.isdesignmode) {
            return ['rgba(0,0,0,1)', 'rgba(255,255,255,1)'];
        }
        try {
            //get the data for the color scheme
            const propArray = await this.propApi.getSchemeDataWithProperty(this.id, 'colorsscheme');
            //map so that we only have the value - which is all we need
            colors = propArray.map((val) => {
                return val.value;
            });
        } catch (error) {
            this._log('No Scheme Found!');
        }

        //If no scheme was added, just display a lot of colors
        if (colors.length === 0) {
            colors = [
                'rgba(0,0,0,1)',
                'rgba(255,0,0,1)',
                'rgba(255,255,0,1)',
                'rgba(0,255,0,1)',
                'rgba(0,255,255,1)',
                'rgba(0,0,255,1)',
                'rgba(255,0,255,1)',
                'rgba(255,255,255,1)',
            ]
        }
        return colors;
    }

    /****************************************************************************************************
     * called when css variables are updated
     * updates the wrapper variables
     *
     * @param {*} cssObj
     * @param {boolean} [doBoundsCheck=false]
     ****************************************************************************************************/
     sigApplyCSSValue(cssObj, doBoundsCheck = false) {
        super.sigApplyCSSValue(cssObj, doBoundsCheck);
    
        if(this.colorPicker) {
            let pickerCSSText = this._getPickerCSS();
            // Filter for inline styles that werent set via getPickerCSS()
            //They need to be added for correct positioning of the control
            const currentPickerCss = this.colorPicker.style.cssText;
            const currentPickerCssArr = currentPickerCss.split(';');
            const additionalPickerCss = currentPickerCssArr.filter((val) => {
                const trimmedVal = val.trim()
                return trimmedVal.indexOf('--theme-sig-control-') === -1;
            })
            pickerCSSText += ';' +  additionalPickerCss.join(';');
            this.colorPicker.style.cssText = pickerCSSText;
        }
    }

    /****************************************************************************************************
     * Parses the CSS that is meant for the wrapper out of the css of the component
     * @returns
     ****************************************************************************************************/
    _getPickerCSS() {
        if (!this.colorPicker) {
            return '';
        }
        const cs = getComputedStyle(this);
        let style = [];
        for(let prop of this.pickerProps) {
            //get property value
            const propVal = cs.getPropertyValue(prop);
            if (propVal) {
                style.push(prop + ':' + propVal);
            }
        }
        return style.join(';')
    }

    /****************************************************************************************************
     * Called by the Designer Runtime when the project language changes.
     * @param {Object} language The definition object of the current language.
     * @return {Undefined} Undefined 
     * @memberof LasalRuntimeSigControlFilemanager
     ****************************************************************************************************/
     designerOnLanguageChanged() {
        this._showColorpicker();
    }

    /****************************************************************************************************
     * Called by the Designer Runtime if the ObjectStore has been updated.
     * @async
     * @param {Object} data The payload of the ObjectStore command which triggered the update.
     * @return {Promise} Returns a Promise, which is resolved after the Textlist update is complete.
     * @memberof LasalRuntimeSigControlFilemanager
     ****************************************************************************************************/
    async designerOnObjectStoreUpdate(data) {
        const textListChanged = await this.textApi.isTextListUpdate(data, this.controlTextList);
        if (textListChanged) this._showColorpicker();
    }    
}
customElements.define(LasalRuntimeSigControlColorpickerInput.is, LasalRuntimeSigControlColorpickerInput)
