/*
 *  Copyright 2017 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.
 */
 
 /**
  * Singleton class for actions on candidates
  */
Ext.define('Ametys.plugins.cms.content.actions.CandidatesActions', {
    singleton: true,
    
    /**
     * @property {String} CANDIDATE_MIXIN The id of mixin for candidates
     */
    CANDIDATE_MIXIN: "org.ametys.cms.referencetable.mixin.Candidate",
    
    /**
     * Open dialog box to create or edit a candidate
     * @param {Object} config
     * @param {String} config.mode The mode : 'new' to create a candidate, 'edit' to edit a candidate
     * @param {String} [config.contentType] The content type for candidate to create. Mandatory if mode equals 'new'.
     * @param {String} [config.contentId] The id of candidate to edit. Mandatory if mode equals 'edit'.
     * @param {String} [config.contentTitle] The title of candidate to create. Only used if mode equals 'new'.
     * @param {Number} [config.workflowName=reference-table] The workflow name.
     * @param {Number} [config.initWorkflowActionId=1] The action id of initialize the workflow. Only used if mode equals 'new'.
     * @param {Number} [config.editWorkflowActionId=2] The workflow action for edition.
     * @param {Number} [config.initAndEditWorkflowActionId=1] The action id of initialize the workflow. Only used if mode equals 'new'.
     */
    open: function(config)
    {
        this._createDialogBox(config);
        this._initializeAndShow(config);
    },
    
    /**
     * Create a new candidate
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    createCandidate: function(controller)
    {
        var tool = Ametys.tool.ToolsManager.getFocusedTool();
        
        this.open({
            mode: 'new',
            contentType: tool.getParams().contentType,
            contentLanguage: Ametys.cms.language.LanguageDAO.getCurrentLanguage(),
            initWorkflowActionId: controller.getInitialConfig('initWorkflowActionId'),
            initAndEditWorkflowActionId: controller.getInitialConfig('initAndEditWorkflowActionId'),
            editWorkflowActionId: controller.getInitialConfig('editWorkflowActionId'),
            workflowName: controller.getInitialConfig('workflowName')
        });
    },
    
    /**
     * Edit a candidate
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    editCandidate: function(controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            var target = targets[0];
            
            this.open({
                mode: 'edit',
                contentId: targets[0].getParameters().id,
	            editWorkflowActionId: controller.getInitialConfig('editWorkflowActionId'),
                workflowName: controller.getInitialConfig('workflowName')
	        }, targets[0].getParameters().id);
        }
    },
    
    /**
     * @private
     * Create the dialog box if not exists
     * @param {Object} config The configuration object
     * @param {String} config.mode The mode : 'new' to create a candidate, 'edit' to edit a candidate
     * @param {String} [config.contentType] The content type for candidate to create
     * @param {String} [config.contentId] The id of candidate to edit
     * @param {String} [config.contentTitle] The title of candidate to create.
     * @param {Number} [config.contentLanguage] The content language
     * @param {Number} [config.workflowName=reference-table] The workflow name
     * @param {Number} [config.initWorkflowActionId=1] The action id of initialize the workflow
     * @param {Number} [config.editWorkflowActionId=2] The workflow action for edition
     * @param {Number} [config.initAndEditWorkflowActionId=1] The action id of initialize the workflow
     */
    _createDialogBox: function(config)
    {
        if (!this._box)
        {
	        this._form = Ext.create ('Ametys.form.ConfigurableFormPanel', {
	            border: false,
	            scrollable: false,
	            
	            defaultFieldConfig: {
	                labelWidth: 130,
	                anchor: '100%'
	            },
	            
	            bodyStyle: {
	                padding: 0
	            },
	            
	            fieldNamePrefix: 'content.input.',
	        });
	        
	        this._box = Ext.create('Ametys.window.DialogBox', {
	            title: config.mode == 'edit' ? "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_EDIT_CANDIDATE_LABEL}}" : "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_ADD_CANDIDATE_LABEL}}",
	            iconCls: 'ametysicon-star129 ' + (config.mode == 'edit' ? 'decorator-ametysicon-edit45' : 'decorator-ametysicon-add64'),
	            
	            width: 500,
	            scrollable: true,
	    
	            layout: 'anchor',
	            defaultType: 'textfield',
	            defaults: {
	                cls: 'ametys',
	                labelAlign: 'right',
	                labelSeparator: '',
	                labelWidth: 130,
	                anchor: '100%',
	                style: 'margin-right:' + (Ametys.form.ConfigurableFormPanel.OFFSET_FIELDSET + 10 + Ametys.form.ConfigurableFormPanel.PADDING_TAB) + 'px'
	            },
	                
	            items: [this._form],
	            
	            selectDefaultFocus: true,
	            closeAction: 'hide',
	                
	            referenceHolder: true,
	            defaultButton: 'validate',
	                
	            buttons : [{
	                reference: 'validate',
                    itemId:'ok-btn',
	                text :"{{i18n PLUGINS_CMS_CONTENT_UIHELPER_CREATECONTENT_OK}}"
	            }, {
	                text :"{{i18n PLUGINS_CMS_CONTENT_UIHELPER_CREATECONTENT_CANCEL}}",
	                handler: Ext.bind(function() {this._box.close();}, this) 
	            }]
	        });
            
            // Configure form
            this._form.configure({
	             "title": {
	                label: "{{i18n PLUGINS_CMS_HIERARCHICAL_REFERENCE_TABLES_CANDIDATE_TITLE_LABEL}}",
	                description: "{{i18n PLUGINS_CMS_HIERARCHICAL_REFERENCE_TABLES_CANDIDATE_TITLE_DESC}}",
	                type: "string",
	                validation: {
	                     mandatory: true
	                },
	                multiple: false
	            },
	            "comment": {
	                label: "{{i18n PLUGINS_CMS_HIERARCHICAL_REFERENCE_TABLES_CANDIDATE_COMMENT_LABEL}}",
	                description: "{{i18n PLUGINS_CMS_HIERARCHICAL_REFERENCE_TABLES_CANDIDATE_COMMENT_DESC}}",
	                type: "string",
	                widget: 'edition.textarea',
	                multiple: false
	            }
	        });
        }
        else
        {
            this._box.setTitle(config.mode == 'edit' ? "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_EDIT_CANDIDATE_LABEL}}" : "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_ADD_CANDIDATE_LABEL}}");
            this._box.setIconCls('ametysicon-star129 ' + (config.mode == 'edit' ? 'decorator-ametysicon-edit45' : 'decorator-ametysicon-add64'));
        }
        
        this._box.down("button[itemId='ok-btn']").setHandler (Ext.bind(this._validate, this, [config]));
    },
    
    /**
     * @private
     * Initialize and show the dialog box
     * @param {Object} config The configuration object
     * @param {String} config.contentType The content type for candidate
     * @param {Number} config.contentLanguage The content language
     * @param {Number} [config.workflowName=reference-table] The workflow name
     * @param {Number} [config.initWorkflowActionId=1] The action id of initialize the workflow
     * @param {Number} [config.editWorkflowActionId=2] The workflow action for edition
     * @param {Number} [config.initAndEditWorkflowActionId=1] The action id of initialize the workflow
     * @param {String} [config.contentId] The id of content to edit
     */
    _initializeAndShow:function(config)
    {
        if (!config.contentId)
        {
            var values = {
                values: {
                    'title': config.contentTitle || "{{i18n PLUGINS_CMS_HIERARCHICAL_REFERENCE_TABLES_CANDIDATE_DEFAULT_TITLE}}",
                    'comment': ''
                }
            };
	        this._form.setValues(values);
            this._box.show();
        }
        else
        {
            Ametys.data.ServerComm.callMethod({
	            role: "org.ametys.cms.content.referencetable.HierarchicalReferenceTablesHelper",
	            methodName: "getCandidateValues",
	            parameters: [config.contentId],
	            callback: {
	                handler: function(values) {
		                this._form.setValues({
		                    values: values
		                });
		                this._box.show();
		            },
	                scope: this
	            },
	            waitMessage: false
	        });
        }
    },
    
    /**
     * Handler on validating dialog box.
     * Creates or edits the candidate
     * @param {Object} config The configuration object
     * @param {String} config.contentType The content type for candidate
     * @param {Number} [config.contentLanguage] The content language
     * @param {Number} [config.workflowName=reference-table] The workflow name
     * @param {Number} [config.initWorkflowActionId=1] The action id of initialize the workflow
     * @param {Number} [config.editWorkflowActionId=2] The workflow action for edition
     * @param {Number} [config.initAndEditWorkflowActionId=1] The action id of initialize the workflow
     * @param {String} [config.contentId] The id of content to edit
     * @private
     */
    _validate: function(config)
    {
        var formValues = this._form.getJsonValues();
        
        if (config.mode == 'new')
        {
            var params = {
	            contentType: config.contentType,
	            contentTitle: formValues['content.input.title'],
	            contentLanguage: config.contentLanguage,
	            initWorkflowActionId: config.initWorkflowActionId || 1,
	            initAndEditWorkflowActionId: config.initAndEditWorkflowActionId || 1,
	            editWorkflowActionId: config.editWorkflowActionId || 2,
	            workflowName: config.workflowName || 'reference-table',
	            additionalWorkflowParameters: {
                    'org.ametys.cms.workflow.CreateContentFunction$mixins': this.CANDIDATE_MIXIN
                },
	            viewName: null,
	            editFormValues: formValues
	        };
	        
	        Ametys.cms.content.ContentDAO.createContent(
	            params,
	            this._createCb,
	            this, // scope
	            true,
	            Ametys.message.MessageTarget.REFERENCE_TABLE_CANDIDATE, 
	            null, 
	            this._box
	        );
        }
        else
        {
            var params = {
                contentId: config.contentId,
                values: formValues,
                viewName: null,
                editWorkflowActionId: config.editWorkflowActionId || 2
            };
            
            Ametys.cms.content.ContentDAO.editContent(
                params, 
                this._editCb, 
                this, 
                true, 
                Ametys.message.MessageTarget.REFERENCE_TABLE_CANDIDATE, 
                null, 
                this._box
            );
        }
    },
    
    /**
     * @private
     * Callback function invoked after creating a candidate
     * @param {Ametys.cms.content.Content} content The created content
     */
    _createCb: function(content)
    {
        if (content != null)
        {
            this._box.close();
        }
    },
    
    /**
     * @private
     * Callback function invoked after editing a candidate
     * @param {Boolean} success true if the content was sucessfully edited
     * @param {Ametys.cms.content.Content} content The edited content
     */
    _editCb: function(success, content)
    {
        if (success)
        {
            this._box.close();
        }
    },
    
    /**
     * Validate a candidate.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    validateCandidate: function(controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            var target = targets[0],
                contentId = targets[0].getParameters().id,
                actionId = parseInt(controller.getInitialConfig("editWorkflowActionId") || 220);
            
            controller.serverCall("validateCandidate", [contentId, actionId], Ext.bind(this._validateCandidateCb, this, [contentId], 1), {errorMessage: "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_VALIDATE_ERROR}}"});
        }
    },
    
    /**
     * @private
     * CallBack function after a candidate has been validated
     * @param {Object} result the server result
     * @param {String} contentId the id of content being validated
     */
    _validateCandidateCb: function(result, contentId)
    {
        if (result && result.success)
        {
	        Ametys.cms.content.ContentDAO.getContent(contentId, function (content) {
	            
	            Ext.create('Ametys.message.Message', {
	                type: Ametys.message.Message.DELETED,
	                targets: {
	                    id: Ametys.message.MessageTarget.REFERENCE_TABLE_CANDIDATE,
	                    parameters: {
	                        contents: [content]
	                    }
	                }
	            });
	            
	            Ext.create('Ametys.message.Message', {
	                type: Ametys.message.Message.CREATED,
	                targets: {
	                    id: Ametys.message.MessageTarget.REFERENCE_TABLE_CONTENT,
	                    parameters: {
	                        contents: [content]
	                    }
	                }
	            });
	            
	        });
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_VALIDATE_CANDIDATE_LABEL}}",
                msg: "{{i18n PLUGINS_CMS_UITOOL_HIERARCHICAL_REFERENCE_TABLES_VALIDATE_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
        }
    }
});