import { LasalRuntimeSigElement, SigPolymer } from '../../sigmatek/sig-element/sig-element.js';
import { Usermanager } from '../sig-control-user-mixin/sig-control-user-mixin.js';
import "../sig-control-input/sig-control-input.js";
import "../sig-control-button/sig-control-button.js";
import "../sig-control-listview/sig-control-listview.js";
import "../sig-control-titlebar/sig-control-titlebar.js";
import '../sig-control-input/sig-control-input-css.js';
import '../sig-control-button/sig-control-button-css.js';
import '../sig-control-listview/sig-control-listview-css.js';
import '../sig-control-titlebar/sig-control-titlebar-css.js';
import '../sig-control-scrollbar/sig-control-scrollbar-css.js';

export class LasalRuntimeSigControlUserLogin extends Usermanager(LasalRuntimeSigElement) {

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

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

    static get template() {
        return SigPolymer.html`
            <style
                include="sig-element-css sig-control-input-css sig-control-button-css sig-control-listview-css sig-control-titlebar-css sig-control-scrollbar-css">
                :host {
                    
                    color: var(--theme-sig-control-user-login-color, rgba(255, 255, 255, 1));
                    background-color: var(--theme-sig-control-user-login-background-color, rgba(42, 42, 42, 1));

                    border-width: var(--theme-sig-control-user-login-border-width, 0);
                    border-color: var(--theme-sig-control-user-login-border-color, transparent);
                    border-style: var(--theme-sig-control-user-login-border-style, none);
                    border-radius: var(--theme-sig-control-user-login-border-radius, 0);

                    
                    display: block;
                    position: absolute;
                    overflow: var(--theme-sig-control-user-login-overflow, hidden);
                }

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

                .clearfix:after {
                    
                    @apply --clearfix
                }

                .sig-control-user-login {
                    
                    position: relative;
                    width: 100%;
                    height: 100%;
                    
                    text-decoration: inherit;
                }

                .content {
                    display: flex;
                    flex-flow: column;
                    align-items: stretch;
                    height: 100%;
                    min-height: 100%;
                    background-color: var(--theme-sig-control-user-login-background-color, rgba(42, 42, 42, 1));
                }

                .inner {
                    display: flex;
                    flex-flow: column;
                    align-items: stretch;
                    height: 100%;
                }

                .inputs {
                    flex: 0 1 auto;
                    height: auto;
                }

                .input {
                    height: 30px;
                    width: 100%;
                    position: unset;
                    margin-bottom: 10px !important;
                }

                .input.last {
                    margin-bottom: 0;
                }

                .buttons {
                    clear: both;
                    border-top: 1px solid var(--theme-sig-control-user-login-button-horizontal-separator-color, rgba(86, 89, 97, 1));
                    height: auto;
                    padding: 0 10px !important;
                }

                .button {
                    position: unset;
                }

                .button.default {
                    margin:10px 0;
                }

                .button.right {
                    margin-left:10px;
                    float: right;
                }

                .button.left {
                    margin-right: 10px;
                    float: left;
                }

                .users {
                    
                    flex: 1 1 100%;
                    position: relative;
                    min-height: 45px;
                    overflow: auto;
                }

                .userlist {
                    top: 0;
                    left: 0;
                    
                    min-width: 100%;
                    width: 100%;
                    min-height: 100%;
                    height: 100%;
                }

                .label {
                    height: auto;
                    display: block;
                    font-size: var(--theme-sig-control-user-login-label-font-size, 11px);
                    color: var(--theme-sig-control-user-login-label-color, rgba(215, 215, 215, 1));
                    text-align: left;
                }

                .content {
                    display: flex;
                    flex-flow: column;
                    align-items: stretch;
                    height: 100%;
                    background-color: var(--theme-sig-control-user-login-background-color, rgba(42, 42, 42, 1));
                }

                .form {
                    overflow: auto;
                    margin: 10px 10px !important;
                    flex: 1 1 100%;
                    width: calc(100% - 20px);
                    height: 100%;
                }

                .inner {
                    display: flex;
                    flex-flow: column;
                    align-items: stretch;
                    height: 100%;
                }

                .title {
                    height: auto;
                    flex: 0 1 auto;
                }

                .clear {
                    clear: both;
                    height: auto;
                }

                :host([hidebuttons]) .buttons,
                :host([hidetitle]) .title,
                :host([hideuserlist]) .users,
                :host([hideinputs]) .inputs,
                :host([hidelabels]) .label,
                :host([hideuserlist]) label.list {
                    display: none;
                }

                :host sig-control-button {
                    height: var(--theme-sig-element-height, 40px);
                    width: var(--theme-sig-element-width, 90px);
                    
                    --theme-sig-control-button-padding: 2px;
                }

                :host sig-control-input {

                    height: var(--theme-sig-element-height, 26px);
                    
                    --theme-sig-control-input-placeholder-color: var(--theme-sig-control-user-login-input-placeholder-color, rgba(142, 142, 142, 1));
                    --theme-sig-control-input-field-position: relative;
                }

                :host sig-control-titlebar {
                    position: unset;
                    display: block;
                    height: var(--theme-sig-element-height, 26px);
                    width:100%;
                }

                :host sig-control-listview {

                    position: unset;
                }
            </style>
            <div class="sig-control-user-login clearfix">
                <div class="content">
                    <div class="content">
                        <div class="title">
                            <sig-control-titlebar id="titlebar" value="[[texts.caption]]"
                                shadowactive="[[titlebarshadowactive]]" applybordereffect="[[applybordereffect]]">
                            </sig-control-titlebar>
                        </div>
                        <div class="form">
                            <div class="inner">
                                <div class="inputs">
                                    <label class="label">[[texts.username]]</label>
                                    <sig-control-input id="username" value="{{username}}" class="input default" placeholder="[[texts.username]]"
                                        titletext="[[texts.enterUsername]]" shadowactive="[[inputfieldshadowactive]]"
                                        shadowpressedactive="[[inputfieldshadowactive]]">
                                    </sig-control-input>
                                    <label class="label">[[texts.password]]</label>
                                    <sig-control-input id="password" class="input default" ispassword
                                        placeholder="[[texts.password]]" titletext="[[texts.enterPassword]] [[usernamec]]"
                                        shadowactive="[[inputfieldshadowactive]]"
                                        shadowpressedactive="[[inputfieldshadowactive]]">
                                    </sig-control-input>
                                </div>
                                <div>
                                    <label class=" label list">[[texts.users]]</label>
                                </div>
                                <div id="users" class="users">
                                    <sig-control-listview id="listview" class="userlist"></sig-control-listview>
                                </div>
                            </div>
                        </div>

                        <div class="buttons clearfix">
                            <sig-control-button id="login" sigbtntext=[[texts.login]] class="button default right"
                                on-up="_login"></sig-control-button>
                            <template is="dom-if" if="[[_showButtons(isloggedin)]]">
                                <sig-control-button id="logout" sigbtntext=[[texts.logout]] class="button default left"
                                    on-up="_logout"></sig-control-button>
                            </template>
                            <template is="dom-if" if="[[_showButtons(iswindow)]]">
                                <sig-control-button id="close" sigbtntext=[[texts.close]] class="button default left"
                                    on-up="_closeWindow"></sig-control-button>
                            </template>
                        </div>
                    </div>
                </div>
                `
    }

