/*
 *  Copyright 2011 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 to create a new content. 
 * @private
 */
Ext.define('Ametys.plugins.cms.content.actions.CreateContentAction', {
	singleton: true,

	/**
	 * @cfg {String} contentTypes (required) The content types to be proposed for creation, separated by comma.
	 */
	
	/**
	 * @cfg {String|Object[]} contentLanguage (required) The language code of the content to create or a list of available languages
	 */
	
	/**
	 * @cfg {Boolean} [allowInherit=false] True to allow for creation the sub-content types of the listed content types.
	 */
	
	/**
	 * @cfg {Boolean} [workflowName] The content workflow name.
	 */
	
	/**
	 * @cfg {Number} [initWorkflowActionId=1] The id of initialize workflow action
	 */
	
	/**
	 * @cfg {Object} [additionalWorkflowParameters] Additionnal workflow parameters to be added to the server request. All parameters will be prefixed by "workflow-".
	 */
	
	/**
	 * @cfg {String} [defaultContentTitle] The default content title. The default value to initialize the content title field. If not provided, the name of the first content types will be used.
	 */
	
	/**
	 * @cfg {String} [dialogTitle] The title of the creation dialog box. If not provided, a default title will be displayed.
	 */
	/**
	 * @cfg {String} [dialogIcon] The path to icon (16x16 pixels) for the creation dialog box. If not provided, a default icon will be displayed.
	 */
	/**
	 * @cfg {String} [dialogHelpMessage1] The message displayed at the top of the dialog box. If not provided, a default message will be displayed.
	 */
	/**
	 * @cfg {String} [dialogHelpMessage2] The message displayed at the bottom of the dialog box. If not provided, a default message will be displayed.
	 */
	
	/**
	 * @cfg {Boolean} [directEdition=false] If true, the newly created content will be opened in edit mode after its creation. Otherwise, if will be opened in view mode.
	 * User edition right is checked: if user has no right to edit the content, the content will be open in view mode.
	 */
	/**
	 * @property {Boolean} _directEdition See {@link #cfg-directEdition}
	 * @private
	 */
	
	/**
	 * @cfg {Number} [editWorkflowActionId=2] The id of edit workflow action. This is used only if #cfg-directEdition is set to true.
	 */
	
	/**
	 * @property {Number} _editWorkflowActionId See {@link #cfg-editWorkflowActionId}
	 * @private
	 */
     
     /**
     * @cfg {String} [view-name=default-edition] The name of the view to use for content edition. This is used only if #cfg-directEdition is set to true.
     */
     
     /**
     * @property {String} _viewNameForEdition See {@link #cfg-view-name}
     * @private
     */
	
	/**
	 * Action function to be called by the controller.
	 * Update its state given the controller configuration and open the content creation dialog box.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 * @param {Function/boolean} [callbackOrState] The callback function invoked when the content has been created. The callback function will received the following parameters:
	 *                                             or the state provided by the ButtonController
     * @param {String/Ametys.cms.content.Content} callback.content The created content as an id or a {@link Ametys.cms.content.Content}.
	 * @param {Object} [scope=window] The callback scope
	 */
	act: function (controller, callbackOrState, scope)
	{
		var btnConfig = controller.getInitialConfig();
		
		// Content type id parameter is mandatory.
		var contentTypesIds = btnConfig['contentTypes'] || btnConfig['contentType'] || null;
		contentTypesIds = contentTypesIds == null ? [] : contentTypesIds.split(',');
		
		// Direct edition configuration.
		this._directEdition = btnConfig['directEdition'] == 'true';
		if (this._directEdition)
		{
			this._editWorkflowActionId = btnConfig['editWorkflowActionId'] ? Number(btnConfig['editWorkflowActionId']) : 2;
            this._viewNameForEdition = btnConfig['view-name'] || 'default-edition';
		}
		
		var allowInherit = btnConfig['allowInherit'] == 'true';
		var includePrivate = btnConfig['includePrivate'] == 'true';
		
		var cbFn = Ext.isFunction(callbackOrState) ? callbackOrState : this._finalizeCreation;
		var scope = scope || this;
		
		// Retrieves the content type list and open the creation dialog box.
        var contentTypes = Ametys.cms.content.ContentTypeDAO.getContentTypes();
        if (contentTypesIds.length > 0)
        {
            contentTypes = contentTypes.createFiltered(function(contentType) {
                return contentTypesIds.indexOf(contentType.getId()) != -1;
            });
            
            if (allowInherit)
            {
                var contentTypesAndInherited = Ext.create("Ext.util.Collection");
                
                contentTypes.each(function (contentType) {
                    var descendantsOrSelf = contentType.getDescendantsOrSelf();
                    contentTypesAndInherited.add(descendantsOrSelf.getRange());
                });
                
                contentTypes = contentTypesAndInherited;
            }
        }
        
        contentTypes = contentTypes.createFiltered(function(contentType) {
                return (!contentType.isPrivate() || includePrivate)
                    && !contentType.isMixin()
                    && !contentType.isAbstract();
            });
            
        if (contentTypes.count() == 0)
        {
            Ametys.Msg.show({
                   title: "{{i18n PLUGINS_CMS_CONTENT_CREATECONTENTACTION_WARNING}}",
                   msg: "{{i18n PLUGINS_CMS_CONTENT_CREATECONTENTACTION_NO_MATCHING_CONTENTTYPE_TEXT}}",
                   buttons: Ext.Msg.OK,
                   icon: Ext.MessageBox.WARNING
            });
        }
        else
        {
        
            contentTypes = contentTypes.createFiltered(function(contentType) {
                    return contentType.hasRight();
                });
                
    		if (contentTypes.count() == 0)
    		{
    			Ametys.Msg.show({
    				   title: "{{i18n PLUGINS_CMS_CONTENT_CREATECONTENTACTION_ERROR}}",
    				   msg: "{{i18n PLUGINS_CMS_CONTENT_CREATECONTENTACTION_CONTENTTYPES_HASNOTRIGHT_TEXT}}",
    				   buttons: Ext.Msg.OK,
    				   icon: Ext.MessageBox.ERROR
    			});
    		}
            else
            {
                this._createContent(contentTypes, btnConfig, cbFn, scope);
            }
        }
    },
    
    /**
     * Open the dialog to create a content.
     * @param {Ext.util.Collection} contentTypes The content types available for the content to create.
     * @param {Object} btnConfig The button configuration.
     * @param {Function} cbFn The callback function invoked when the content has been created.
     * @param {Object} scope The callback scope
     * @protected
     */
    _createContent: function(contentTypes, btnConfig, cbFn, scope)
    {
        var openParams = {
            contentTypes: contentTypes.getRange(),
            contentLanguage: btnConfig.contentLanguage,
            initWorkflowActionId: btnConfig.initWorkflowActionId,
            initAndEditWorkflowActionId: btnConfig.initAndEditWorkflowActionId,
            editWorkflowActionId: btnConfig.editWorkflowActionId,
            workflowName: btnConfig.workflowName,
            additionalWorkflowParameters: this._getAdditionalWorkflowParameters(btnConfig),
            defaultContentTitle: btnConfig.defaultContentTitle,
            rootContentPath: btnConfig.rootContentPath,
            
            icon: btnConfig.dialogIcon,
            iconCls: btnConfig.dialogIconCls,
            title: btnConfig.dialogTitle,
            helpmessage1: btnConfig.dialogHelpMessage1,
            helpmessage2: btnConfig.dialogHelpMessage2,
            
            initValues: btnConfig.initValues,
            forceValues: btnConfig.forceValues,
            forceMode: btnConfig.forceMode,
            
            fullContents: true
        }
        
        Ametys.cms.uihelper.CreateContent.open(openParams, cbFn, scope);
    },
	
	/**
	 * Get the additional workflow parameters
	 * @param {Object} btnConfig The controller configuration
	 * @return the additional workflow parameters 
	 */
	_getAdditionalWorkflowParameters: function (btnConfig)
	{
		return btnConfig.additionalWorkflowParameters;
	},
	
	/**
	 * Called at the end of process of creation.
	 * Open the 'content' tool
	 * @param {String} content the content id of the created content.
	 * @private
	 */
	_finalizeCreation: function(content)
	{
		var params = {
			id: content.getId(),
			mode: 'view'
		}
		
		if (this._directEdition)
		{
			// Check if edit action is available
			if (Ext.Array.contains(content.getAvailableActions(), this._editWorkflowActionId))
			{
				params.mode = 'edit';
				params['edit-workflow-action'] = this._editWorkflowActionId;
                params['view-name'] = this._viewNameForEdition;
			}
		}
		
		Ametys.tool.ToolsManager.openTool('uitool-content', params);
	}
});