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

/**
 * This tool displays the list of unknown users
 * @private
 */
Ext.define('Ametys.plugins.admin.user.UnknownUsersTool', {
    extend: 'Ametys.tool.Tool',
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageEdited, this);
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },
    
    createPanel: function()
    {
        this._store = this.createUnknownUserStore();
        this._store.getData().setMultiSortLimit(2);
        
        // Search input
        this._searchField = Ext.create('Ext.form.TextField', {
            xtype: 'textfield',
            cls: 'ametys',
            maxWidth: 250,
            flex: 1,
            emptyText: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_SEARCH_EMPTY_TEXT}}",
            listeners: {change: Ext.Function.createBuffered(() => this._store.load(), 500, this)}
        });
        
        this._grid = Ext.create("Ext.grid.Panel", {
            store: this._store,
            scrollable: true,
            stateful: true,
            stateId: this.getId() + "$grid",
            cls: 'uitool-unknown-users',
            
            columns: [
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_TO_FORGET}}", width: 50, sortable: true, dataIndex: 'forget', renderer: this._renderStatus, stateful: true, stateId: 'col-forget'},
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_FULLNAME}}", width: 200, sortable: true, dataIndex: 'fullname', stateful: true, stateId:'col-fullname' },
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_EMAIL}}", width: 200, sortable: true, hidden: true, dataIndex: 'email', stateful: true, stateId: 'col-email'},
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_LOGIN}}", width: 200, sortable: true, dataIndex: 'login', stateful: true, stateId: 'col-login'},
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_POPULATION}}", width: 200, sortable: false, dataIndex: 'populationLabel', stateful: true, stateId: 'col-populationLabel'},
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_POPULATIONID}}", width: 200, sortable: true, hidden: true, dataIndex: 'populationId', stateful: true, stateId: 'col-populationId'},
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_LAST_CONNECTION}}", width: 160, sortable: true, dataIndex: 'last_connection_date', renderer: Ametys.grid.GridColumnHelper.renderDateTime, stateful: true, stateId: 'col-last_connection_date'}, 
                {header: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_COL_MISSING_SINCE}}", width: 180, sortable: true, dataIndex: 'missing_date', renderer: Ametys.grid.GridColumnHelper.renderDateTime, stateful: true, stateId: 'col-missing_date'}
            ],
            multiColumnSort: true,
            
            selModel : {
                mode: 'MULTI'
            },
            
            dockedItems: [
                {
                    xtype: 'toolbar',
                    layout: { 
                        type: 'hbox',
                        align: 'stretch'
                    },
                    dock: 'top',
                    items: [
                        this._searchField,
                        {
                            // Clear filter
                            tooltip: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_CLEAR_FILTER}}",
                            handler: Ext.bind(this._clearFilter, this),
                            iconCls: 'a-btn-glyph ametysicon-eraser11 size-16',
                            cls: 'a-btn-light'
                        }
                    ],
                },
                {
                    xtype: 'pagingtoolbar',
                    store: this._store,
                    dock: 'bottom',
                    displayInfo: true,
                    displayMsg: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_PAGEBAR_RESULT_1}}{0}{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_PAGEBAR_RESULT_2}}{1}{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_PAGEBAR_RESULT_3}}{2}",
                    emptyMsg: "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_PAGEBAR_NO_RESULT}}"
                }
            ],
            
            listeners: {
                selectionchange: {fn: this._onSelectionChange, scope: this}
            }
        });
        
        return this._grid;
    },
    
    /**
     * @private
     */
    createUnknownUserStore: function() {
        var storeConfig = {
            autoLoad: true,
            
            model: 'Ametys.plugins.admin.user.UnknownUser',
            proxy: {
                type: 'ametys',
                role: 'org.ametys.core.user.status.UserStatusManager',
                methodName: 'searchUnknownUsers',
                methodArguments: ["pattern", "start", "limit", "sorters"],
                reader: {
                    type: 'json',
                    rootProperty: "unknownUsers",
                    totalProperty: "total"
                }
            },
            remoteSort: true,
            remoteFilter: true,
            sorters: [{property: "forget", direction: 'DESC'}, {property: "last_connection_date", direction: 'ASC'}],
            
            listeners: {
                'beforeload': {fn: this._onBeforeLoad, scope: this}
            }
        };

        return Ext.create('Ext.data.Store', storeConfig);
    },
    
    _onBeforeLoad: function(store, op)
    {
        var params = op.getParams() || {};
        
        var sorters = []
        store.getSorters().each(sorter => {
            var property = sorter.getProperty();
            var direction = sorter.getDirection();
            if (property == "fullname")
            {
                // the fullname column is actually a combination of two property
                sorters.push({property: "lastname", direction: direction})
                sorters.push({property: "firstname", direction: direction})
            }
            else
            {
                sorters.push({property: property, direction: direction})
            }
        })
        params.sorters = sorters;
        
        params.pattern = this._searchField.getValue();
        
        op.setParams(params);
    },
    
    /**
     * Clear the current filter
     * @private
     */
    _clearFilter: function()
    {
        this._searchField.reset();
    },
    
    sendCurrentSelection: function()
    {
        var selection = this._grid.getSelectionModel().getSelection();
        var targets = [];
        
        Ext.Array.forEach(selection, function(record) {
            targets.push({
                id: Ametys.message.MessageTarget.UNKNOWN_USER,
                parameters: {
                    login: record.get('login'),
                    populationId: record.get('populationId'),
                    forget: record.get('forget')
                }
            })
        }, this);
        
        Ext.create('Ametys.message.Message', {
            type: Ametys.message.Message.SELECTION_CHANGED,
            targets: targets
        });
    },
    
    refresh: function()
    {
        this._store.load({
            scope: this,
            callback: this.showUpToDate
        });
    },

    /**
     * @private
     */
    _onSelectionChange: function(model, selected, eOpts)
    {
        this.sendCurrentSelection();
    },
    
    /**
     * @private
     */
    _onMessageEdited: function(message)
    {
        var userTargets = message.getTargets(Ametys.message.MessageTarget.UNKNOWN_USER);
        if (userTargets)
        {
            // Update visible entry
            Ext.Array.forEach(userTargets, function(target) {
                var login = target.getParameters().login;
                var populationId = target.getParameters().populationId;
                var idx = this._store.findBy(record => record.get("login") == login && record.get("populationId") == populationId)
                if (idx > -1)
                {
                    this._store.getAt(idx).set("forget", target.getParameters().forget, {commit: true})
                }
            }, this);
            
            // update current selection (only if focus thanks to protection)
            this.sendCurrentSelection();
        }
    },
    
    /**
     * @private
     */
    _renderStatus: function(value)
    {
        var isTrue = Ext.isBoolean(value) ? value : value == 'true';
        if (isTrue)
        {
            return '<span class="a-grid-glyph running ametysicon-multimedia-command-play" title="' + "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_CHECKED_TITLE}}" + '"></span>';
        }
        else
        {
            return '<span class="a-grid-glyph ametysicon-datetime-clock" title="' + "{{i18n PLUGINS_ADMIN_UNKNOWN_USERS_TOOL_CHECKED_TITLE}}" + '"></span>';
        }
    },
});