/*
 *  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.
 */

/**
 * Provides the action to insert the last publications in the editor
 */
Ext.define('Ametys.web.editor.InsertLastPublication', {
	singleton: true,
	
    /**
     * @property {Ametys.window.DialogBox} _box The dialog box to insert the last publication
     * @private
     */
	/**
	 * @property {String[]} _contentIds The content ids returned by the SelectContentBySearch dialogbox
	 * @private
	 */
	
	/**
	 * The action to call to insert the last publications
	 * @param {Ametys.cms.editor.EditorButtonController} controller the controller calling the action
	 */
	action: function(controller)
	{
        this._currentLanguage = Ametys.cms.language.LanguageDAO.getCurrentLanguage();
        var contentTarget = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget(Ametys.message.MessageTarget.CONTENT);
        if (contentTarget != null && contentTarget.getParameters().lang)
        {
            this._currentLanguage = contentTarget.getParameters().lang;
        }
        
        Ametys.cms.uihelper.SelectContentBySearch.open({
            modelId: controller.getInitialConfig('search-model'),
            multiple: true,
            
            icon: Ametys.CONTEXT_PATH + controller.getInitialConfig('icon-small'),
            title: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_DIALOG_TITLE}}", 
            helpmessage1: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_HELP_MSG1}}", 
            helpmessage2: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_HELP_MSG2}}",
            
            callback: Ext.bind(this._chooseContentCb, this)
        });
    },
    
    /**
     * Callback called after contents have been selected
     */
    _chooseContentCb: function(contentIds)
    {
        if (contentIds == null)
        {
            return;
        }
        
        this._contentIds = contentIds;
        
        // Box creation
        this._createDialogBox();
        
        // Initialize fields
        this._box.getComponent('viewName').getStore().load({
           params: {contentIds: this._contentIds},
           callback: this._viewLoadCb,
           scope: this
        });
        
        this._box.getComponent('level').reset();
        
        // Show box
        this._box.show();
    },
    
    /**
     * 
     * Creates the dialog box
     * @private
     */
    _createDialogBox: function()
    {
        this._box = Ext.create('Ametys.window.DialogBox', {
            title: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_DIALOG_TITLE}}",
            icon: Ametys.getPluginResourcesPrefix('web') + '/img/content/edition/insert_lastpublication_16.png',
            scrollable: false,
            
            width: 450,
            layout: { 
                type: 'vbox',
                align: 'stretch'
            },
            
            defaults : {
                cls: 'ametys',
                labelWidth: 100,
                labelAlign: 'right',
                labelSeparator: '',
                msgTarget: 'side'
            },
            
            items: [{
                xtype: 'component',
                cls: 'a-text',
                html: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_PARAM_HINT}}"
            },
            {
                xtype: 'combobox',
                name: 'viewName',
                itemId: 'viewName',
                fieldLabel: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_VIEW_LABEL}}",
                editable: false,
                forceSelection: true,
                allowBlank: false,
                valueField: 'value',
                displayField: 'label',
                queryMode: 'local',
                store: {
                    type: 'store', // Ext.data.Store
                    proxy: {
                        type: 'ametys',
                        plugin: 'web',
                        url: 'common-views.json',
                        reader: {
                            type: 'json',
                            rootProperty: 'views'
                        }
                    },
                    fields: [
                         {name: 'value', mapping: 'name'},
                         {name: 'label', mapping: 'label', type: 'string'}
                    ],
                    sortOnLoad: true,
                    sorters: [{property: 'label', direction:'ASC'}]
                }
            }, {
                xtype: 'combobox',
                name: 'level',
                itemId: 'level',
                fieldLabel: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_LABEL}}",
                editable: false,
                forceSelection: true,
                allowBlank: false,
                valueField: 'value',
                displayField: 'label',
                queryMode: 'local',
                value: 3,
                store: {
                    type: 'array', // Ext.data.ArrayStore
                    fields: ['value', 'label'],
                    data: [
                           [1, "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_1}}"],
                           [2, "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_2}}"],
                           [3, "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_3}}"]
                    ]
                }
            },
            {
                xtype: 'component',
                cls: 'a-text',
                html: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_EG}}",
                style: {fontStyle: 'italic'}
            }],
            
            closeAction: 'destroy',
            defaultFocus: 'viewName',
            
            referenceHolder: true,
            defaultButton: 'validate',
            
            buttons: [{
            	reference: 'validate',
                text : "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_OK_BTN}}",
                handler: Ext.bind(this._validate, this)
            }, {
                text : "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_LEVEL_CANCEL_BTN}}",
                handler: Ext.bind(function() {this._box.close();}, this) 
            }]
        });
    },
    
    /**
     * Load callback for the viewName combobox
     * @cfg {Ext.data.Model[]} records Array of records.
     * @cfg {Ext.data.operation.Operation} operation The load operation.
     * @cfg {Boolean} success True when operation completed successfully.
     */
    _viewLoadCb: function(records, operation, success)
    {
        var defaultValue = 'abstract',
            field = this._box.getComponent('viewName'),
            store = field.getStore();
        
        if (store.find('value', defaultValue) != -1)
        {
            field.setValue(defaultValue);
        }
        else
        {
            field.reset();
        }
    },
    
    /**
     * The button handler used to validate the dialog box.
     * @param {Ext.button.Button} button The button.
     * @param {Ext.event.Event} e The click event.
     */
    _validate: function(button, e)
    {
        var viewNameField = this._box.getComponent('viewName');
        var levelField = this._box.getComponent('level');
        
        if (!viewNameField.isValid() || !levelField.isValid())
        {
            return;
        }
        
        var params = {
            contentId: this._contentIds,
            viewName: viewNameField.getValue(),
            level: levelField.getValue(),
            lang: this._currentLanguage
        };
        
        var response = Ametys.data.ServerComm.send({
            plugin: 'web',
            url: 'contents/last-published',
            parameters:params, 
            callback: {
                handler : this._validateCb,
                scope: this
            },
            responseType: 'xml2text',
            waitMessage: true,
            errorMessage: "{{i18n PLUGINS_WEB_INSERTLASTPUBLICATION_ERROR}}"
        });
        
        this._box.close();
    },
    
    /**
     * The validate callback function.
     * Receive the last published content response from the server and insert the corresponding html
     * @param {Object} response The server response
     * @param {Object} args The callback arguments
     */
    _validateCb: function(response, args)
    {
        var html = Ext.dom.Query.selectValue('', response);
        
        // FIXME "tinyMCE.activeEditor" a better method is to use the field.getEditor()
        tinyMCE.activeEditor.focus();
        tinyMCE.activeEditor.execCommand('mceBeginUndoLevel');
        tinyMCE.insertHTMLAtRoot(html);
        tinyMCE.activeEditor.execCommand('mceEndUndoLevel');
    }
});