// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hp/core/EventDispatcher', 'hp/services/Log'],
function(EventDispatcher, log) { "use strict";

    var RestoreEventDispatcher = (function() {
        
        var LOG_LEVEL = 0;
        
        function logMsg(level, message) {
            if (level <= LOG_LEVEL) {
                log.log(message + " " + Date.now());
            }
        }
        /**
         * @constructor
         */
        function RestoreEventDispatcher() {
            
            // Used to communicate with multiple Restore views.
            var realDispatcher = new EventDispatcher();
            var replayableEvents = [];
            
            this.on = function () {
                realDispatcher.on(arguments[0], arguments[1]);
            };
            this.off = function () {
                realDispatcher.off(arguments[0], arguments[1]);
            };
            this.fire = function (level, eventName, eventInfo) {
                replayableEvents[level] = [eventName, eventInfo];
                replayableEvents[level + 1] = undefined;
                logMsg(1, "Fire Restore Event: " + level + "-" + eventName);
                realDispatcher.fire(eventName, eventInfo);
            };
            
            this.shouldEventsBeReplayed = function (level, eventName, eventInfo) {
                var eventsShouldBeReplayed =
                    (replayableEvents[level] !== undefined) &&
                    (replayableEvents[level][0] === eventName)
                if (!eventsShouldBeReplayed) {
                    replayableEvents = [];
                }
                return eventsShouldBeReplayed;
            };
            this.replayEvents = function (level) {
                while (replayableEvents[level] !== undefined) {
                    logMsg(1, "Replay Restore Event: " + level + "-" + replayableEvents[level][0]);
                    realDispatcher.fire(replayableEvents[level][0], replayableEvents[level][1]);
                    level += 1;
                }
            };
            this.clearReplay = function (level) {
                while (replayableEvents[level] !== undefined) {
                    replayableEvents[level] = undefined;
                    level += 1;
                }
            };
            this.clearAllReplayableEvents = function () {
                replayableEvents = [];
            };
        }

        return RestoreEventDispatcher;
    }());

    return RestoreEventDispatcher;
});
