/*
 *  Copyright 2022 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Define general actions for multifactor authentication
 * @private
 */
Ext.define('Ametys.plugins.coreui.authentication.MultifactorAuthenticationActions', {
	singleton: true,
	
	/**
	 * This method will open a dialog box to see the user's authentication token and generate tokens
	 */
	showMFAAuthenticationDialogBox: function ()
	{
		this._delayedInitializeMultifactorAuthenticationDialog();
        
        Ametys.data.ServerComm.callMethod({
            role: 'org.ametys.plugins.core.authentication.MultifactorAuthenticationManager',
            methodName: 'getUserSecretForCurrentUser',
            parameters: [],
            callback: {
                handler: this._showCB,
                scope: this
            },
            errorMessage: true
        });
	},
	
	/**
	 * @private
	 * Callback after loading secret
	 */
	_showCB: function (infos)
    {
        this._mfaAuthenticationBox.getComponent("activate_application").setValue(infos.active);
        this._updateSecret(infos.secret);
        
		this._mfaAuthenticationBox.show();
    },
    
	/**
	 * @private
	 * Draw the multifactor authentication dialog box
	 */
	_delayedInitializeMultifactorAuthenticationDialog: function ()
	{
		if (!this._mfaAuthenticationDialogInitialized)
		{
    		this._mfaAuthenticationBox = Ext.create('Ametys.window.DialogBox', {
    			title :"{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_LABEL}}",
    			iconCls : 'ametysicon-system-qrcode',
    			
    			width : 650,
    			scrollable: true,  
    			
                layout:
                {
                    type: 'vbox',
                    align: 'middle'
                },
    			
    			items : [{
    		                xtype: 'component',
    		                html: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_HINT}}",
    		                cls: 'a-text',
    		                width: '100%'
    		            },
                        {
                            xtype: 'component',
                            html: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_HINT2}}",
                            cls: 'a-text',
                            width: '100%'
                        },
                        {
                            xtype: "radio",
                            boxLabel: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_EMAIL_LABEL}}",
                            ametysDescription: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_EMAIL_DESCRIPTION}}",
                            allowBlank: true,
                            alignTarget: 'center',
                            checked: true,
                            itemId: "activate_email",
                            name: "type",
                            readonly: true,
                            width: '100%',
                            listeners: {
                                change: this._oncheck,
                                scope: this
                            }
                        },  
                        {
                            xtype: "radio",
                            boxLabel: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_APPLICATION_LABEL}}",
                            ametysDescription: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_APPLICATION_DESCRIPTION}}",
                            allowBlank: true,
                            itemId: "activate_application",
                            width: '100%',
                            name: "type",
                            cls: 'mfa-grey-after',
                            listeners: {
                                change: this._oncheck,
                                scope: this
                            }
                        },
                        {
                            xtype: 'component',
                            html: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_APPLICATION_HINT}}",
                            cls: 'a-text',
                            style: {
                                marginLeft: '70px',
                                textIndent: '-15px'
                            },
                            width: '100%' 
                        },
                        {
                            xtype: 'component',
                            html: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_APPLICATION_HINT2}}",
                            cls: 'a-text',
                            style: {
                                marginLeft: '70px',
                                textIndent: '-15px'
                            },
                            width: '100%' 
                        },
                        {
                            xtype: 'image',
                            itemId: "qr-code",
                            width: 128,
                            height: 128
                        },
                        {
                            xtype:'component',
                            itemId: "secret",
                            style: {
                                marginBottom: '15px'
                            }
                        },
                        {
                            xtype: 'component',
                            html: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_APPLICATION_HINT3}}",
                            cls: 'a-text',
                            style: {
                                marginLeft: '70px',
                                textIndent: '-15px'
                            },
                            width: '100%' 
                        },
                        {
                            xtype: 'component',
                            html: "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_ACTIVATE_APPLICATION_HINT4}}",
                            cls: 'a-text',
                            style: {
                                marginLeft: '40px'
                            },
                            width: '100%' 
                        }
    				],
    			
    			closeAction: 'hide',
    			defaultFocus: 'activate_application',
    			
    			referenceHolder: true,
    			defaultButton: 'validate',
    			
    			buttons : [ {
                    reference: 'changesecret',
                    text :"{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_BTN_CHANGESECRET}}",
                    handler : this._changeSecret,
                    scope: this
                },
                ' ', 
                {
    				reference: 'validate',
    				text :"{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_BTN_OK}}",
    				handler : this._save,
    				scope: this
    			},{
                    reference: 'cancel',
                    text :"{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_BTN_CANCEL}}",
                    handler : function () { this._mfaAuthenticationBox.close() },
                    scope: this
                }  ]
    		});
    		
    		this._mfaAuthenticationDialogInitialized = true;
        }
	},
	
	_oncheck: function(radio, value)
	{
	   var email = this._mfaAuthenticationBox.getComponent("activate_email");
	   var app = this._mfaAuthenticationBox.getComponent("activate_application");
	   
       (radio == email ? app : email).setValue(!value);
	},
    
    /**
     * @private
     * When ok the dialog
     */
    _save: function()
    {
        var value = this._mfaAuthenticationBox.getComponent("activate_application").getValue();
        
        Ametys.data.ServerComm.callMethod({
            role: 'org.ametys.plugins.core.authentication.MultifactorAuthenticationManager',
            methodName: 'authenticationApplicationForCurrentUser',
            parameters: [value],
            callback: {
                handler: this._saveCB,
                scope: this
            },
            errorMessage: true
        });        
    },
    
    /**
     * @private
     * Ok callback
     */
    _saveCB: function()
    {
        this._mfaAuthenticationBox.close();
    },

    /**
     * @private
     * Update the secret value
     */
    _updateSecret: function(secret)
    {
        this._secret = secret;
        this._mfaAuthenticationBox.getComponent("secret").setHtml(secret);
        this._mfaAuthenticationBox.getComponent("qr-code").setSrc(Ametys.getPluginDirectPrefix('core-impl') + '/mfa/qrcode?foo=' + Math.random());
    },
    
    /**
     * @private
     * Renew the secret
     */
    _changeSecret: function()
    {
        Ametys.Msg.confirm("{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_BTN_CHANGESECRET_CONFIRM_LABEL}}", 
                "{{i18n PLUGINS_CORE_UI_MULTIFACTOR_AUTHENTICATION_BTN_CHANGESECRET_CONFIRM}}", 
                function(answer) {
                    if (answer == 'yes')
                    {
                        Ametys.data.ServerComm.callMethod({
                            role: 'org.ametys.plugins.core.authentication.MultifactorAuthenticationManager',
                            methodName: 'renewSecretForCurrentUser',
                            parameters: [],
                            callback: {
                                handler: this._changeSecretCB,
                                scope: this
                            },
                            errorMessage: true
                        });        
                    }
                },
                this
        );
    },
    
    /**
     * @private
     * Renew the secret
     */
    _changeSecretCB: function(secret)
    {
        this._updateSecret(secret);
    }    
});