/**
 * Class manages state if superuser/admin is logged in or not
 */
class LoginStateHandler {
    static init() {
        window.sigApiReadyPromise.then(() => {
            const codemodule = new LoginStateHandler();
        });
    }

    constructor() {
        this._registerEvents();
    }

    /**
     * @private
     * Subscribe to user management system events.
     * There is no need to use the sigUtils API to register event listeners because
     * global code modules such as this one are never destroyed during runtime. 
     */
    _registerEvents() {
        sigApi.eventMediator.subscribe(
            sigApi.events.getInternalEvent('USER_LOGGED_IN'),
            (maid, miid, msg) => {
                this._onUserLogin(maid, miid, msg);
            }
        );
        sigApi.eventMediator.subscribe(
            sigApi.events.getInternalEvent('USER_LOGGED_OUT'),
            (maid, miid, msg) => {
                this._onUserLogout(maid, miid, msg);
            }
        );
    }

    /**
     * @private
     * Handle system event user login
     */
    _onUserLogin(maid, miid, msg) {
        const userName = msg?.user?.userName?.toLowerCase();
		const isAdmin = userName === 'superuser' || userName  === 'administrator';
        const isSetter = userName === 'superuser' || userName === 'setter';
        const isSuperuser = userName === 'superuser';

        //const isAdmin = userName === 'superuser' || userName === 'administrator';
        
		sigApi.datapointManager.writeDataPoint('0:UserMerker1.isAdmin', isAdmin ? 1 : 0);
        sigApi.datapointManager.writeDataPoint('0:UserMerker1.isSetter', isSetter ? 1 : 0);
        sigApi.datapointManager.writeDataPoint('0:UserMerker1.isSuperuser', isSuperuser ? 1 : 0);
        
        
        
    }

    /**
     * @private
     * Handle system event user logout
     */
    _onUserLogout(maid, miid, msg) {
        sigApi.datapointManager.writeDataPoint('0:UserMerker1.isAdmin', 0);
        sigApi.datapointManager.writeDataPoint('0:UserMerker1.isSetter', 0);
        sigApi.datapointManager.writeDataPoint('0:UserMerker1.isSuperuser', 0);
    }
}

/**
 * Create the codemodule instance
 */
LoginStateHandler.init();
