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

export class LasalRuntimeSigControlUserInfo extends LasalRuntimeSigElement {

    static get is() {
        return "sig-control-user-info";
    }

    static get importMeta() { return import.meta; }

    static get template() {
        return SigPolymer.html`
        <style include="sig-element-css sig-control-scrollbar-css">
            :host {
                
                color: var(--theme-sig-control-user-info-color, inherit);
                background-color: var(--theme-sig-control-user-info-background-color, transparent);
                border-width: var(--theme-sig-control-user-info-border-width, 0px);
                border-color: var(--theme-sig-control-user-info-border-color, transparent);
                border-style: var(--theme-sig-control-user-info-border-style, none);
                border-radius: var(--theme-sig-control-user-info-border-radius, 0px);

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

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

            .clearfix:after {
                @apply --clearfix
            }

            .sig-user-info {
                
                display: table;
                width: 100%;
                height: 100%;
                text-decoration: inherit;
                cursor: pointer;
            }

            .sig-user-info div.content {
                
                display: table-cell;
                text-align: var(--theme-sig-control-user-info-value-align, center);
                vertical-align: var(--theme-sig-control-user-info-value-vertical-align, middle);
                text-decoration: inherit;
            }
        </style>
        <div class="sig-user-info clearfix" on-tap="_opendialog">
            <div id="value" class="content">[[cvalue]]</div>
        </div>
        `
    }

    static get properties() {
        let props = {
            cvalue: {
                type: String,
                value: '',
                computed: '_valueChanged(value, defaulttext, texts, isloggedin)'
            }
        }
        return props;
    }

    constructor() {
        super();
        this.sigAddRequiredProperty('value');
        this.controlTextList = this.getControlTextListName();
        this.wmApi = window.sigApi.windowManager;
        this.umApi = window.sigApi.userManager;
        this.evtmApi = window.sigApi.eventMediator;
        this.evtsApi = window.sigApi.events;
        this.arApi = window.sigApi.appRouter;
        this.tmApi = window.sigApi.textManager;
        this.utilsApi = window.sigApi.sigUtils;
        this.value = '';
        this.defaulttext = '';
        this.isloggedin = false;
        this.texts = this._getTextsObject()[this.controlTextList];


        if (!this.isdesignmode && this.evtmApi && this.evtsApi) {

            this.sigAddEventListener('LANGUAGE_CHG', (majorId, minorId, msg) => {
                this._switchLang(majorId, minorId, msg);
            }, 'runtimeEvent');

            this.sigAddEventListener('USER_LOGGED_IN', (majorId, minorId, msg) => {
                this._userLoggedIn(majorId, minorId, msg);
            }, 'runtimeEvent');

            this.sigAddEventListener('USER_LOGGED_OUT', (majorId, minorId, msg) => {
                this._userLoggedOut(majorId, minorId, msg);
            }, 'runtimeEvent');
        }
        if (this.umApi) {
            this.isloggedin = this.umApi.isUserLoggedIn();
        }
    }

    disconnectedCallback() {
        super.disconnectedCallback();
        this.wmApi = null;
        this.umApi = null;
        this.evtmApi = null;
        this.evtsApi = null
        this.arApi = null;
        this.tmApi = null;
        this.utilsApi = null;
        this.texts = null;
    }

    ready() {
        super.ready();
        SigPolymer.afterNextRender(this, function () {
            this._init();
        });

    }

    _init() {
        this._switchLang();
    }

    _valueChanged(value, defaulttext, texts, isloggedin) {
        if (value !== undefined && defaulttext !== undefined && texts !== null && Object.keys(texts).length > 0 && isloggedin !== undefined) {
            if (isloggedin) {
                return (value !== '') ? value : this.texts.loggedOn;
            } else {
                return (defaulttext !== '') ? defaulttext : this.texts.loggedOut;
            }
        }
    }

    _opendialog() {
        const uid = this.utilsApi.getUID();
        this.umApi.getActiveUser(uid)
            .then((result) => {
                if (result.user) {
                    if (this.detailtarget !== undefined) {
                        const _targetroute = this.arApi.getRoutesByInstanceID(this.detailtarget);
                        if (_targetroute && _targetroute[0]) this.arApi.navigate(_targetroute[0].path);
                        else this.arApi.navigate(this.detailtarget);
                    }
                    if (this.detailwindow !== undefined) { this._openWindow(this.detailwindow); }
                    this.evtmApi.publish(this.evtsApi.getInternalEvent('SEND_USER_DATA'), { type: 'user', source: this.id, target: this._getTargetList(), data: { mode: 'view', user: result.user } });
                }
            })
            .catch(error => {
                if (error.status === 1) {
                    if (this.logintarget !== undefined) { this.arApi.navigate(this.logintarget); }
                    if (this.loginwindow !== undefined) { this._openWindow(this.loginwindow); }
                } else {
                    this._log(error);
                }
            });
    }

    async _openWindow(window) {
        if (this.disconnected) return;
        await this.wmApi.openWindow(window);
    }

    _getTargetList() {
        if (this.detailcontrolid) {
            return this.detailcontrolid.split(',').map(item => item.trim());
        }
        return null;
    }

    _userLoggedIn(majorId, minorId, msg) {
        this.isloggedin = true;
        this._log('User logged in');
    }

    _userLoggedOut(majorId, minorId, msg) {
        this.isloggedin = false;
        this._log('User logged out');
    }

    async _switchLang(majorId, minorId, msg) {
        if (this.tmApi) {
            const texts = await this.tmApi.getTextsAsync(this._getTextsObject());
            this.texts = texts[this.controlTextList];
        }
    }

    designerOnLanguageChanged() {
        this._switchLang();
    }

    async designerOnObjectStoreUpdate(data) {
        const textListChanged = await this.tmApi.isTextListUpdate(data, this.controlTextList);
        if (textListChanged) this._switchLang();
    }

    _getTextsObject() {
        return {
            [this.controlTextList]: {
                loggedOn: 'Your are logged on',
                loggedOut: 'You are not logged on'
            }
        }
    }
}
customElements.define(LasalRuntimeSigControlUserInfo.is, LasalRuntimeSigControlUserInfo);