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

/**
 * This tool allows to see items from an external datasource, in order to import them.
 */
Ext.define('Ametys.plugins.contentio.search.SCCSearchTool', {
    extend: 'Ametys.plugins.cms.search.AbstractSearchTool',
    
    /**
     * @private
     * @property {String} _collectionId The id of the collection in the tool
     */

    statics: {
      /**
         * Function to render the content title with its icon
         * @param {Object} value The data value
         * @param {Object} metaData A collection of metadata about the current cell
         * @param {Ext.data.Model} record The record
         */
        renderImported: function(value, metaData, record)
        {
            var cssClass;
            if (record.get('imported') === 'true' || record.get('imported') === true)
            {
                cssClass = 'item-imported';
            }
            else
            {
                cssClass = 'item-no-imported';
            }
            var title = '<span class="a-grid-glyph ametysicon-upload119 ' + cssClass + '" title="' + "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_SEARCH_BUTTON_IMPORT}}" + '"/>';
            title += value;
            
            return title;
        }
    },
    
    _possiblyCallInternalSetParams: function()
    {
        var params = this.getParams();
        if (!this._collectionId)
        {
            this._collectionId = params.collectionId;
            this.setTitle(params.collectionLabel);
        }
        else
        {
            this._paramsHasChanged = false;
            this._initSearchForm(params);
        }
        
        this._internalSetParams(false);
    },
    
    _getStoreCfg: function()
    {
        return {
            remoteSort: true,
            proxy: {
                type: 'ametys',
                plugin: 'contentio',
                url: 'scc-search/list.json',
                cancelOutdatedRequest: true,
                reader: this._getReaderCfg()
             },
             
             sortOnLoad: true,

             listeners: {
                 'beforeload': {fn: this._onBeforeLoad, scope: this},
                 'load': {fn: this._onLoad, scope: this}
             }
        };
    },

    _getReaderCfg: function()
    {
        return {
            type: 'json',
            rootProperty: 'items'
        };
    },
    
    _onSelectionChanged: function(sm, selected)
    {
        var button = this.searchPanel.down('#import-btn');
        if (button != null)
        {
            Ext.Array.filter(selected, function(record) {return record.get('imported') == false;}).length > 0 ? button.enable() : button.disable();
        }
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_NOSELECTION;
    },
    
    _getSearchFormPanelBBar: function()
    {
        var items = this.callParent(arguments);
        
        items.push('-');
        items.push({
            iconCls: 'ametysicon-upload119',
            itemId: 'import-btn',
            text: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_SEARCH_BUTTON_IMPORT}}",
            handler: this._importFn,
            scope: this,
            disabled: true
        });
        return items;
    },
    
    /**
     * @protected
     * Function to import the current selection
     */
    _importFn: function()
    {
    	// Deactivates grid interactions, pagination, buttons and load a mask
        this._setGridDisabled(true);
        this._getSearchToolbar().items.get('cancel').setDisabled(true);
        this._getSearchToolbar().items.get('import-btn').setDisabled(true);
        this.grid.mask("{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_LOAD_MASK}}");
        
        var selection = this.grid.getSelection();
        
        // Ouverture du tool de logs
        Ametys.tool.ToolsManager.openTool(
            'uitool-server-logs',
            {
                id: "uitool-sync-logs", 
                category: "org.ametys.plugins.contentio.synchronize.SynchronizableContentsCollectionHelper", 
                title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_SYNC_LOGS}}"
            }, 
            "cr"
        );
        
        /**
         * @private
         * @property {Number} _count Use to count how many elements have been handled to hide the mask
         */
        this._count = selection.length;
        Ext.Array.forEach(selection, function(item) {
            
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.contentio.synchronize.search.SCCSearchToolHelper",
                methodName: "importContent",
                parameters: [this.getParams().controllerId, this._collectionId, item.get("scc$uniqueid"), this._getAdditionalImportParams()],
                callback: {
                    handler: this._importFnCb,
                    scope: this,
                    ignoreOnError: false
                },
                errorMessage: {
                    msg: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_ERROR}}",
                    category: Ext.getClassName(this)
                },
                priority: Ametys.data.ServerComm.PRIORITY_LONG_REQUEST
            });
        }, this);
    },
    
    /**
     * @protected
     * Get the additional parameters to send to the import function
     * @return {Object} additional parameters
     */
    _getAdditionalImportParams: function()
    {
    	return {
            language: Ametys.cms.language.LanguageDAO.getCurrentLanguage()
        }
    },
    
    /**
     * @protected
     * Callback function after importing the remote values
     * @param {Object} result The server result
     */
    _importFnCb: function(result)
    {
    	this._count--;
    	
    	if (this._count == 0)
		{
	    	// Shows the out of date ribbon, activates grid interactions, pagination, buttons (but not imported one) and unload the mask
	        this.showOutOfDate();
	        this._setGridDisabled(false);
        	this.grid.unmask();
    	}
        
        if (result)
        {
	    	if (result.error == "alreadyImported")
	    	{
	            Ametys.notify({
	                type: 'warn',
	                iconGlyph: 'ametysicon-upload119',
	                title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_TITLE}}",
	                description: Ext.String.format("{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_ERROR_ALREADY_IMPORTED}}", result.contents[0].title)
	            });
	    	}
            else if (result.error == "noSyncCode")
            {
                Ametys.notify({
                    type: 'warn',
                    iconGlyph: 'ametysicon-upload119',
                    title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_TITLE}}",
                    description: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_ERROR_NO_SYNC_CODE}}"
                });
            }
	        else if (result.contents && result.contents.length > 0)
	        {
	            var contentIds = [];
	        
		        Ext.Array.each(result.contents, function (content){
		            contentIds.push(content.id);
		        });
		        
		        Ext.create("Ametys.message.Message", {
		            type: Ametys.message.Message.CREATED,
		            targets: {
		            id: Ametys.message.MessageTarget.CONTENT,
		                parameters: { ids: contentIds }
		            }
		        });
	            
	            var desc = result.contents.length == 1 ? Ext.String.format("{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_SUCCESS_SINGLE}}", result.contents[0].title) : Ext.String.format("{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_SUCCESS_MULTIPLE}}", result.total);
		        
	            Ametys.notify({
	                type: 'info',
	                iconGlyph: 'ametysicon-upload119',
	                title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_IMPORT_TITLE}}",
	                description: desc,
	                action: result.contents.length == 1 ? Ext.bind(Ametys.tool.ToolsManager.openTool, Ametys.tool.ToolsManager, ['uitool-content', {'id': result.contents[0].id}], false) : null
	            });
	            
	            if (result.contents.length == 1)
	            {
	                Ametys.tool.ToolsManager.openTool('uitool-content', {'id': result.contents[0].id});
	            }
	        }
        }
    },
    
    _retrieveCriteriaAndColumns: function(force)
    {
        this._updatingModel = true;
        
        Ametys.data.ServerComm.callMethod({
        	role: "org.ametys.plugins.contentio.synchronize.search.SCCSearchToolHelper",
        	methodName: "getSearchModelConfiguration",
            parameters: [this._collectionId],
        	callback: {
        		handler: this._getModelCb,
        		scope: this
        	},
            errorMessage: {
                msg: "{{i18n plugin.cms:UITOOL_SEARCH_ERROR}}",
                category: Ext.getClassName(this)
            }
        });
    },
    
    /**
     * @protected
     * Callback function after retrieving from server the search criteria and columns
     * @param {Object} result The server result
     */
    _getModelCb: function(result)
    {
        var toolParams = this.getParams().toolParams || {};
        this._configureSearchTool(result['criteria'], result, toolParams);
    },
    
    /**
     * Function called before loading the store
     * @param {Ext.data.Store} store The store
     * @param {Ext.data.operation.Operation} operation The object that will be passed to the Proxy to load the store
     * @private
     */
    _onBeforeLoad: function(store, operation)
    {
        if (this.grid && !this._updatingModel && (!(this.form instanceof Ametys.form.ConfigurableFormPanel) ||  this.form.isFormReady()))
        {
            this.grid.getView().unmask();
            
            if (!this.form.isValid())
            {
                this._stopSearch();
                return false;
            }
            
            operation.setParams( Ext.apply(operation.getParams() || {}, {
                collectionId: this._collectionId,
    			values: this.form.getJsonValues()
            }));
            
            this._error = null;
        }
        else
        {
            // avoid use less requests at startup (applyState...)
            return false;
        }
    },
    
    /**
     * Function called after loading results
     * @param {Ext.data.Store} store The store
     * @param {Ext.data.Model[]} records An array of records
     * @param {Boolean} successful True if the operation was successful.
     * @param {Ext.data.Operation} operation The operation that triggered this load.
     * @private
     */
    _onLoad: function (store, records, successful, operation)
    {
        if (operation.aborted)
        {
            // the load has been canceled. Do nothing.
            return;
        }
        
    	// Hack to process groups locally even if remoteSort is enabled.
        store.getData().setAutoGroup(true);
        
        this._setGridDisabled(false);
        
        if (!successful)
        {
            Ametys.log.ErrorDialog.display({
                title: "{{i18n plugin.cms:UITOOL_SEARCH_ERROR_TITLE}}",
                text: "{{i18n plugin.cms:UITOOL_SEARCH_ERROR}}",
                details: "",
                category: "Ametys.plugins.contentio.search.SCCSearchTool"
            });
            return;
        }
        
        if (this._error)
        {
            Ametys.log.ErrorDialog.display({
                title: "{{i18n plugin.cms:UITOOL_SEARCH_ERROR_QUERY_TITLE}}",
                text: this._error,
                details: "",
                category: "Ametys.plugins.contentio.search.SCCSearchTool"
            });
        }
        
        if (records.length == 0)
        {
            this.grid.getView().mask("{{i18n plugin.cms:UITOOL_CONTENTEDITIONGRID_NO_RESULT}}", 'ametys-mask-unloading');
        }
    }
});