    static get properties() {
        let props = {
            hidetitle: {
                type: Boolean,
                value: false,
                reflectToAttribute: true,
                observer: '_updateLayout'
            },
            hideinputs: {
                type: Boolean,
                value: false,
                reflectToAttribute: true,
                observer: '_updateLayout'
            },
            hideuserlist: {
                type: Boolean,
                value: false,
                reflectToAttribute: true,
                observer: '_updateLayout'
            },
            hidebuttons: {
                type: Boolean,
                value: false,
                reflectToAttribute: true,
                observer: '_updateLayout'
            },
            hidelabels: {
                type: Boolean,
                value: false,
                reflectToAttribute: true,
                observer: '_updateLayout'
            },
            inputfieldshadowactive: {
                type: Boolean,
                value: false,
                reflectToAttribute: true
            },
            titlebarshadowactive: {
                type: Boolean,
                value: false,
                reflectToAttribute: true
            },
            titletext: {
                type: String,
                value: '',
                observer: '_switchLang'
            },
            username: {
                type: String,
                observer: '_usernameChanged'
            },
            loginonpasswordsubmit: {
                type: Boolean,
                value: false,
                observer: '_loginWayChanged'
            }
        }
        return props;
    }

    constructor() {
        super();
        this.umApi = window.sigApi.userManager;
        this.wmApi = window.sigApi.windowManager;
        this.tmApi = window.sigApi.textManager;
        this.arApi = window.sigApi.appRouter;
        this.utilsApi = window.sigApi.sigUtils;
        this.iswindow = false;
        this.isloggedin = false;
        this.data = null;
        this.config = null;
        this.closeafterlogout = false;
        this.closeafterlogin = false;
        this.applybordereffect = false;
        this.texts = {};

        this.loginFunction = () => this._login();
        this.controlTextList = this.getControlTextListName();

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

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

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

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

            this.sigAddEventListener('USER_RESTORED', (majorId, minorId, msg) => {
                this._userRestored(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');
        }
    }

    connectedCallback() {
        super.connectedCallback();
        this._init();
    }

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

    _init() {
        this._switchLang();
        this._setUserListProps();
        SigPolymer.afterNextRender(this, function (params) {
            this.isloggedin = this.umApi.isUserLoggedIn();
            if (this.context) this.iswindow = (this.context.type === 'window') ? true : false;
            this._renderUserList();
            this._applFontObjects();
            if (this.isdesignmode) this.$.listview.isactive = true;
        });
    }

    _showButtons(_value) {
        return this.isdesignmode || _value;
    }

    async _login() {
        if (this.disconnected) return;
        const uid = this.utilsApi.getUID();
        const result = await this.umApi.login(this.$.username.value, this.$.password.value, undefined, undefined, undefined, uid).catch(
            error => {
                return error;
            });
        if (this._hasNoErrors(result)) {
            this._userLoggedIn();
            this._dispatchEvent('userloggedin');
            if (this.closeafterlogin) this._closeWindow();
            if (this.logintarget !== undefined) { this.arApi.navigate(this.logintarget); }
            return true;
        } else {
            await this._showAlert(this._getTextObj('userCouldnotBeLoggedIn'), this._getTextObj('alertTitle', [result.status])).catch(error => {
                this._log(error);
                return error;
            });
            return false;
        }
    }

    async _logout() {
        if (this.disconnected) return;
        const uid = this.utilsApi.getUID();
        const result = await this.umApi.logout(undefined, undefined, undefined, uid).catch(
            error => {
                return error;
            });
        if (this._hasNoErrors(result)) {
            this._userLoggedOut();
            this._dispatchEvent('userloggedout');
            if (this.closeafterlogout) this._closeWindow();
            if (this.logouttarget !== undefined) { this.arApi.navigate(this.logouttarget); }
            return true;
        } else {
            await this._showAlert(result.errortxt, this._getTextObj('alertTitle', [result.status])).catch(error => {
                return error;
            });
            return false;
        }
    }

    _userCreated(majorId, minorId, msg) {
        this._renderUserList();
    }

    _userUpdated(majorId, minorId, msg) {
        this._renderUserList();
    }

    _userDeleted(majorId, minorId, msg) {
        this._renderUserList();
    }

    _userRestored(majorId, minorId, msg) {
        this._renderUserList();
    }

    _userLoggedIn(majorId, minorId, msg) {
        this.isloggedin = true;
        this._clearInputs();
    }

    _userLoggedOut(majorId, minorId, msg) {
        this.isloggedin = false;
        this._clearInputs();
    }

    _setUserListProps() {
        this.$.listview.disablekeys = false;
        this.$.listview.disablemultiselect = true;
        this.$.listview.hideheader = true;
        this.$.listview.activemarked = true;
    }

    async _renderUserList() {
        if (this.disconnected) return;
        let result = {};
        if (!this.isdesignmode) {
            const uid = this.utilsApi.getUID();
            result = await this.umApi.getUserList(uid).catch(error => {
                return error;
            });
        } else {
            result.users =
                [{
                    id: 0,
                    userName: 'user0 - selected',
                    active: true
                },
                {
                    id: 1,
                    userName: 'user1 - normal (even)'
                },
                {
                    id: 2,
                    userName: 'user2 - alternate (odd)'
                }];
        }

        if (this._hasNoErrors(result)) {
            this.data = {
                "cols": [{
                    "id": "id",
                    "name": "id",
                    "type": "text",
                    "default": "&nbsp;",
                    "visible": false,
                    "sortable": false
                }, {
                    "id": "userName",
                    "name": "User name",
                    "type": "text",
                    "default": "&nbsp;",
                    "visible": true,
                    "sortable": false
                }],
                "data": {
                    "nodes": result.users
                }
            }
            this.config = {
                updateSelectionCallback: (data, pane) => {
                    this._updateSelection(data, pane);
                },
                clickCallback: (data, pane) => {
                    this._updateActiveRow(data, pane);
                },
                data: this.data,
                name: "users"
            };
            this.$.listview.config = this.config;
        } else {
            await this._showAlert(result.errortxt, this._getTextObj('alertTitle', [result.status])).catch(error => {
                return error;
            });
        }
    }

    _updateSelection(data, pane) {
    }

    _updateActiveRow(user, pane) {
        this.$.username.value = user.userName;
        this.$.password.value = user.password;
    }

    _clearInputs() {
        this.$.username.value = '';
        this.$.password.value = '';
        this.$.listview._clearActiveRow(true);
    }

    _closeWindow() {
        if (this.context.type === 'window') {
            const window = document.getElementById(this.context.instanceId);
            if (window instanceof HTMLElement) window.close();
        }
    }

    _updateLayout() {
        if (!window.chrome) {
            SigPolymer.afterNextRender(this, function (params) {
                this.$.listview.style.height = this.$.users.offsetHeight + "px";
            });
        }
    }
    async _switchLang(majorId, minorId, msg) {
        if (this.tmApi) {
            let username = this.username; 
            const texts = await this.tmApi.getTextsAsync(this._getTextsObject());
            if (this.titletext !== '') texts[this.controlTextList].caption = this.titletext;
            this.texts = texts[this.controlTextList];
            this.username = ''; 
            this.username = username; 
        }
    }

    designerOnLanguageChanged() {
        this._switchLang();
    }

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

    _getTextsObject() {
        return {
            [this.controlTextList]: {
                caption: 'User login',
                login: 'Login',
                logout: 'Logout',
                close: 'Close',
                username: 'Username',
                password: 'Password',
                enterUsername: 'Enter username',
                enterPassword: 'Enter password',
                users: 'Users',
                userCouldnotBeLoggedIn: 'User could not be logged in - please check username and password',
            }
        }
    }

    evtHandlerLogin(data) {
        if (Array.isArray(data) && data.length >= 2) {
            this.$.username.value = data[0].toString();
            this.$.password.value = data[1].toString();
        }
        this._login();
    }

    evtHandlerLogout() {
        this._logout();
    }

    designerOnBoundsChanged() {
        if (this.isdesignmode) this._updateLayout();
    }

    async _usernameChanged(username) {
        if (username) {
            this.usernamec = await this.tmApi.getTextWithParameterAsync(this._getTextObj('forUsername', [username]));
        } else {
            this.usernamec = '';
        }
    }

    _loginWayChanged(newVal, oldVal) {
        if (!this.isdesignmode) {
            if (newVal) {
                this.sigAddEventListener('sig-control-input-value-updated', this.loginFunction,
                    'jsEvent', this.$.password);
            } else {
                this.sigRemoveEventListener('sig-control-input-value-updated', this.loginFunction,
                    'jsEvent', this.$.password);
            }
        }
    }
}
customElements.define(LasalRuntimeSigControlUserLogin.is, LasalRuntimeSigControlUserLogin);
