/*
 *  Copyright 2024 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 to display force subscriptions
 */
Ext.define('Ametys.plugins.page.subscription.ForceSubscriptionsTool', {
    extend: "Ametys.tool.Tool",
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onSubscriptionChanged, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onSubscriptionChanged, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onSubscriptionDeleted, this);
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },
    
    /**
     * Call after subscription is modified or deleted
     * @param {Object} message The target message
     * @private
     */
    _onSubscriptionChanged: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.SUBSCRIPTION);
        if (targets.length > 0)
        {
            this._subscriptionId = targets[0].getParameters().id;
            this.showOutOfDate(); 
        }
    },
    
    /**
     * Listener upon reception of a deletion message
     * @param {Ametys.message.Message} message the deletion message
     * @private
     */
    _onSubscriptionDeleted: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.SUBSCRIPTION);
        if (targets.length > 0)
        {
            this._subscriptionId = null;
            var store = this._subscriptionsStore;
            var index = store.find("id", targets[0].getParameters().id); 
            if (index != -1)
            {
                store.removeAt(index);
            }
            
            if (this._subscriptionsStore.getCount() > 0)
            {
                this._subscriptionsGrid.getView().unmask();
            }
            else 
            {
                this._subscriptionsGrid.getView().mask("{{i18n PLUGINS_PAGE_SUBSCRIBE_USER_SUBSCRIPTIONS_FORCE_TOOL_NO_SUBSCRIPTION}}", 'ametys-mask-unloading');
            }
        }
    },
    
    setParams: function (params)
    {
        this.callParent(arguments);
        this.refresh();
    },
    
    refresh: function()
    {
        this.showRefreshing();
        
        this.callParent(arguments);

        this._subscriptionsStore.load({
            callback: Ext.bind(function() {
                this._refreshCb();
            }, this)
        });
    },
    
    /**
     * After refresh, select the subscription. If null, select the first
     * @private
     */
    _refreshCb: function()
    {
        if (this._subscriptionsStore.getCount() > 0)
        {
            this._subscriptionsGrid.getView().unmask();
            if (this._subscriptionId)
            {
                var index = this._subscriptionsStore.find("id", this._subscriptionId);
                if (index != -1)
                {
                    this._subscriptionsGrid.getSelectionModel().select(index);
                }
            }
        }
        else
        {
            this._subscriptionsGrid.getView().mask("{{i18n PLUGINS_PAGE_SUBSCRIBE_USER_SUBSCRIPTIONS_FORCE_TOOL_NO_SUBSCRIPTION}}", 'ametys-mask-unloading');
        }
        
        this.showRefreshed();
    },
    
    sendCurrentSelection: function()
    {
        var selection = this._subscriptionsGrid.getSelectionModel().getSelection();
        if (selection.length > 0)
        {
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.SELECTION_CHANGED,
                targets: {
                    id: Ametys.message.MessageTarget.SUBSCRIPTION,
                    parameters: {
                        id: selection[0].id // no multi selection
                    }
                }
            });
        }
        else
        {
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.SELECTION_CHANGED,
                targets: []
            });
        }
    },
    
    createPanel: function()
    {
        this._panel = Ext.create('Ext.Panel', { 
            cls: 'force-subscriptions-tool',
            scrollable: true,
            items: [
                this._getSubscriptionsPanel()
            ]
        });
        
        return this._panel;            
    },
    
    /**
     * Get the subscriptions panel
     * @private
     */
    _getSubscriptionsPanel: function()
    {
        this._subscriptionsStore = Ext.create('Ext.data.Store', {
            proxy: {
                type: 'ametys',
                role: 'org.ametys.plugins.pagesubscription.dao.ForceTagSubscriptionsDAO',
                methodName: 'getForceGroupSubscriptions',
                methodArguments: ['siteName'],
                reader: {
                    type: 'json'
                },
                extraParams: {
                    siteName: Ametys.getAppParameter('siteName')
                }
            },
            fields: [
                {name: 'thematic'},
                {name: 'tag'},
                {
                    name: 'tagLabel',
                    convert: function(value, record) {
                        return value || (record.data.tag ? record.data.tag.label : null);
                    },
                    depends: [ 'tag' ]
                },
                {name: 'broadcastChannel'},
                {name: 'group'},
                {
                    name: 'groupLabel',
                    convert: function(value, record) {
                        return value || (record.data.group ? record.data.group.label : null);
                    },
                    depends: [ 'group' ]
                }
            ],
            groupField: 'groupLabel',
        });
        
        this._subscriptionsGrid = Ext.create('Ext.grid.Panel',{
            minHeight: 250,
            scrollable: true,
            store : this._subscriptionsStore,
            stateful: true,
            stateId: this.self.getName() + "$subscriptiongrid",
            columns: [
                {stateId: 'grid-column-group', header: "{{i18n PLUGINS_PAGE_SUBSCRIBE_USER_SUBSCRIPTIONS_FORCE_GROUP_FIELD_LABEL}}", sortable: true, flex: 1, dataIndex: 'groupLabel', hidden: true},
                {stateId: 'grid-column-tag', header: "{{i18n PLUGINS_PAGE_SUBSCRIBE_USER_SUBSCRIPTIONS_FORCE_TAG_FIELD_LABEL}}", sortable: true, flex: 1, dataIndex: 'tagLabel'},
                {stateId: 'grid-column-frequency', header: "{{i18n PLUGINS_PAGE_SUBSCRIBE_USER_SUBSCRIPTIONS_FORCE_FREQUENCY_FIELD_LABEL}}", flex: 1, dataIndex: 'frequency', renderer: Ext.bind(this._renderFrequency, this)},
                {stateId: 'grid-column-channel', header: "{{i18n PLUGINS_PAGE_SUBSCRIBE_USER_SUBSCRIPTIONS_FORCE_BROADCAST_CHANNEL_FIELD_LABEL}}", flex: 1, dataIndex: 'broadcastChannel', renderer: Ext.bind(this._renderBroadcastChannel, this)},
            ],
            features: [{
                groupHeaderTpl: ['{name}'],
                ftype: 'grouping'
            }],
        });
        
        this._subscriptionsGrid.on('selectionchange', this.sendCurrentSelection, this);
        
        return this._subscriptionsGrid;
    },
    
    /**
     * @private
     * Render the subscription frequency
     * @param {Object} value The data value
     * @param {Object} metaData A collection of metadata about the current cell
     * @param {Ext.data.Model} record The record
     * @return {String} the render
     */
    _renderFrequency: function (value, metaData, record)
    {
        return value.label;
    },
    
    /**
     * @private
     * Render the subscription canal
     * @param {Object} value The data value
     * @param {Object} metaData A collection of metadata about the current cell
     * @param {Ext.data.Model} record The record
     * @return {String} the render
     */
    _renderBroadcastChannel: function (value, metaData, record)
    {
        return value.map(v => v.label).join(", ");
    }
});

/** Class defining target message names for subscriptions */
Ext.define("Ametys.message.SubscriptionMessageTarget",
{
    override: "Ametys.message.MessageTarget",
    
    statics: 
    {
        /**
         * @member Ametys.message.MessageTarget
         * @readonly
         * @property {String} SUBSCRIPTION The target type is a subscription. The expected parameters are:  
         * @property {String} SUBSCRIPTION.id The id of the subscription
         */
        SUBSCRIPTION: "subscription"
    }
});