import { LasalRuntimeSigElement, SigPolymer } from '../../sigmatek/sig-element/sig-element.js';

class LasalRuntimeSigHotAlarmImage 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
     ****************************************************************************************************/
    static get importMeta() {
        return import.meta;
    }

    /****************************************************************************************************
     * Return the component style and template as a template literal
     ****************************************************************************************************/
    static get template() {
        return SigPolymer.html`
        <style include="sig-element-css">
            :host {
                border-width: var(--theme-sig-control-hotalarm-image-border-width, 0px);
                border-color: var(--theme-sig-control-hotalarm-image-border-color, --palette-default-color253);
                border-style: var(--theme-sig-control-hotalarm-image-border-style, solid);
                border-radius: var(--theme-sig-control-hotalarm-image-border-radius, 20px);
                border-top-left-radius: var(--theme-sig-control-hotalarm-image-border-radius-top-left, var(--theme-sig-control-hotalarm-image-border-radius, 20px));
                border-bottom-left-radius: var(--theme-sig-control-hotalarm-image-border-radius-bottom-left, var(--theme-sig-control-hotalarm-image-border-radius, 20px));
                border-top-right-radius: var(--theme-sig-control-hotalarm-image-border-radius-top-right, var(--theme-sig-control-hotalarm-image-border-radius, 20px));
                border-bottom-right-radius: var(--theme-sig-control-hotalarm-image-border-radius-bottom-right, var(--theme-sig-control-hotalarm-image-border-radius, 20px));

                display: block;
                position: absolute;
                overflow: hidden;
            }

            :host * {
                @apply --notextselect;
                margin: 0;
                padding: 0;
            }

            .clearfix:after {
                @apply --clearfix
            }

            .sig-control-hotalarm-image {
                color: inherit;
                width: 100%;
                height: 100%;
                position: relative;     
            }
            
            #statealarminactive {
                background-color: var(--theme-sig-control-hotalarm-image-background-color, inherit);
                border: none;
                border-radius: 0px;
            }

            #statealarmactive {
                background-color: var(--theme-sig-control-hotalarm-image-pressed-background-color, inherit);
                border: none;
                border-radius: 0px;
            }

            .statealarm {
                background-repeat: no-repeat;
                vertical-align: var(--theme-sig-control-hotalarm-image-vertical-align, middle);
                width: 100%;
                height: 100%;
            }
            
            :host(:not([statealarm="0"])) #statealarminactive {
                display: none;
            }

            :host([statealarm="0"]) #statealarmactive    {
                display: none;
            }

            .statealarm img {
                height: 100%;
                width: 100%;
                object-fit: var(--theme-sig-control-hotalarm-image-background-size, contain);
                object-position: var(--theme-sig-control-hotalarm-image-background-position-y, center) var(--theme-sig-control-hotalarm-image-background-position-x, center);
                
                padding-left: var(--theme-sig-control-hotalarm-image-padding-left, 3px);
                padding-top: var(--theme-sig-control-hotalarm-image-padding-top, 3px);
                padding-right: var(--theme-sig-control-hotalarm-image-padding-right, 3px);
                padding-bottom: var(--theme-sig-control-hotalarm-image-padding-bottom, 3px);
                box-sizing: border-box;
            }

        </style>
        <div class="sig-control-hotalarm-image clearfix" on-tap="_handleTap">
            <div id="statealarmactive" class="statealarm"></div>
            <div id="statealarminactive" class="statealarm"></div>
        </div>
        `;
    }

    /****************************************************************************************************
     * define the custom tag name 
     ****************************************************************************************************/
    static get is() {
        return "sig-control-hotalarm-image";
    }


    /****************************************************************************************************
     * define the main porperties of the component
     * reflected property names should always be lower case so it can be used directly on the element as an attribute
     ****************************************************************************************************/
    static get properties() {
        let props = {
            statealarm: {
                type: Number,
                value: 0,
                reflectToAttribute: true
            },
            blinkinterval: {
                type: Number,
                value: 500,
                observer: "_HandleState"
            },
            previewstate: {
                type: String,
                value: "inactive",
                reflectToAttribute: false,
                observer: '_getHotAlarmDesigner'
            },
            bgimg: {
                type: String,
                value: 'none',
                observer: '_setBgImages'
            },
            bgimgpressed: {
                type: String,
                value: 'inherit',
                observer: '_setBgImages'
            }
        }
        return props;
    }


    /****************************************************************************************************
     * called when the element has been created, but before property values are set and local DOM is initialized
     ****************************************************************************************************/
    constructor() {
        super();

        this.intervalHandle = undefined;
        this.hotAlarmActive = false;
        this.evtMedApi = undefined;
        this.journalApi = undefined;
        this.APIsReady = false;
        this.eventIdEventJounalChanged = null;
        this.defaultimg = `${this.importPath}hotalarm-image-default.svg`;
        this.defaultimgdesigner = `${this.importPath}hotalarm-image-default.svg`
    }


    /****************************************************************************************************
     * called after the element is attached to the document
     * can be called multiple times during the lifetime of an element
     * the first attached callback is guaranteed not to fire until after ready
     ****************************************************************************************************/
    connectedCallback() {
        super.connectedCallback();

        SigPolymer.beforeNextRender(this, function (params) {
            if (!this.isdesignmode) {
                this.evtMedApi = window.sigApi.eventMediator;
                this.evtApi = window.sigApi.events;
                this.journalApi = window.sigApi.eventJournal;
                this.alarmApi = window.sigApi.alarm;
                this.APIsReady = true;
                this._registerEvents();
            }
            this._init();
        });
    }


    /****************************************************************************************************
     * called after the element is detached from the DOM
     * can be called multiple times during the lifetime of an element
     *use this to cleanup your "mess" ;-)
     ****************************************************************************************************/
    disconnectedCallback() {
        super.disconnectedCallback();
    }

    /****************************************************************************************************
     * register all needed events
     ****************************************************************************************************/
    _registerEvents() {
        if (!this.isdesignmode) {
            //register for the hotalarm update
            this.alarmApi.registerHotAlarmUpdate(0b0001);

            this.sigAddEventListener('TEMP_ALARM_MGR_HOTALARM_STATE_CHG', () => {
                this._getHotAlarm();
            }, 'runtimeEvent');
        }
    }

    /****************************************************************************************************
     * initialize the component.
     ****************************************************************************************************/
    _init() {
        this._setBgImages();
        if (!this.isdesignmode) {
            this._getHotAlarm();
        }
        else {
            this._getHotAlarmDesigner();
        }
    }

    /****************************************************************************************************
     * sets the images for the alarms active and inative state
     ****************************************************************************************************/
    _setBgImages() {
        const hasBgImg = this.bgimg !== undefined && this.bgimg !== 'none';
        const hasBgImgPressed = this.bgimgpressed !== undefined && this.bgimgpressed !== 'none';

        //if no image is set, use the default
        if (hasBgImg) {
            this._setImage('statealarminactive', this.bgimg);
        } else {
            if (this.isdesignmode) {
                this._setImage('statealarminactive', this.defaultimgdesigner);
            } else {
                this._setImage('statealarminactive', this.defaultimg);
            }

        }

        if (this.bgimgpressed === 'inherit' && hasBgImg) {
            this._setImage('statealarmactive', this.bgimg)
        } else if (hasBgImgPressed && this.bgimgpressed !== 'inherit') {
            this._setImage('statealarmactive', this.bgimgpressed)
        } else {
            if (this.isdesignmode) {
                this._setImage('statealarmactive', this.defaultimgdesigner);
            } else {
                this._setImage('statealarmactive', this.defaultimg);
            }
        }


    }

    /****************************************************************************************************
     * sets the image for a specific state
     * by creating an img tag, and appending that to the specified parent element
     * 
     * @param {HTMLElement} element the element to which the image should be appended
     * @param {String} src the url to the image
     ****************************************************************************************************/
    _setImage(element, src) {
        //make sure there is nothing inside the element we want to appen the image to
        this.$[element].innerHTML = '';

        //create the img tag element
        const img = document.createElement('img');
        img.src = src;
        this.$[element].appendChild(img);

    }

    /****************************************************************************************************
     * check if a hot alarm is available ( not for Designer )
     ****************************************************************************************************/
    _getHotAlarm() {
        if (this.APIsReady === true) {
            let hotAlarm;
            //hotAlarm = this.journalApi.getHOTAlarmPrio();
            hotAlarm = this.alarmApi.getHotAlarm(0b0001);
            if (hotAlarm && hotAlarm.getState() > 0 && hotAlarm.getState() < 255) {
                this.hotAlarmActive = true;
            }
            else {
                this.hotAlarmActive = false;
            }
            this._HandleState();
        }

    }
 
    /****************************************************************************************************
     * simulation values for designer
     ****************************************************************************************************/
    _getHotAlarmDesigner() {
        if (this.isdesignmode) {
            switch (this.previewstate) {
                case 'inactive':
                    this.hotAlarmActive = false;
                    break;

                case 'active':
                    this.hotAlarmActive = true;
                    break;

                default:
                    this.hotAlarmActive = false;
                    break;
            }

            this._HandleState();
        }

    }
 
    /****************************************************************************************************
     * Handles the state of the alarm image (inactive, active, blink)
     ****************************************************************************************************/
    _HandleState() {
        if (this.intervalHandle !== undefined) {
            this.sigClearInterval(this.intervalHandle);
            this.intervalHandle = undefined;
        }

        if (this.hotAlarmActive) {
            if (this.blinkinterval != 0) {
                this.statealarm = 1;
                this.intervalHandle = this.sigSetInterval(() => { this._toggleState(); }, this.blinkinterval);
            }
            else {
                this.statealarm = 1;
            }
        }
        else {
            this.statealarm = 0;
        }

    }
 
    /****************************************************************************************************
     * Toggles the state of the alarm image
     ****************************************************************************************************/
    _toggleState() {
        this.statealarm = this.statealarm ^ 1;
    }

    /****************************************************************************************************
     * handles the tap event on the div 
     ****************************************************************************************************/
     _handleTap(e) {

        if (!this.isdesignmode) {
            e.preventDefault();
            this._dispatchEvent('mousedown');
        }

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