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-button/sig-control-button.js";
import "../sig-control-listview/sig-control-listview.js";
import "../sig-control-titlebar/sig-control-titlebar.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 LasalRuntimeSigControlUserList extends Usermanager(LasalRuntimeSigElement) {

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

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

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

                
                display: block;
                position: absolute;
                overflow: var(--theme-sig-control-user-list-overflow, hidden);
                --theme-sig-control-user-list-deleted-row-opacity:.4;
            }

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

            .clearfix:after {
                
                @apply --clearfix
            }

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

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

            .form {
                overflow: hidden;
                flex: 1 1 100%;
            }

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

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

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

            .button {
                position: unset;
            }

            .button.default {
                margin: var(--theme-sig-control-user-list-button-margin, 10px) 0;
            }

            .button.right {
                margin-left: var(--theme-sig-control-user-list-button-margin, 10px);
                float: right;
            }

            .button.left {
                margin-right: var(--theme-sig-control-user-list-button-margin, 10px);
                float: left;
            }

            .button.symbol{
                width: var(--theme-sig-control-user-list-button-symbol-width, 50px) !important;
            }

            .button.noleftmargin{
                margin-left:px;
            }

             .button.norightmargin{
                margin-right:0px;
            }

            .button.disabled {
                opacity: var(--theme-sig-control-user-list-button-disabled-opacity, .4);
                pointer-events: none !important;
            }

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

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

            .message {
                color: inherit;
                text-decoration: inherit;
                text-align: center;
                line-height: 40px;
                height: 100%;
            }

            :host([hidebuttons]) .buttons,
            :host([hidetitle]) .title,
            :host([hideuserlist]) .users {
                display: none !important;
            }

            :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-titlebar {
                position: unset;
                display: block;
                height: var(--theme-sig-element-height, 26px);
                width:100%;
               
            }
        </style>
        <div class="sig-control-user-list clearfix">
            <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 id="users" class="users">
                            <sig-control-listview id="listview" class="userlist"></sig-control-listview>
                        </div>
                    </div>
                </div>
                <div id="buttons" class="buttons clearfix">
                    <template is="dom-if" if="[[_hasNoButtons(isloggedin, window)]]">
                        <div class="message">
                            [[texts.pleaseLoginToSeeAllOptions]]
                        </div>
                    </template>
                    <template is="dom-if" if="[[_showButtons(isloggedin)]]">
                        <template is="dom-if" if="[[_showButtons(permissions, 'toggledeleted')]]">
                            <sig-control-button id="toggledeleted" sigbtntext=""
                                sigbtntype="toggle" sigbtnicon$ ="[[ctoggledeletedsymbol]]" sigbtniconpressed="[[ctoggledeletedsymbol]]"
                                class="button default right symbol" on-up="_toggleDeletedUsers"></sig-control-button>
                        </template>
                        <template is="dom-if" if="[[window]]">
                            <sig-control-button id="viewuser" sigbtntext=[[texts.view]] class="button default right"
                                on-up="_viewUser"></sig-control-button>
                        </template>
                        <template is="dom-if" if="[[_showButtons(permissions.updateUser || _updateSelfPermissions())]]">
                            <sig-control-button id="updateuser" sigbtntext=[[texts.edit]] class="button default right"
                                on-up="_updateUser"></sig-control-button>
                        </template>
                        <template is="dom-if" if="[[_showButtons(permissions.createUser)]]">
                            <sig-control-button id="createuser" sigbtntext=[[texts.new]] class="button default right"
                                on-up="_createUser"></sig-control-button>
                        </template>
                        <template is="dom-if" if="[[_showButtons(permissions.deleteUser)]]">
                            <sig-control-button id="delteorrestoreuser" sigbtntext=[[texts.delete]] class="button default right noleftmargin"
                                on-up="_deleteOrRestoreUser"></sig-control-button>
                        </template>
                        
                    </template>
                </div>
            </div>
        </div>
        `
    }

    static get properties() {
        let props = {
            isloggedin: {
                type: Boolean,
                value: false,
                observer: '_isLoggedin'
            },
            activeuser: {
                type: Object,
                value: null,
                observer: '_updateUserPermissions'
            },
            hidetitle: {
                type: Boolean,
                value: false,
                reflectToAttribute: true
            },
            hideheader: {
                type: Boolean,
                value: false,
                observer: '_init'
            },
            hideuserlist: {
                type: Boolean,
                value: false,
                reflectToAttribute: true,
            },
            hidebuttons: {
                type: Boolean,
                value: false,
                reflectToAttribute: true
            },
            titlebarshadowactive: {
                type: Boolean,
                value: false,
                reflectToAttribute: true
            },
            titletext: {
                type: String,
                value: '',
                observer: '_switchLang'
            },
            showDeletedUsers: {
                type: Boolean,
                value: false,
                observer: '_updateShowDeletedUsers'
            },
            ctoggledeletedsymbol: {
                type: String,
                computed: '_makeUnicode(toggledeletedsymbol)'
            }
        }
        return props;
    }

    constructor() {
        super();
        this.umApi = window.sigApi.userManager;
        this.wmApi = window.sigApi.windowManager;
        this.evtsApi = window.sigApi.events;
        this.evtmApi = window.sigApi.eventMediator;
        this.tmApi = window.sigApi.textManager;
        this.utilsApi = window.sigApi.sigUtils;
        this.controlTextList = this.getControlTextListName();
        this.firstRenderDone = false;
        this.applybordereffect = false;
        this.target = null;
        this.window = null;
        this.iswindow = false;
        this.markedusers = null;
        this.selecteduser = null;
        this.longpressdelay = 250;
        this.config = null;
        this.data = null;
        this.permissions = {};
        this.texts = this._getTextsObject()[this.controlTextList];
        this.toggledeletedsymbol = 'f506';

        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');

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

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

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

    disconnectedCallback() {
        super.disconnectedCallback();
        this.umApi = null;
        this.wmApi = null;
        this.evtsApi = null;
        this.evtmApi = null;
        this.tmApi = null;
        this.utilsApi = null;
        this.target = null;
        this.window = null;
        this.markedusers = null;
        this.selecteduser = null;
        this.config = null;
        this.data = null;
        this.permissions = null;
        this.activeuser = null;
        this.text = null;
    }

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

    _isLoggedin(newval, oldval) {
        if (newval) {
            const uid = this.utilsApi.getUID();
            this.umApi.getActiveUser(uid).then((result) => {
                this.activeuser = result.user;
            }).catch(error => {
                return error;
            });
        } else {
            this.activeuser = {};
        }
    }

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

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

    _showButtons(value, rule) {
        let _value = value;
        if (value && typeof value === 'object' && rule) {
            switch (rule) {
                case 'toggledeleted':
                    _value = value.createUser || value.deleteUser;
                    break;
            }
        }
        return (this.isdesignmode) ? true : _value;
    }

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

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

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

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


    _userLoggedIn(majorId, minorId, msg) {
        const user = msg.user;
        if (this.isloggedin && user && this.activeuser.id !== user.id) this.isloggedin = false;
        this.isloggedin = true;
    }

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

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

    async _renderUserList(clearActiveRow = false) {
        if (this.disconnected) return;
        let result = {}
        if (!this.isdesignmode) {
            const uid = this.utilsApi.getUID();
            result = await this.umApi.getUserList(uid, ((this.permissions.createUser || this.permissions.deleteUser) && this.showDeletedUsers) ? 0 : 1).catch(error => {
                return error;
            });
        } else {
            result.users = [{
                id: 0,
                userName: 'administrator',
                firstName: 'Administrator',
                lastName: 'Administrator',
                info: 'Selected',
                timeout: 0,
                active: true
            },
            {
                id: 1,
                userName: 'user1',
                firstName: 'User1',
                lastName: 'User1',
                info: 'Selected marked',
                timeout: 0,
                active: true,
                marked: true
            },
            {
                id: 2,
                userName: 'user2',
                firstName: 'User2',
                lastName: 'User2',
                info: 'Alternate (odd)',
                timeout: 0
            },
            {
                id: 3,
                userName: 'user3',
                firstName: 'User3',
                lastName: 'User3',
                info: 'Normal (even)',
                timeout: 0
            },
            {
                id: 4,
                userName: 'user4',
                firstName: 'User4',
                lastName: 'User4',
                info: 'Marked',
                timeout: 0,
                marked: true
            },
            {
                id: 5,
                userName: 'user5',
                firstName: 'User5',
                lastName: 'User5',
                info: 'Deleted',
                timeout: 0,
                isDeleted: true
            }
            ];
        }
        if (this._hasNoErrors(result)) {
            result.users.forEach(user => user.rowRenderCallback = this._renderRow.bind(this));
            this.data = {
                "cols": [
                    {
                        "id": "id",
                        "name": this.texts.id,
                        "type": "text",
                        "css": {
                            "text-align": "center"
                        },
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false,
                    },
                    {
                        "id": "userName",
                        "name": this.texts.userName,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false
                    },
                    {
                        "id": "firstName",
                        "name": this.texts.firstName,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false
                    },
                    {
                        "id": "lastName",
                        "name": this.texts.lastName,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false
                    },
                    {
                        "id": "info",
                        "name": this.texts.info,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false
                    },
                    {
                        "id": "roles",
                        "name": this.texts.roles,
                        "type": "text",
                        "default": null,
                        "visible": true,
                        "sortable": false,
                        "formatDataCallback": this._formatRoles
                    },
                    {
                        "id": "lastLogin",
                        "name": this.texts.lastLogin,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false,
                        "formatDataCallback": this._formatDate,
                    },
                    {
                        "id": "lastLogout",
                        "name": this.texts.lastLogout,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false,
                        "formatDataCallback": this._formatDate,
                    },
                    {
                        "id": "timeout",
                        "name": this.texts.timeout,
                        "type": "text",
                        "default": "&nbsp;",
                        "visible": true,
                        "sortable": false
                    }],
                "data": {
                    "nodes": result.users
                }
            }
            this.config = {
                updateSelectionCallback: (data, pane) => {
                    this._updateSelection(data, pane);
                },
                updateActiveRowCallback: (data, pane) => {
                    this._updateActiveRow(data, pane);
                },
                clickCallback: (data, pane) => {
                    this._click(data, pane);
                },
                doubleClickCallback: (data, pane) => {
                    this._doubleClick(data, pane);
                },
                longPressCallback: (data, pane) => {
                    this._longPress(data, pane);
                },
                onEnterCallback: (data, pane) => {
                    this._viewUser(true);
                },
                onRenderReadyCallback: (data, pane) => {
                    if (!this.firstRenderDone) this.firstRenderDone = true;
                    this._setButtonState();
                },
                data: this.data,
                name: "userlist",
                self: this
            };
            this.$.listview.config = this.config;
            if (clearActiveRow) { this.$.listview._clearActiveRow(true); }
        } else {
            console.error(result);
        }
    }

    _renderRow(row) {
        if (row instanceof HTMLElement) {
            const data = (row.dataset.data) ? JSON.parse(row.dataset.data) : null;
            if (data && data.isDeleted) {
                row.classList.add('isdeleted');
                row.style.opacity = 'var(--theme-sig-control-user-list-deleted-row-opacity)';
            }
        }
    }

    _updateSelection(users, pane) {
        this.markedusers = users;
    }

    _updateActiveRow(user, pane) {
        this.selecteduser = user;
        this._setButtonState(user);
    }

    _click(user, pane) {
        this._viewUser();
    }

    _doubleClick(user, pane) {
        this._viewUser(true);
    }

    _longPress(user, pane) {
    }

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

    async _updateUserPermissions() {
        if (this.disconnected) return;
        if (this.isloggedin && this.activeuser) {
            const uid = this.utilsApi.getUID();
            await this.umApi.getUserPermissions(this.activeuser, uid).then(result => {
                this.permissions = result.permissions;
                this._setButtonState(this.selecteduser);
            }).catch(error => {
                console.error(error);
                this.permissions = {};
            });
        } else {
            this.permissions = {};
        }
        this._renderUserList();
    }

    _formatDate(timestamp, row, col, self) {
        if (Number.isInteger(timestamp)) {
            const localDate = new Date(timestamp);
            const date = localDate.toLocaleDateString();
            const time = localDate.toLocaleTimeString();
            return date + ' ' + time;
        }
        if (self) {
            return self.texts.notAvailable;
        }
        return timestamp;
    }

    _formatRoles(roles, row, col, self) {
        let roleNames = [];
        if (Array.isArray(roles)) {
            roles.forEach((role) => {
                if (role) {
                    roleNames.push(role)
                }
            });
        }
        if (roleNames.length === 0 && self) {
            roleNames.push(self.texts.none);
        }
        return roleNames.join();
    }

    async _formatRolesAsync(roles, row, col, self) {
        if (this.disconnected) return;
        function f1() {
            let roleNames = [];

            return new Promise((resolve, reject) => {
                this.sigSetTimeout(
                    () => {
                        roles.forEach((role) => {
                            if (role.name) {
                                roleNames.push(role.name)
                            }
                        });
                        resolve(roleNames)
                    },
                    Math.floor(Math.random() * 1000) + 2500
                )
            })
        }
        const result = await f1();
        return result;
    }

    _renderColors(value, row, col, self) {
        return new Promise((resolve, reject) => {
            let _render = `<span style="color:green">${value}</span>`;
            if (value === 'not available') _render = `<span style="color:red">${value}</span>`;
            else if (value === '&nbsp;') _render = `<span style="color:red">-</span>`;
            resolve(_render);
        })
    }

    _deleteOrRestoreUser() {
        if (this.permissions.deleteUser || this.permissions.createUser) {
            if (this.selecteduser.isDeleted) this._restoreUser();
            else this._deleteUser();
        }
    }

    async _deleteUser() {
        if (this.disconnected) return;
        if (this.permissions.deleteUser) {
            const count = this._getMarkedCount();
            if (count > 0) {
                const confirm = await this._showConfirm(this._getTextObj('doYouRealyWantToDeleteUsers', [count]), this._getTextObj('caption'), 1).then(result => {
                    return true;
                }).catch(error => {
                    this._log(error);
                    return false;
                });
                if (confirm) {
                    const uid = this.utilsApi.getUID();
                    const result = await this.umApi.deleteUser(this.markedusers, undefined, undefined, undefined, uid).catch(
                        error => {
                            return error;
                        });
                    if (this._hasNoErrors(result)) {
                        return true;
                    } else {
                        await this._showAlert(result.errortxt, this._getTextObj('alertTitle', [result.status])).catch(error => {
                            this._log(error);
                        });
                        return false;
                    }
                }
            } else {
                await this._showAlert(this._getTextObj('pleaseSelectUserFirst'), this._getTextObj('caption')).catch(error => {
                    this._log(error);
                });
            }
        } else {
            await this._showAlert(this._getTextObj('noPermissionToDeleteUsers'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _viewUser(evt) {
        if (this.disconnected) return;
        if (this.selecteduser) {
            if (evt) { this._openWindow() };
            this.evtmApi.publish(this.evtsApi.getInternalEvent('SEND_USER_DATA'), { type: 'user', source: this.id, target: this._getTargetList(), data: { mode: 'view', user: this.selecteduser } });
        } else {
            await this._showAlert(this._getTextObj('pleaseSelectUserFirst'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _updateUser(evt) {
        if (this.disconnected) return;
        if ((this.permissions.updateUser || (this.selecteduser.id === this.activeuser.id && this._updateSelfPermissions())) && this.selecteduser && this.selecteduser.readOnly !== true && this._checkAccess(this.selecteduser.accessNumber)) {
            this._openWindow();
            this.evtmApi.publish(this.evtsApi.getInternalEvent('SEND_USER_DATA'), { type: 'user', source: this.id, target: this._getTargetList(), data: { mode: 'update', user: this.selecteduser } });
        } else if (!this.selecteduser) {
            await this._showAlert(this._getTextObj('pleaseSelectUserFirst'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        } else {
            await this._showAlert(this._getTextObj('noPermissionToUpdateTheUser'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _createUser(evt) {
        if (this.disconnected) return;
        if (this.permissions.createUser) {
            this._openWindow();
            this.evtmApi.publish(this.evtsApi.getInternalEvent('SEND_USER_DATA'), { type: 'user', source: this.id, target: this._getTargetList(), data: { mode: 'create' } });
        } else {
            await this._showAlert(this._getTextObj('noPermissionToCreateUser'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _linkToken() {
        if (this.disconnected) return;
        if (this.permissions.linkToken) {
            await this._showAlert('Link token needs implementation', this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        } else {
            await this._showAlert(this._getTextObj('noPermissionToLinkToken'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _importUsers() {
        if (this.disconnected) return;
        if (this.permissions.importUsers) {
            await this._showAlert('Import users needs implementation', this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        } else {
            await this._showAlert(this._getTextObj('noPermissionToImportUsers'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _exportUsers() {
        if (this.disconnected) return;
        if (this.permissions.importUsers) {
            await this._showAlert('Export users needs implementation', this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        } else {
            await this._showAlert(this._getTextObj('noPermissionToExportUsers'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _restoreUser() {
        if (this.disconnected) return;
        if (this.permissions.deleteUser) {
            const count = this._getMarkedCount();
            if (count > 0) {
                if (this.markedusers.some(user => !user.isDeleted)) {
                    await this._showAlert(this._getTextObj('userExistsCannotRestore'), this._getTextObj('caption')).catch(error => {
                        this._log(error);
                    });
                    return false;
                }

                const confirm = await this._showConfirm(this._getTextObj('doYouRealyWantToRestoreUsers', [count]), this._getTextObj('caption'), 1).then(result => {
                    return true;
                }).catch(error => {
                    this._log(error);
                    return false;
                });
                if (confirm) {
                    const result = await this.umApi.restoreUser(this.markedusers).catch(
                        error => {
                            return error;
                        });
                    if (this._hasNoErrors(result)) {
                        return true;
                    } else {
                        await this._showAlert(result.errortxt, this._getTextObj('alertTitle', [result.status])).catch(error => {
                            this._log(error);
                        });
                        return false;
                    }
                }
            } else {
                await this._showAlert(this._getTextObj('pleaseSelectUserFirst'), this._getTextObj('caption')).catch(error => {
                    this._log(error);
                });
            }
        } else {
            await this._showAlert(this._getTextObj('noPermissionToRestoreUsers'), this._getTextObj('caption')).catch(error => {
                this._log(error);
            });
        }
    }

    async _openWindow() {
        if (this.disconnected) return;
        if (this.window || this.window === 0) {
            await this.wmApi.openWindow(this.window).catch(error => {
                this._log(error);
            });
        }
    }

    _getTargetList() {
        if (this.target) {
            return this.target.split(',');
        }
        return null;
    }

    _hasNoButtons(isloggedin, window) {
        return (!isloggedin && !this.isdesignmode) ? true : false;
    }

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

    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 list',
                id: 'ID',
                userName: 'User name',
                firstName: 'First name',
                lastName: 'Last name',
                info: 'Info',
                roles: 'Roles',
                lastLogin: 'Last login',
                lastLogout: 'Last logout',
                timeout: 'Timeout',
                export: 'Export',
                import: 'Import',
                linkToken: 'Link token',
                reset: 'Reset',
                delete: 'Delete',
                new: 'New',
                edit: 'Edit',
                view: 'View',
                restore: 'Restore',
                pleaseLoginToSeeAllOptions: 'Please login to see all options',
                none: 'none',
                notAvailable: 'not available'
            }
        }
    }

    evtHandlerViewUser() {
        this._viewUser(true);
    }

    evtHandlerUpdateUser() {
        this._updateUser();
    }

    evtHandlerCreateUser() {
        this._createUser();
    }

    evtHandlerDeleteUser() {
        this._deleteUser();
    }

    evtHandlerRestoreUser() {
        this._restoreUser();
    }

    evtHandlerLinkToken() {
    }

    evtHandlerImportUsers() {
    }

    evtHandlerExportUsers() {
    }

    evtHandlerMoveCursorDown() {
        this.$.listview.moveCursorDown();
    }

    evtHandlerMoveCursorUp() {
        this.$.listview.moveCursorUp();
    }

    evtHandlerMoveCursorPageDown() {
        this.$.listview.moveCursorPageDown();
    }

    evtHandlerMoveCursorPageUp() {
        this.$.listview.moveCursorPageUp();
    }

    _getMarkedCount() {
        if (this.markedusers !== null) {
            return this.markedusers.length;
        }
        return 0;
    }

    designerOnAppliedCSSValue(cssObj) {
        if (cssObj.hasOwnProperty('--theme-sig-control-user-list-deleted-row-opacity')) this._renderUserList();
    }

    _setButtonState(user) {
        const buttons = this.shadowRoot.querySelectorAll('#buttons sig-control-button');
        const hasAccess = (user && user.accessNumber !== undefined) ? this._checkAccess(user.accessNumber) : false;
        buttons.forEach(button => {
            let enableButton = false;
            switch (button.id) {
                case 'delteorrestoreuser':
                    if (hasAccess && user && user.id > 3) enableButton = true;
                    if (user && user.isDeleted) button.sigbtntext = this.texts.restore;
                    else button.sigbtntext = this.texts.delete;
                    break;
                case 'viewuser':
                    if (user) enableButton = true;
                    break;
                case 'exportusers':
                case 'importusers':
                case 'createuser':
                case 'toggledeleted':
                    enableButton = true;
                    break;
                case 'updateuser':
                    if (hasAccess && this.permissions.updateUser ||
                        (hasAccess && this.activeuser.id === user.id && this._updateSelfPermissions()))
                        enableButton = true;
                    break;
                case 'linktoken':
                default:
                    if (hasAccess) enableButton = true;
                    break;
            }
            if (enableButton) this._enableButton(button);
            else this._disableButton(button);
        });
    }

    _toggleDeletedUsers() {
        this.showDeletedUsers = !this.showDeletedUsers;
    }

    _updateShowDeletedUsers(newval, oldval) {
        if (this.firstRenderDone && newval !== undefined) this._renderUserList();
    }

    _makeUnicode(code) {
        return String.fromCharCode(parseInt(code, 16));
    }
}
customElements.define(LasalRuntimeSigControlUserList.is, LasalRuntimeSigControlUserList);