/*
 *  Copyright 2013 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.
 */

/**
 * This helper provides a dialog box to edit the parameters of the CMIS connection
 * See #open method.
 */
Ext.define('Ametys.explorer.resources.helper.CMISConnection', {
    singleton: true,
    
    /**
     * @property {Boolean} _initialized True if the dialog was already initialized
     * @private
     */
    
    /**
     * @property {Ametys.window.DialogBox} _box The dialog box to edit the CMIS connection parameters
     * @private
     */
    
    /**
     * @property {String} _mode the current mode : 'new' for creation or 'edit' for edition
     * @private
     */
    
    /**
     * @property {Ext.form.Basic} _form The inner basic form.
     * @private
     */
    
    /**
     * Add or a edit a CMIS connection. Opens a dialog box to fill/edit the CMIS connection parameters
     * @param {String} id The id of parent folder if mode equals 'new' or the CMIS folder id  mode equals 'edit'
     * @param {Function} callback The callback function called when the CMIS connection was created. Has the following parameters:
     * @param {String} callback.parentId The id of parent folder. Can be null in "edition" mode
     * @param {String} callback.id The id of CMIS folder. Can not be null
     * @param {String} callback.name The name of CMIS folder. Can not be null
     * @param {String} [mode=new] The open mode : 'new' for creation or 'edit' for edition. 'new' par default.
     */
    open: function (id, callback, mode)
    {
        this._mode = mode || 'new';
        this._cbFn = callback;
        
        this._delayedInitialize ();
        this._box.show();
        
        this._initForm (id);
    },
    
    /**
     * @private
     * Initialize the dialog box
     * @return {Boolean} true if the box has been initialized (or if it was already initialized).
     */
    _delayedInitialize: function()
    {
        if (this._initialized)
        {
            return true;
        }
        
        var formPanel = Ext.create('Ext.form.Panel', {
            border: false,
            
            scrollable: true,
            defaultType: 'textfield',
            fieldDefaults : {
                cls: 'ametys',
                labelAlign: 'right',
                labelSeparator: '',
                labelWidth: 140,
                width: "100%"
            },
            
            items : [{
                fieldLabel: "{{i18n PLUGINS_EXPLORER_CMIS_FOLDER_NAME}}" + " *",
                ametysDescription: "{{i18n PLUGINS_EXPLORER_CMIS_FOLDER_NAME_DESC}}",
                name: 'name',
                itemId: 'name',
                value: "{{i18n PLUGINS_EXPLORER_CMIS_FOLDER_DEFAULT_NAME}}",
                allowBlank: false
            }, {
                fieldLabel: "{{i18n PLUGINS_EXPLORER_CMIS_SERVER_URL}}" + " *",
                ametysDescription: "{{i18n PLUGINS_EXPLORER_CMIS_SERVER_URL_DESC}}",
                name: 'url',
                allowBlank: false
            }, {
                fieldLabel: "{{i18n PLUGINS_EXPLORER_CMIS_REPOSITORY_ID}}",
                ametysDescription: "{{i18n PLUGINS_EXPLORER_CMIS_REPOSITORY_ID_DESC}}",
                name: 'repoId'
            }, {
                fieldLabel: "{{i18n PLUGINS_EXPLORER_CMIS_REPOSITORY_MOUNT_POINT}}",
                ametysDescription: "{{i18n PLUGINS_EXPLORER_CMIS_REPOSITORY_MOUNT_POINT_DESC}}",
                name: 'mountPoint',
                regex: new RegExp('^\/.*$'),
                regexText: "{{i18n PLUGINS_EXPLORER_CMIS_REPOSITORY_MOUNT_POINT_INVALID_REGEX}}"
            }, {
                fieldLabel: "{{i18n PLUGINS_EXPLORER_CMIS_USER_LOGIN}}",
                ametysDescription: "{{i18n PLUGINS_EXPLORER_CMIS_USER_LOGIN_DESC}}",
                name: 'login'
            }, {
                fieldLabel: "{{i18n PLUGINS_EXPLORER_CMIS_USER_PASSWORD}}",
                ametysDescription: "{{i18n PLUGINS_EXPLORER_CMIS_USER_PASSWORD_DESC}}",
                name: 'password',
                inputType: 'password'
            }, {
                xtype: 'hiddenfield',
                name: 'id'
            }]
        });
        
        this._box = Ext.create('Ametys.window.DialogBox', {
            title:"{{i18n PLUGINS_EXPLORER_CMIS_CONNECTION_DIALOG_TITLE}}",
            icon: Ametys.getPluginResourcesPrefix('explorer') + '/img/cmis/cmis_16.png',
            
            layout: 'fit',
            width: 460,
            
            items: formPanel,
            
            defaultFocus: 'name',
            closeAction: 'hide',
            
            referenceHolder: true,
            defaultButton: 'validate',

            buttons: [{
                reference: 'validate',
				text:"{{i18n plugin.core-ui:PLUGINS_CORE_UI_DIALOG_OK}}",
                handler: Ext.bind(this._okFn, this)
            },{
				text: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_DIALOG_CANCEL}}",
                handler: Ext.bind(function() {this._box.hide();}, this)
            } ]
        });
        
        this._initialized = true;
        return true;
    },

    /**
     * @private
     * Initialize or reinitialize the form with the appropriate values depending on the mode.
     * @param {String} id The id of the resource.
     */
    _initForm: function (id)
    {
        var form = this._box.down('form').getForm();
        
        if (this._mode == 'new')
        {
            form.findField('id').setValue(id);
            form.findField('name').reset();
            form.findField('name').enable();
            form.findField('repoId').reset();
            form.findField('mountPoint').reset();
            form.findField('url').reset();
            form.findField('login').reset();
            form.findField('password').reset();
        }
        else
        {
            Ametys.data.ServerComm.callMethod({
                role: 'org.ametys.plugins.explorer.resources.actions.ExplorerResourcesDAO', 
                methodName: 'getCMISProperties',
                parameters: [id],
                callback: {
                    handler: this._getCMISPropertiesCb,
                    scope: this
                },
                waitMessage: {
                    target: this._box
                },
                errorMessage: "{{i18n PLUGINS_EXPLORER_CMIS_GET_PROPERTIES_ERROR}}"
            });
        }
    },
    
    /**
     * Callback function invoked after retrieving CMIS access properties
     * @param {Object} data The CMIS properties
     * @private
     */
    _getCMISPropertiesCb: function (data)
    {
        var form = this._box.down('form').getForm();
        
        form.findField('id').setValue(data.id);
        form.findField('name').setValue(data.name);
        form.findField('name').disable();
        form.findField('repoId').setValue(data.repoId);
        form.findField('mountPoint').setValue(data.mountPoint);
        form.findField('url').setValue(data.url);
        form.findField('login').setValue(data.login);
        form.findField('password').setValue(data.password);
    },

    /**
     * @private
     * Handler function called when the 'Ok' button of dialog box #_box is pressed.
     */
    _okFn: function()
    {
        var form = this._box.down('form').getForm();
        if (!form.isValid())
        {
            return;
        }
        
        var params = form.getValues();
        var url;
        
        
        if (this._mode == 'new')
        {
            Ametys.data.ServerComm.callMethod({
                role: 'org.ametys.plugins.explorer.resources.actions.ExplorerResourcesDAO', 
                methodName: 'addCMISCollection',
                parameters: [params.id, params.name, params.url, params.login, params.password, params.repoId, params.mountPoint, true],
                callback: {
                    handler: this._addCb,
                    scope: this
                },
                waitMessage: true,
                errorMessage: "{{i18n PLUGINS_EXPLORER_CMIS_ADD_ERROR}}"
            });
        }
        else
        {
            Ametys.data.ServerComm.callMethod({
                role: 'org.ametys.plugins.explorer.resources.actions.ExplorerResourcesDAO', 
                methodName: 'editCMISCollection',
                parameters: [params.id, params.url, params.login, params.password, params.repoId, params.mountPoint],
                callback: {
                    handler: this._editCb,
                    scope: this
                },
                waitMessage: true,
                errorMessage: "{{i18n PLUGINS_EXPLORER_CMIS_EDIT_ERROR}}"
            });
        }
    },

    /**
     * @private
     * Callback function invoked after adding CMIS collection
     * @param {Object} response The server response
     */
    _addCb: function (response)
    {
        if (response.message && response.message == 'locked')
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_EXPLORER_FOLDER_HANDLE_ADD}}",
                msg: "{{i18n PLUGINS_EXPLORER_CMIS_ADD_LOCKED}}",
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            
            if (this._cbFn)
            {
                Ext.Function.defer (this._cbFn, 0, null, [null, null, null]);
            }
            
            return false;
        }
        
        this._box.hide();
        
        var id = response.id;
        var parentID = response.parentID;
        var name = response.name;
        
        if (this._cbFn)
        {
            Ext.Function.defer (this._cbFn, 0, null, [parentID, id, name]);
        }
    },
    
    /**
     * @private
     * Callback function invoked after editing CMIS collection
     * @param {Object} response The server response
     */
    _editCb: function (response)
    {
        if (response.message && response.message == 'locked')
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_EXPLORER_FOLDER_HANDLE_ADD}}",
                msg: "{{i18n PLUGINS_EXPLORER_CMIS_EDIT_LOCKED}}",
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            
            if (this._cbFn)
            {
                Ext.Function.defer (this._cbFn, 0, null, [null, null, null]);
            }
            
            return false;
        }
        
        this._box.hide();
        
        var id = response.id;
        var name = response.name;
        
        if (this._cbFn)
        {
            Ext.Function.defer (this._cbFn, 0, null, [null, id, name]);
        }
    }
});