/*
 *  Copyright 2020 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 is used to configure view parameters
 */
Ext.define("Ametys.plugins.web.parameters.view.ViewParametersDialogHelper", {
    singleton: true,

    /**
     * Open the dialog box to configure view parameters
     * @param {String} pageId The page id
     * @param {String} zoneName The zone name (can be null)
     * @param {String} zoneItemId The zone item id (can be null)
     * @param {Function} callback The function call after configure view parameters
     */
    open: function (pageId, zoneName, zoneItemId, callback)
    {
    	Ametys.data.ServerComm.callMethod({
			role: "org.ametys.web.parameters.view.ViewParametersDAO",
			methodName: "getViewParametersDefinitions",
			parameters: [pageId, zoneName, zoneItemId],
			callback: {
				handler: this._configureCB,
				scope: this,
				arguments: {
                    pageId: pageId,
                    zoneName: zoneName,
                    zoneItemId: zoneItemId,
                    callback: callback
                }
			},
			waitMessage: true,
            errorMessage: true
		});
    },
    
    /**
     * @private
     * Callback function after retrieving view parameters.<br/>
     * Draw the forms.
     * @param {Object} response the server response
     * @param {Object[]} args the callback arguments.
     */
	_configureCB: function(response, args)
	{
        var cfpConfig = {
            hideDisabledFields: true,
            
            additionalWidgetsConfFromParams: {
                contentType: 'contentType' // some widgets requires the contentType configuration  
            }
        };

        this._form = Ext.create('Ametys.form.ConfigurableFormPanel', cfpConfig);
        this._form.configure(response.parameters.elements);
        
        var params = {
            pageId: args.pageId,
            zoneName: args.zoneName,
            zoneItemId: args.zoneItemId,
            callback: args.callback
        };
        
        // Dialog box
        this._createDialogBox(params);
        this._box.add(this._form);
        
        Ametys.data.ServerComm.callMethod({
			role: "org.ametys.web.parameters.view.ViewParametersDAO",
			methodName: "getViewParametersValues",
			parameters: [params.pageId, params.zoneName, params.zoneItemId],
			callback: {
				handler: this._initFormCb,
				scope: this,
		        arguments: params
			},
			waitMessage: true,
			errorMessage: true
		});
	},
	
	/**
     * @private
     * Initialize form values
     * @param {Object} response The values of service parameters
     */
    _initFormCb: function (response)
    {
        this._form.setValues(response);
        this._form.focus();
        
        this._box.show();
    },
	
	/**
     * @private
     * Create the view parameters dialog box
     * @param {Object} params the parameters for validate function
     */
    _createDialogBox: function(params)
    {
    	var ratio = 0.80,
    	maxHeight = window.innerHeight * ratio,
        maxWidth = window.innerWidth * ratio;
    	
        this._box = Ext.create('Ametys.window.DialogBox', {
            title :"{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_LABEL}}",
            iconCls : 'ametysicon-art-pallet decorator-ametysicon-gear39',
            
            layout: 'fit',
            bodyPadding: '0',
            maxHeight: maxHeight,
        	maxWidth: maxWidth,
        	width: 700,
        	minHeight: 300,
            
            items: [],
            
            closeAction: 'destroy',
            
            referenceHolder: true,
            defaultButton: 'validate',
            
            buttons : [
                {
                    reference: 'validate',
                    itemId: 'button-ok',
                    text :"{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_OK}}",
                    handler: function() { this._validate(params); },
                    scope: this
                }, {
                    text :"{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_CANCEL}}",
                    handler: function() { this._box.close(); },
                    scope: this
            } ]
        });
    },
    
    /**
     * @private
     * Validate the dialog box and create the service.
     * @param {Object} params the parameters for validate function
     */
    _validate: function (params)
    {
        var invalidFields = this._form.getInvalidFields();
        var values = this._form.getJsonValues();
        
        if (invalidFields.length > 0)
        {
            Ametys.Msg.show({
                   title: "{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_SAVE_ERROR}}",
                   msg: "{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_SAVE_ERROR_INVALIDFIELDS}}" + Ametys.form.SaveHelper.getInvalidFieldsAsReadableList(invalidFields),
                   buttons: Ext.Msg.OK,
                   icon: Ext.MessageBox.ERROR
            });
            return;
        }

        Ametys.data.ServerComm.callMethod({
			role: "org.ametys.web.parameters.view.ViewParametersDAO",
			methodName: "setViewParametersValues",
			parameters: [params.pageId, params.zoneName, params.zoneItemId, values],
			callback: {
				handler: this._saveParametersCb,
				scope: this,
				arguments: params
			},
			waitMessage: true,
			errorMessage: true
		});
    },
    
    /**
     * @private
     * Callback after saving view parameters
     * @param {Object} response The server response
     * @param {Object} args The callback arguments
     */
    _saveParametersCb: function (response, args)
    {
        var errors = response.errors;
        if (Ext.isEmpty(errors))
        {
            if (this._box)
            {
                this._box.close();
            }
            
            // Execute callback function passed to #open method
            var callback = args.callback;
            if (Ext.isFunction(callback))
            {
            	callback(args.pageId, args.zoneName, args.zoneItemId);
            }
        }
        else
    	{
        	Ametys.Msg.show({
				   title: "{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_ERROR}}",
				   msg: "{{i18n PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_ERROR_MSG}}",
				   buttons: Ext.Msg.OK,
				   icon: Ext.MessageBox.ERROR
			});
    	}
    }
});