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

/**
 * Class to handle system announce.
 * This constructor sends a check request, that will send another one on callback.
 * @private
 */
Ext.define('Ametys.plugins.coreui.system.Announce', {
    singleton: true,
    
    /**
     * @private
     * @property {Number} _lastModification The date (as long) or 0 if not applicable, of the known system statup time.
     */
    _lastModification: 0,
    /**
     * @private
     * @property {Number} _lastMaintenance The date (as long) or 0 if not applicable, of the known system statup time.
     */
    _lastMaintenance: 0,
    /**
     * @private
     * Send a check request.
     */
    _sendCheckMessage: function()
    {
        // Define a 'no.system.message' application parameter to 'true' to disable ping.
        if (Ametys.getAppParameter('no.system.message') != true)
        {
            Ametys.data.ServerComm.send({
                plugin: 'core-ui',
                url: 'system-announcement/view.xml',
                priority: Ametys.data.ServerComm.PRIORITY_MINOR,
                callback: {
                    handler: this._messageCallback,
                    scope: this
                }
            });
        }
    },
    
    /**
     * Callback function invoked when the message is returned.
     * @param {Object} response The XML response provided by the {@link Ametys.data.ServerComm}.
     * @param {Object} args The callback parameters passed to the {@link Ametys.data.ServerComm#send} method.
     * @private
     */
    _messageCallback: function(response, args)
    {
        this._sendCheckMessage();
        
        if (Ametys.data.ServerComm.isBadResponse(response))
        {
            Ametys.log.LoggerFactory.getLoggerFor('Ametys.plugins.coreui.system.Announce').error({
                message: "System announce", 
                details: "Cannot retrieve system announce"
            });
            return;
        }
        
        var isAvailable = Ext.dom.Query.selectValue('> SystemAnnounce > IsAvailable', response, 'false') === 'true';
        if (isAvailable)
        {
            var message = Ext.dom.Query.selectValue('> SystemAnnounce > Message', response);
            var lastModification = Ext.dom.Query.selectNumber('> SystemAnnounce > LastModification', response);
            
            if (lastModification > this._lastModification)
            {
                this._lastModification = lastModification;
                
                Ext.getCmp("ribbon").closeMessage("announce");
                Ext.getCmp("ribbon").addMessage({
                    title: "{{i18n PLUGINS_CORE_UI_TOOL_ANNOUNCE_TITLE}}",
                    text: message,
                    closeable: true,
                    type: "info",
                    id: "announce"
                });
                
                var state = Ext.dom.Query.selectValue('/SystemAnnounce/@state', response);
                var startDate = Ext.dom.Query.selectValue('/SystemAnnounce/@start-date', response,);
                var endDate = Ext.dom.Query.selectValue('/SystemAnnounce/@end-date', response);
                
                Ext.create('Ametys.message.Message', {
                    type: Ametys.message.Message.MODIFIED,
                    targets: [{
                        id: 'system-announcement',
                        parameters: {
                            state: state,
                            startDate: startDate,
                            endDate: endDate
                        }
                    }]
                });
            }
        }
        else if (this._lastModification != 0)
        {
            Ext.getCmp("ribbon").closeMessage("announce");
        
            this._lastModification = 0;
            
            var state = Ext.dom.Query.selectValue('/SystemAnnounce/@state', response);
            var startDate = Ext.dom.Query.selectValue('/SystemAnnounce/@start-date', response,);
            var endDate = Ext.dom.Query.selectValue('/SystemAnnounce/@end-date', response);
            
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.MODIFIED,
                targets: [{
                    id: 'system-announcement',
                    parameters: {
                        state: state,
                        startDate: startDate,
                        endDate: endDate
                    }
                }]
            });
        }
        
        var isMaintenance = Ext.dom.Query.selectValue('/SystemAnnounce/Maintenance/@active', response, 'false') === 'true';
        if (isMaintenance)
        {
            var lastMaintenance = Ext.dom.Query.selectNumber('> SystemAnnounce > Maintenance > timestamp', response);
            var mode = Ext.dom.Query.selectValue('/SystemAnnounce/Maintenance/@mode', response, '');
            
            
            if (lastMaintenance > this._lastMaintenance)
            {
                this._lastMaintenance = lastMaintenance;
                
                var title = {
                    'FORCED': "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TITLE_FORCED}}",
                    'AUTOMATIC': "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TITLE_AUTOMATIC}}"
                };
                
                var message;
                if (mode == 'FORCED')
                {
                    var comment = Ext.dom.Query.selectValue('> SystemAnnounce > Maintenance > comment', response, "")
                    if (comment)
                    {
                        message = comment + "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TEXT_FORCED_WITH_COMMENT}}";
                    }
                    else
                    {
                        message = "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TEXT_FORCED}}";    
                    }
                    
                }
                else
                {
                    message = "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TEXT_AUTOMATIC}}";
                }
                
                var since = Ext.dom.Query.selectValue('> SystemAnnounce > Maintenance > since', response, "");
                if (since == "")
                {
                    since = "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TEXT_NOTIME}}";
                }
                else
                {
                    since = Ext.Date.format(Ext.Date.parse(since, Ext.Date.patterns.ISO8601DateTime), Ext.Date.patterns.FullDateTime);
                }
                message = message.replace("{since}", since);
                
                var initiator = Ext.dom.Query.selectValue('> SystemAnnounce > Maintenance > initiator', response, "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MAINTENANCE_BANNER_TEXT_NOINITIATOR}}");
                message = message.replace("{initiator}", initiator);
                
                Ext.getCmp("ribbon").closeMessage("maintenance");
                Ext.getCmp("ribbon").addMessage({
                    title: title[mode],
                    text: message,
                    closeable: false,
                    type: "warning",
                    id: "maintenance"
                });
            }
            
        } 
        else
        {
            this._lastMaintenance = 0; 
            Ext.getCmp("ribbon").closeMessage("maintenance");
        }
    }
    
});

// Start the announce checker.
(function () {
    Ext.onReady(Ametys.plugins.coreui.system.Announce._sendCheckMessage, Ametys.plugins.coreui.system.Announce);
})();