/*
 *  Copyright 2016 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.
 */
/**
 * Tool for displaying the collections of synchronizable contents in a grid.
 */
Ext.define('Ametys.plugins.contentio.CollectionTool', {
    extend: "Ametys.tool.Tool",
    
    /**
     * @property {Ext.data.ArrayStore} _store The store
     * @private
     */
    
    /**
     * @property {Ext.grid.Panel} _grid The grid panel displaying the collections
     * @private
     */
    
    /**
     * @property {String} _selectionAfterRefresh If not null, the id of the population to select when the next refresh will be finished.
     * @private
     */
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onMessageCreated, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onMessageDeleted, this);
    },
    
    createPanel: function()
    {
        this._store = this._createStore();
        
        this._grid = Ext.create("Ext.grid.Panel", { 
            store: this._store,
            stateful: true,
            stateId: this.self.getName() + "$grid",
            
            columns: [
                {stateId: 'grid-title', header: "{{i18n PLUGINS_CONTENTIO_COLLECTIONS_TOOL_COLUMN_TITLE}}", flex: 1, sortable: true, dataIndex: 'label', renderer: Ametys.grid.GridColumnHelper.renderTextWithIcon},
                {stateId: 'grid-model', header: "{{i18n PLUGINS_CONTENTIO_COLLECTIONS_TOOL_COLUMN_MODEL}}", width: 200, sortable: true, dataIndex: 'model'},
                {stateId: 'grid-contenttype', header: "{{i18n PLUGINS_CONTENTIO_COLLECTIONS_TOOL_COLUMN_CONTENT_TYPE}}", width: 200, sortable: true, dataIndex: 'contentType'},
                {stateId: 'grid-id', header: "{{i18n PLUGINS_CONTENTIO_COLLECTIONS_TOOL_COLUMN_ID}}", width: 200, hidden: true, dataIndex: 'id'}
            ],
            
            listeners: {
            	'selectionchange': this.sendCurrentSelection, 
            	'itemdblclick': this.editCollection,
            	scope: this
            }
        });
        
        return this._grid;
    },
    
    /**
     * @private
     * Create the store for collections.
     * @return {Ext.data.Store} The store
     */
    _createStore: function ()
    {
        return Ext.create('Ext.data.Store', {
            autoDestroy: true,
            model: 'Ametys.plugins.contentio.CollectionTool.CollectionEntry',
            proxy: {
                type: 'ametys',
                plugin: 'contentio',
                url: 'collections.json',
                reader: {
                    type: 'json',
                    rootProperty: 'collections'
                }
             },
             
             sortOnLoad: true,
             sorters: [{property: 'label', direction:'ASC'}]
        });
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },
    
    setParams: function (params)
    {
        this.callParent(arguments);
        this.showOutOfDate();
    },
    
    refresh: function ()
    {
        this.showRefreshing();
        
        function callback()
        {
            this.showRefreshed();
            var record = this._store.getById(this._selectionAfterRefresh);
            if (record != null)
            {
                this._grid.getSelectionModel().select([record]);
                this._selectionAfterRefresh = null;
            }
        };
        this._store.load({callback: callback, scope: this});
    },
    
    sendCurrentSelection: function()
    {
        var selection = this._grid.getSelection();
        
        var targets = [];
        Ext.Array.forEach(selection, function(collection) {
            targets.push({
                id: Ametys.message.MessageTarget.SYNCHRONIZABLE_CONTENTS_COLLECTION,
                parameters: {
                    id: collection.get('id')
                }
            });
        }, this);
        
        Ext.create('Ametys.message.Message', {
            type: Ametys.message.Message.SELECTION_CHANGED,
            targets: targets
        });
    },
    
    /**
     * Handler when a collection is double clicked. Open the edition form
     * @param {Ext.view.View} view The view
     * @param {Ext.data.Model} record The double clicked item
     */
    editCollection: function (view, record) 
    { 
    	Ametys.cms.contentio.SynchronizableContentsCollectionDAO.getCollection([record.getId()], Ametys.plugins.contentio.CollectionActions.doEdit);
	},
    
    /**
     * Listener on creation message.
     * @param {Ametys.message.Message} message The creation message.
     * @private
     */
    _onMessageCreated: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.SYNCHRONIZABLE_CONTENTS_COLLECTION);
        if (targets.length > 0)
        {
            this._selectionAfterRefresh = targets[0].getParameters().id;
            this.showOutOfDate();
        }
    },
    
    /**
     * Listener on edition message.
     * @param {Ametys.message.Message} message The edition message.
     * @private
     */
    _onMessageModified: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.SYNCHRONIZABLE_CONTENTS_COLLECTION);
        if (targets.length > 0)
        {
            this.showOutOfDate();
        }
    },
    
    /**
     * Listener on deletion message.
     * @param {Ametys.message.Message} message The deletion message.
     * @private
     */
    _onMessageDeleted: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.SYNCHRONIZABLE_CONTENTS_COLLECTION);
        Ext.Array.forEach(targets, function(target) {
            var record = this._store.getById(target.getParameters().id);
            this._grid.getSelectionModel().deselect([record]);
            this._store.remove(record);
        }, this);
    }
    
});

/**
 * This class is the model for entries in the grid of the synchronizable contents collections tool
 * @private
 */
Ext.define("Ametys.plugins.contentio.CollectionTool.CollectionEntry", {
    extend: 'Ext.data.Model',
    
    fields: [
        {name: 'id'},    
        {name: 'label', type: 'string'},
        {name: 'contentType', type: 'string'},
        {name: 'model', type: 'string'},
        {name: 'isValid', mapping: 'isValid', type: 'boolean'},
		{name: 'iconGlyph', defaultValue: 'ametysicon-documents12'},
		{
			name: 'iconDecorator',
			calculate: function(data)
			{
				return data.isValid ? '' : 'decorator-ametysicon-caution9 a-grid-decorator-warn-color';
			}
		}
		
    ]
});

Ext.define("Ametys.message.SynchronizableContentsCollectionMessageTarget",{
    override: "Ametys.message.MessageTarget",
    statics: 
    {
        /**
         * @member Ametys.message.MessageTarget
         * @readonly
         * @property {String} SYNCHRONIZABLE_CONTENTS_COLLECTION The target of the message is a collection of synchronizable contents
         * @property {String} SYNCHRONIZABLE_CONTENTS_COLLECTION The id of the colelction
         */
        SYNCHRONIZABLE_CONTENTS_COLLECTION: "synchronizableContentsCollection"
    }
});