/*
 *  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 step of {@link Ametys.plugins.web.page.AddPageWizard} wizard allow to fill the properties of the content that will be created with the page.
 */
Ext.define("Ametys.plugins.web.page.AddPageWizard.ContentPropertiesCard", {
	
	extend: "Ametys.plugins.web.page.AddPageWizard.Card",

    name: "content-properties",
    
    resetModel: function (callback)
	{
		this._model = {
            'userDefinedTitle' : false
        };
        
        callback();
	},
	
	updateModel: function ()
	{
		this._model['contentFormValues'] = this._form.form.getFieldValues();
	},
    
    onEnter: function()
    {
        var fullModel = Ametys.plugins.web.page.AddPageWizard.getModel();
        
        this._contenttype = fullModel["contenttype"]
                                || Ametys.plugins.web.page.AddPageWizard.getInitialConfig('default-contenttype')
                                || Ametys.plugins.web.page.AddPageWizard.getInitialConfig('default-selected-contenttype');
        this._contenttitle = this._getContentTitle(fullModel);
        
        this._viewName = Ametys.plugins.web.page.AddPageWizard.getInitialConfig('content-createViewName');
    },
    
    updateUI: function (callback)
    {
        this._form.destroyComponents();
        
        if (!Ext.isEmpty(this._contenttype))
        {
            Ametys.data.ServerComm.callMethod({
                role: 'org.ametys.cms.contenttype.ContentTypesHelper',
                methodName: 'getViewAsJSON',
                parameters: [this._contenttype, this._viewName, true],
                callback: {
                    scope: this,
                    handler: this._drawCreationForm,
                    arguments: [callback]
                },
                waitMessage: false, // The tool is refreshing
                errorMessage: {
                    msg: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['content-properties']['error-message'],
                    category: Ext.getClassName(this)
                }
            });
        }
    },
    
    _drawCreationForm: function (response, args)
    {
        if (response.view)
        {
            // Draw form
            this._disableAdditionalCreation(response.view.elements);
            this._form.configure(response.view.elements);
            this._form.setValues(); // setValues must always be called for configurable form panel in order to complete its initialization
            // Reset values
            this._form.form.setValues(this._model['contentFormValues']);
            
            if (!this._model['userDefinedTitle'])
            {
                // If the title was not changed by the user, let's update it in case it should be the same as the page title
                this._form.form.setValues({'content.input.title' : this._contenttitle});
            }
            
            this._form.getField('content.input.title').on('change', this._onTitleChange, this);
        }
        
        // Callback
        var callback = args[0];
        if (Ext.isFunction(callback))
        {
            callback(true);
        }
    },
    
    _onTitleChange: function(field, newValue, oldValue, eOpts)
    {
        this._model['userDefinedTitle'] = true;
        this._contenttitle = newValue;
    },
    
    _disableAdditionalCreation: function (viewElements)
    {
        for (var i in viewElements)
        {
            var element = viewElements[i];
            var type = element.type ? element.type : null;
            
            if (!type || type == 'composite' || type == 'repeater')
            {
                this._disableAdditionalCreation (element.elements);
            }
            else
            {
                element['widget-params'] = element['widget-params'] || {};
                element['widget-params'].creatingContent = true;
            }
        }
    },
    
	createPanel: function() {
        this._form = Ext.create ('Ametys.form.ConfigurableFormPanel', {
            border: false,
            scrollable: true,
            labelAlign: 'top',
            
            defaultFieldConfig: {
                labelAlign: 'top',
                anchor: '100%'
            },
            
            bodyStyle: {
                padding: 0
            },
            
            additionalWidgetsConfFromParams: {
                contentType: 'contentType' // some widgets requires the contentType configuration  
            },
            
            fieldNamePrefix: 'content.input.',
            listeners: {
                'validitychange': Ext.bind(Ametys.plugins.web.page.AddPageWizard._onChange, Ametys.plugins.web.page.AddPageWizard)
            },
            
            displayGroupsDescriptions: false
        });
        
        return this._form;
    },
    
    _getContentTitle: function(fullModel)
    {
        var contentTitle = fullModel["default-content-title"] ? fullModel["default-content-title"] : (fullModel['title-long'] ? fullModel['title-long'] : fullModel['title']);
        return contentTitle;
    },
    
    apply: function(fullModel, callback) {
        var initConfig = Ametys.plugins.web.page.AddPageWizard.getInitialConfig();
        
        if (!this._model['userDefinedTitle'])
        {
            this._contenttitle = this._getContentTitle(fullModel);
            this._form.form.setValues({'content.input.title' : this._contenttitle});
        }
        
        var params = {
            contentType: fullModel["contenttype"],
            contentName: this._contenttitle,
            contentTitle: this._contenttitle,
            contentLanguage: fullModel["page-lang"],
            initWorkflowActionId: initConfig.workflowInitActionId,
            editWorkflowActionId: initConfig.workflowEditActionId,
            initAndEditWorkflowActionId : initConfig.workflowInitAndEditActionId,
            workflowName: initConfig['workflow-workflowName'],
            additionalWorkflowParameters: {
                'org.ametys.web.workflow.CreateContentFunction$pageId': fullModel["page-id"],
                'org.ametys.web.workflow.CreateContentFunction$zoneName': fullModel["zone"],
                'org.ametys.web.repository.site.Site': Ametys.getAppParameter('siteName')
            },
            viewName: initConfig['content-createViewName'],
            editFormValues: this._form.getJsonValues()
        };
        
        for (var c in initConfig)
        {
            if (c.indexOf("workflow-") == 0)
            {
                params.additionalWorkflowParameters[c.substr("workflow-".length)] = initConfig[c];
            }
        }
            
        Ametys.cms.content.ContentDAO.createContent(
            params,
            Ext.bind(this._applyContentCB, this, [fullModel, callback], 0),
            this, // scope
            true,
            null, 
            null, 
            Ametys.plugins.web.page.AddPageWizard._box
        );
    },
    
    /**
     * @private
     * Callback function after creating content
     * @param {Object} fullModel The full model.
     * @param {Function} callback The callback function
     * @param {Ametys.cms.content.Content} content The created content
     * @param {Object} fieldsInError The errors in fields
     * @param {Object} workflowMsgErrors The errors in workflow
     */
    _applyContentCB: function (fullModel, callback, content, fieldsInError, workflowMsgErrors)
    {
        if (!Ext.Object.isEmpty(fieldsInError) || !Ext.Object.isEmpty(workflowMsgErrors))
        {
            var detailedMsg = '<ul>';
            for (var key in fieldsInError)
            {
                detailedMsg += '<li>' + fieldsInError[key] + '</li>';
            }
            for (var key in workflowMsgErrors)
            {
                detailedMsg += '<li>' + workflowMsgErrors[key] + '</li>';
            }
            detailedMsg += '</ul>';
            
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_WEB_CREATEPAGE_ERRORS_MSG}}",
                msg: detailedMsg,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
        }
        else
        {
	        fullModel['content-id'] = content.getId();
	        // Open content tool
	        Ametys.plugins.web.page.AddPageWizard._contentId = content.getId();
	        callback(true);
        }
    },
  
    getUI: function ()
    {
        return this._form;
    },
    
    isModelOk: function(fullModel)
    {
        if (fullModel["contenttype"] && fullModel["title"] && this._form.getInvalidFields().length == 0)
        {
            // fullModel["page-lang"] removed because it will only be available during apply()
            return true;
        }
        return false;
    },

//    isProcessOk: function(fullModel)
//    {
//        return true;
//    },
    
    isAvailable: function(fullModel)
    {
        return fullModel["pagecontent-type"] == "contenttype" 
            && !Ext.isEmpty(fullModel["contenttype"])
            && (!fullModel["contenttype-view-names"] || fullModel["contenttype-view-names"].indexOf(Ametys.plugins.web.page.AddPageWizard.getInitialConfig('content-createViewName')) != -1);
    }
	
});