/*
 *  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 defining the actions related to content types.
 * @private
 */
Ext.define('Ametys.plugins.contenttypeseditor.ContentTypesActions', {
	singleton: true,
	
    /**
     * @private
     * @property {Ametys.window.DialogBox} _exportExcelBox The dialog box for selecting a view to export.
     */
    
	/**
	 * Open content types
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	open: function(controller)
	{
		var targets = controller.getMatchingTargets();
        targets.forEach(function(target) 
        {
            Ametys.plugins.contenttypeseditor.ContentTypesActions.openById(target.getParameters().id); 
        });
	},
    
    /**
     * Open the content type with the given id 
     * @param {String} contentTypeId Id of the content type to open
     */
    openById: function(contentTypeId)
    {
        Ametys.tool.ToolsManager.openTool('uitool-contenttypeseditor', {id: contentTypeId});
    },
    
    /**
     * Export the content type in XLS format
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    exportExcel: function(controller)
    {
        var contentTypeIds = [];
            
        Ext.Array.each(controller.getMatchingTargets(), function(target){
            contentTypeIds.push(target.getParameters().id)
        });
        
        // Open the dialog to select the view to export
        this._displayExportDialogBox(contentTypeIds);
    },
    
    /**
     * @private
     * Display the dialog box to select a view to export to Excel format.
     * @param {String[]} contentTypeIds Selected content types
     */
    _displayExportDialogBox: function(contentTypeIds)
    {
        var formPanel = this._createSelectViewFormPanel(contentTypeIds);
        
        this._exportExcelBox = Ext.create('Ametys.window.DialogBox', {
            title: "{{i18n plugin.contenttypes-editor:PLUGINS_CONTENTTYPESEDITOR_EXPORT_DIALOG_TITLE}}",
            
            width: 450,
            scrollable: false,
            
            items: [ 
                {
                    xtype: 'container',
                    itemId: 'hint',
                    html: "{{i18n plugin.contenttypes-editor:PLUGINS_CONTENTTYPESEDITOR_EXPORT_DIALOG_HINT}}",
                    cls: 'a-text'
                }, 
                formPanel
            ],
            
            closeAction: 'destroy',
            buttons: [{
                text: "{{i18n plugin.contenttypes-editor:PLUGINS_CONTENTTYPESEDITOR_EXPORT_DIALOG_OK_BUTTON}}",
                handler: Ext.bind(this._exportExcelOk, this, [formPanel])
            }, {
                text: "{{i18n plugin.contenttypes-editor:PLUGINS_CONTENTTYPESEDITOR_EXPORT_DIALOG_CANCEL_BUTTON}}",
                handler: Ext.bind( function() {this._exportExcelBox.close();}, this)
            }]    
        });
        this._exportExcelBox.show();
    },
    
    /**
     * @private
     * Generates the Excel document with content types informations.
     * @param {Ext.form.Panel} formPanel The form panel
     */
    _exportExcelOk: function(formPanel)
    {
        var form = formPanel.getForm();
        if (!form.isValid())
        {
            return;
        }
        
        var url = Ametys.getPluginDirectPrefix('contenttypes-editor') + '/export/';
        
        var data = { viewName: form.findField("viewName").getValue() };
        var contentTypes = form.findField("contentTypes").getValue();
        if (contentTypes.length > 1)
        {
            url += 'content-types-archive.zip';
            data["contenttype-ids"] = contentTypes;
        }
        else
        {
            url += 'content-type.xls';
            data["contenttype-id"] = contentTypes[0];
        }
        
        this._exportExcelBox.close();
        
        Ametys.openWindow(url, data);
    },
    
    /**
     * @private
     * Creates the form panel to select a view.
     * @param {String[]} contentTypeIds The available content types
     * @return {Ext.form.Panel} The form panel
     */
    _createSelectViewFormPanel: function(contentTypeIds)
    {
        var formPanel = Ext.create('Ametys.form.ConfigurableFormPanel', {
            scrollable: false,
            flex: 1
        });
        
        formPanel.configure({
            contentTypes: {
                type: 'string',
                multiple: true,
                widget: 'edition.hidden'
            },
            viewName: {
                type: 'string',
                widget: 'edition.metadata-set',
                mandatory: false,
                'widget-params': {
                    contentTypesField: 'contentTypes',
                    includeInternals: true,
                    emptyText: "{{i18n plugin.contenttypes-editor:PLUGINS_CONTENTTYPESEDITOR_EXPORT_DIALOG_ALL_DATA}}",
                    hideLabel: true,
                    defaultValue: '',
                    value: '' // Also use value for default value because there are issues with empty default value
                }
            }
        });
        formPanel.setValues({values: {contentTypes: contentTypeIds}});
        
        return formPanel;
    },
    
     /**
     * Export a graph of content type to png format
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    exportGraph: function(controller)
    {
        var url = Ametys.getPluginDirectPrefix('contenttypes-editor') + '/export/content-types-graph.png';
        
        var contentTypeIds = [];
        Ext.Array.each(controller.getMatchingTargets(), function(target){
            contentTypeIds.push(target.getParameters().id)
        });
        
        var data = {};
        data["contenttype-ids"] = contentTypeIds;
        
        var tool = Ametys.tool.ToolsManager.getFocusedTool();
        if (tool.getParams().hierarchicalView)
        {
            data["isHierarchicalView"] = true;
        }
        
        Ametys.openWindow(url, data);
    },
    
    /**
     * Export a graph of all content types to png format
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    exportGraphForAllContentTypes: function(controller)
    {
        var url = Ametys.getPluginDirectPrefix('contenttypes-editor') + '/export/content-types-graph.png';
        var data = {'all' : true};
        
        Ametys.openWindow(url, data);
    },
    
    /**
     * Export the content type in zip format
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    exportZip: function(controller)
    {
        Ametys.openWindow(Ametys.getPluginDirectPrefix('contenttypes-editor') + '/export/content-types-archive.zip');
    },
    
    /**
     * Toggle content types
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     * @param {Boolean} isPressed State of button (pressed or not)
     */
    toggleContentTypes: function(controller, isPressed)
    {
        var tool = Ametys.tool.ToolsManager.getFocusedTool();
        
        var paramName = controller.getConfig('tool-param-to-edit');
        var params = {}
        params[paramName] = isPressed;
        tool.setParams(params);
    },
    
    /**
     * Display metadata detail according to the metadata path
     * @param {String} path The path of metadata
     */
    displayMetadataDetailByPath: function(path)
    {
        Ametys.tool.ToolsManager.getFocusedTool().displayMetadataDetailByPath(path);
    },
    
    /**
     * Display metatadatas of current content type in metadata tree
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     * @param {Boolean} isPressed State of button (pressed or not)
     */
    hideInheritedMetadata: function(controller, isPressed)
    {
        var tool = Ametys.tool.ToolsManager.getFocusedTool();
        tool._hideInheritedMetadata = isPressed;
        tool.refresh();
        controller.toggle(isPressed);
    }
    
});