/*
 *  Copyright 2015 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 handle actions on newsletter.
 * @private
 */
 Ext.define('Ametys.plugins.newsletter.category.NewsletterActions', {
 	singleton: true,
 	
 	/**
 	 * @private
 	 * @property {Ametys.plugins.newsletter.category.AutomaticNewsletterUI} _dialog The dialog box for the automatic newsletters.
 	 */
 	
 	/**
 	 * @private
 	 * @property {Object} _openParams The parameters for the CreateContent helper.
 	 */
 	
 	/**
 	 * Creates a new newsletter.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	addNewsletter: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		if (target == null)
 		{
 			return;
 		}
 		
 		var categoryId = target.getParameters().id;
 		var lang = target.getParameters().lang;
 		
 		var btnConfig = controller.getInitialConfig();
 		
 		this._openParams = {
			contentLanguage: lang, 
			initWorkflowActionId: btnConfig.initWorkflowActionId,
			workflowName: btnConfig.workflowName,
			additionalWorkflowParameters: {
				'org.ametys.plugins.newsletter.workflow.CreateNewsletterFunction$category': categoryId,
				'org.ametys.web.repository.site.Site': Ametys.getAppParameter('siteName')
			},
			defaultContentTitle: btnConfig.defaultContentTitle,
			
			icon: '/plugins/newsletter/resources/img/newsletter_16.png',
			title: "{{i18n PLUGINS_NEWSLETTER_CONTENT_CREATENEWSLETTERACTION_TITLE}}" + '...',
			
			fullContents: true
		}
 		
 		// Retrieve the content type list and open the creation dialog box
 		var contentTypesIds = btnConfig.contentTypes.split(',');
        var contentTypes = Ametys.cms.content.ContentTypeDAO.getContentTypes().createFiltered(function (contentType) {
            return contentTypesIds.indexOf(contentType.getId()) != -1
                && !contentType.isMixin()
                && !contentType.isAbstract();
        });
        
 		this._openParams.contentTypes = contentTypes.getRange();
		
		Ametys.cms.uihelper.CreateContent.open (this._openParams, this._createCb, this);
 	},
 	
 	/**
 	 * Callback function called after the content was created.
 	 * @param {String/Ametys.cms.content.Content} content The created content as an id or a {@link Ametys.cms.content.Content}.
 	 * @private
 	 */
 	_createCb: function(content)
 	{
 		var params = {
			id: content.getId(),
			mode: 'view'
		};
		Ametys.tool.ToolsManager.openTool('uitool-content', params);
 	},
 	
 	// -----------------------------------------------------------------------
 	/**
 	 * Creates an automatic newsletter.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	setAutomaticNewsletter: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		if (target != null)
 		{
 			var categoryId = target.getParameters().id;
 			
 			Ametys.plugins.newsletter.category.AutomaticNewsletterUI.open (categoryId, Ext.bind(this._selectAutomaticNewsletter, this));
 		}
 	},
 	
 	/**
 	 * @private
 	 * Function invoked after selected the automatic newsletters
 	 * @param {String} categoryId the id of newsletter category
 	 * @param {String[]} autoNewsletterIds the ids of chosen automatic newsletters
 	 */
 	_selectAutomaticNewsletter: function (categoryId, autoNewsletterIds)
 	{
 		Ametys.data.ServerComm.callMethod({
			role: "org.ametys.plugins.newsletter.auto.AutomaticNewsletterDAO",
			methodName: 'setAutomaticNewsletters',
			parameters: [categoryId, autoNewsletterIds],
			callback: {
				handler: this._setAutomaticNewslettersCb,
				scope: this,
				arguments: {
					categoryId: categoryId
				}
			},
			errorMessage: {
				category: this.self.getName(),
				msg: "{{i18n PLUGINS_NEWSLETTER_AUTOMATIC_DIALOG_SET_ERROR}}"
			},
			waitMessage: true
		});
 	},
 	
 	/**
 	 * Callback function after the server succeeded in setting the automatic newsletters in the category.
 	 * @param {Object} response The response provided by the server.
 	 * @param {Object} args The callback arguments.
 	 * @private
 	 */
 	_setAutomaticNewslettersCb: function(response, args)
 	{
 		Ext.create("Ametys.message.Message", {
 			type: Ametys.message.Message.MODIFIED,
 			targets: {
 			    id: Ametys.message.MessageTarget.NEWSLETTER_CATEGORY,
 				parameters: {
 					ids: [args.categoryId]
 				}
 			}
 		});
 	}
 });