Ext.define('DisplayManager', {
    constructor:function () {
        this.ActionTimer = null;
        this.Pause = null;
        this.BackgroundObject = null;
        this.InternalTimer = null;
    },
    startCheckingTimer:function () {
        var that = this;
        this.stopCheckingTimer();
        if (this.Pause != null && this.Pause.TimerValue > 0 && this.Pause.TimerID >= 0) {
            this.InternalTimer = setInterval(function () {
                that.checkInternalTimer(that);
            }, 30);
        } else {
            Author.log("Something is wrong in startCheckingTimer");
        }
    },
    checkInternalTimer:function (displayManager) {
        if (displayManager.Pause != null && displayManager.Pause.TimerValue > 0 && displayManager.Pause.TimerID >= 0) {
            var timerValue = Author.LessonManager.AuthorLesson.InternalTimer.getTimerValue();
            if (timerValue >= displayManager.Pause.TimerValue) {
                displayManager.stopCheckingTimer();
                displayManager.Pause.onTimerReached(timerValue);
            }
        } else {
            displayManager.stopCheckingTimer();
        }
    },
    stopCheckingTimer:function () {
        if (this.InternalTimer != null) {
            window.clearInterval(this.InternalTimer);
        }
    },
    showLesson:function (lesson, startNodeID, startElementID) {


        lesson.LessonRoot.addListener('lessonRootCompleted', this.onLessonRootCompleted, this);
        lesson.LessonRoot.onStartShowLessonRoot();
        lesson.LessonRoot.show(startNodeID, startElementID);
    },
    onLessonRootCompleted:function (rootNode, startNodeID, startElementID) {
       // Author.log(Ext.String.format('onLessonRootCompleted: startNodeID: {0}, startElementID: {1}', startNodeID, startElementID));
        if (startNodeID == "0") startNodeID = "-1";

        if (startNodeID != "-1" || startElementID != "-1") {

            var startNode = Author.LessonManager.AuthorLesson.getLessonNodeByID(startNodeID);
            if (startNode.Type == 'RANDOM') {
                // Author.log (Ext.String.format('Start from random option:\n{0}', startNode));
                startNode.randomizeElements(startElementID);
            }

            this.navigateToScreen(startNodeID, startElementID);
        } else {
            this.showLessonNode(rootNode.ChildNode);
        }
    },
    navigateToScreen:function (startNodeID, startElementID) {
        if (this.Pause) {
            // Author.log("Pause Cacnelled by navigateToScreen:\n" + this.Pause.Source);
            this.Pause = null;
        }
        startElementID = startElementID || false;
        if (startElementID == "-1") startElementID = false;
        var startNode = Author.LessonManager.AuthorLesson.getLessonNodeByID(startNodeID);
        var travelPaths = startNode.NodePath.split('|');
        travelPaths.shift();     //remove lessonRootNode.

        if (!startElementID) {
            travelPaths.pop();    //remove the showing lesson node.
        }
        while (travelPaths.length > 0) {
            var travellingNode = Author.LessonManager.AuthorLesson.getLessonNodeByID(travelPaths.shift());
            if (travellingNode) {
                //  Author.log(Ext.String.format("travling node:\n{0}", travellingNode));
                this.travelLessonNode(travellingNode);
            }
        }
        if (!startElementID) {
            //Author.log(Ext.String.format("LessonNode.travelNodes finished, startToShowSelectedNode:\n{0}", startNode));
            this.showLessonNode(startNode);
        } else {
            if (typeof(startNode.hasElement) == 'function' && startNode.hasElement(startElementID)) {
                var startElement = startNode.travelElements(startElementID);
                if (startElement) {
                    startElement.addListener('elementCompleted', startNode.onElementCompleted, startNode);
                    this.showElement(startElement);
                } else {
                    Author.log(Ext.String.format("LessonNode.travelElements finished but didn't find element: {0}", startElementID));
                }
            } else {
                Author.log(Ext.String.format("LessonNode.travelElements:doesn't contain element: {0}", startElementID));
                this.showLessonNode(startNode);
            }
        }
    },
    travelLessonNode:function (node) {
        node.onStartTravelNode();
        node.travel();
    },
    showLessonNode:function (node) {
        Author.AudioManager.stopPlayingAudio();
        Author.VideoManager.stopPlayingVideo();
        node.onStartShowNode();
        if (Author.LessonManager.ReferenceWindow.isVisible()) {
            Author.LessonManager.ReferenceWindow.highLightCurrentScreen();
        }
        node.show();
    },
    showElement:function (element) {
        Author.AudioManager.stopPlayingAudio();
        Author.VideoManager.stopPlayingVideo();
        if (!Author.LessonManager.isElementVisited(element)) {
            Author.LessonManager.VisitedElementIds.add(element.id, element.Name);
        }
        // Author.log(Author.LessonManager.VisitedElementIds.getCount()) ;
        element.onStartShowElement();
        if (Author.LessonManager.ReferenceWindow.isVisible()) {
            Author.LessonManager.ReferenceWindow.highLightCurrentScreen();
        }
        element.show();
    },
    showResponse:function (response) {
        response.onStartShowResponse();
        response.show();
    },
    showList:function (list, startActionPosition) {
        if (list.ListType == 'ENDLIST') {
            Author.AudioManager.stopPlayingAudio();
            Author.VideoManager.stopPlayingVideo();
        }
        if (Author.CurrentStateManager.CurrentElementTimeoutTimer) {
            window.clearTimeout(Author.CurrentStateManager.CurrentElementTimeoutTimer);
            Author.CurrentStateManager.CurrentElementTimeoutTimer = null;
        }
        if (list.onStartShowList(startActionPosition)) {
            this.processListActions();
        }
        else {
            Author.log("DisplayManager.showList: error");
        }
    },
    processListActions:function () {
        if (this.Pause) {
           // Author.log("DisplayManager.processListActions:\n" + this.Pause.Source);
        }
        while (Author.CurrentStateManager.CurrentActionPosition < Author.CurrentStateManager.CurrentList.getActionsCount()) {
            var doActionResult = Author.DisplayManager.doAction();
            if (!doActionResult) {
                Author.log("Invalid doActionResult");
                return;
            }
            if (doActionResult.MoveOn && doActionResult.Interval > 0) {
                window.clearTimeout(Author.DisplayManager.ActionTimer);
                this.ActionTimer = setTimeout(Author.DisplayManager.processListActions, doActionResult.Interval);
                return;
            }
            if (!doActionResult.MoveOn) {
                return;
            }
        }

        Author.CurrentStateManager.CurrentList.onListCompleted();
    },
    doAction:function () {
        var curAction = Author.CurrentStateManager.CurrentList.getCurrentAction();
        Author.CurrentStateManager.CurrentActionPosition++;
        // Author.log(Ext.String.format("DoAction: {0}", curAction.toString()));
        if (Author.DisplayManager.pause) {
            if (Author.DisplayManager.pause.WaitMode = WaitModes.WaitFor) {
                Author.DisplayManager.pause = null;
            } else {
                Author.log("In doAction, why the pause is here???" + Author.DisplayManager.pause);
            }
        }
        if (curAction && curAction.isConditionMatched()) {
            return this.processAction(curAction);
        }
        return {MoveOn:true, Interval:0};
    },
    processAction:function (action) {
        Author.CurrentStateManager.CurrentAction = action;
        var doActionResult = action.processAction(this.BackgroundObject.getContent());

        Author.CurrentStateManager.addAction(action);
        if (doActionResult.Interval > 0) {
            Author.CurrentStateManager.fixZIndexes();
        }
        return doActionResult;
    },
    removeActionsInList:function (list) {
        Author.CurrentStateManager.removeActionsInList(list);
    },
    clearScreen:function (showingObject) {
        Author.CurrentStateManager.removeNonBackgroundOrForegroundActions();
        Author.CurrentStateManager.removeActionsNotBeforeOrder(showingObject.LogicalOrder);
        Author.CurrentStateManager.fixDisplayableActionsVisibility(showingObject.LogicalOrder);
        Author.CurrentStateManager.fixChangeActions(showingObject.LogicalOrder);
    },
    gotoLessonNode:function (lessonNodeID) {
        if (this.Pause) {
            Author.log('GotoLessonNode. Pause should not be here,  do something.Pause:\n' + this.Pause);
        }
        var nextNode = Author.LessonManager.AuthorLesson.getLessonNodeByID(lessonNodeID);
        if (nextNode) {
            this.showLessonNode(nextNode);
        }
        else {
            Author.log("GotoLessonNode. bad lessonNodeID");
        }
    },
    tryToTriggerResponse: function (name, value, answer) {
        if (Author.CurrentStateManager.isNagivationToResponseAvailable()) {
            if (this.Pause) {
                this.Pause = null;
            }
            Author.CurrentStateManager.checkAndShowResponse(name, value, answer);
        }
        else {
            Author.log("Can't goto response.");
        }
    },
    doNavigationAction:function (navigationAction, sourceAction) {
        //Author.LessonManager.log(Ext.String.format("DoNavigationAction: {0}", navigationAction));
        switch (navigationAction) {
            case NavigationTypes.Next:
                if (this.Pause) {
                    this.Pause.onSkipped(new SkipEvent(SkipEventTriggers.Action, {
                        Name:sourceAction.Name,
                        Value:sourceAction.Value
                    }));
                }
                else {
                    Author.log('Cannot go next');
                }
                break;
            case NavigationTypes.Back:
                var canGoBack = false;
                switch (Author.CurrentStateManager.CurrentLessonNode.Type) {
                    case 'SEQUENCE':
                    case 'RANDOM':
                        canGoBack = (Author.CurrentStateManager.CurrentElementPosition > 0) || (Author.CurrentStateManager.CurrentLessonNode.ParentNode.Type == 'MENU');
                        break;
                }
                if (canGoBack) {
                    if (this.Pause) {
                        //Author.log("DisplayManager.doNavigationAction.Back:\n" + this.Pause.Source + "\nCancelled by Back Action.");
                        this.Pause = null;
                    }
                    Author.CurrentStateManager.setAnswerBasedOnInteraction(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                    Author.CurrentStateManager.CurrentLessonNode.showPreviousElement();
                }
                else {
                    Author.log('Cannot Go back');
                }
                break;
            case NavigationTypes.Exit:

                if (Author.CurrentStateManager.CurrentLessonNode.ShowingEndList) {
                    if (this.Pause) {
                        this.Pause.onSkipped(new SkipEvent(SkipEventTriggers.Action, {
                            Name:sourceAction.Name,
                            Value:sourceAction.Value
                        }));
                    }
                } else {
                    if (this.Pause) {
                        //Author.log("DisplayManager.doNavigationAction.Exit:\n" + this.Pause.Source + "\nCancelled by Exit Action.");
                        this.Pause = null;
                    }
                    Author.CurrentStateManager.setAnswerBasedOnInteraction(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                    Author.CurrentStateManager.CurrentLessonNode.onExitLesson();
                }
                break;
            case NavigationTypes.ToMainMenu:
                if (Author.CurrentStateManager.CurrentLessonNode.ParentNode.Type == 'MENU') {
                    if (this.Pause) {
                        // Author.log("DisplayManager.doNavigationAction.ToMainMenu:\n" + this.Pause.Source + "\nCancelled by ToMainMenu Action.");
                        this.Pause = null;
                    }
                    Author.CurrentStateManager.setAnswerBasedOnInteraction(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                    Author.CurrentStateManager.CurrentLessonNode.onGoBackToMainMenu();
                }
                else {
                    Author.log('Cannot Go ToMainMenu');
                }
                break;
            case NavigationTypes.ToPreviousMenu:
                if (Author.CurrentStateManager.CurrentLessonNode.ParentNode.Type == 'MENU') {
                    if (this.Pause) {
                        // Author.log("DisplayManager.doNavigationAction.ToPreviousMenu:\n" + this.Pause.Source + "\nCancelled by ToPreviousMenu Action.");
                        this.Pause = null;
                    }
                    Author.CurrentStateManager.setAnswerBasedOnInteraction(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                    Author.CurrentStateManager.CurrentLessonNode.onGoBackToParentNode();
                }
                else {
                    Author.log('Cannot Go Upper');
                }
                break;
            case NavigationTypes.ToResponse:
                this.tryToTriggerResponse(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                break;
            case NavigationTypes.Repeat:
                if (Author.CurrentStateManager.canRepeat()) {
                    if (this.Pause) {
                        //  Author.log("DisplayManager.doNavigationAction.Repeat:\n" + this.Pause.Source + "\nCancelled by Repeat Action.");
                        this.Pause = null;
                    }
                    Author.CurrentStateManager.setAnswerBasedOnInteraction(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                    if (Author.CurrentStateManager.CurrentElement) {
                        Author.CurrentStateManager.CurrentElement.onRepeat();
                        return
                    }
                    if (Author.CurrentStateManager.CurrentLessonNode) {
                        Author.CurrentStateManager.CurrentLessonNode.onRepeat();
                        return;
                    }
                }
                else {
                    Author.log("CurrentStateManager.doNavigationAction.Repeat:\nCan not repeat.");
                }
                break;
            case NavigationTypes.Skip:
                if (Author.CurrentStateManager.CurrentElement && Author.CurrentStateManager.CurrentLessonNode && Author.CurrentStateManager.CurrentLessonNode.Type == 'SEQUENCE') {
                    if (this.Pause) {
                        // Author.log("DisplayManager.doNavigationAction.Skip:\n" + this.Pause.Source + "\nCancelled by Skip Action.");
                        this.Pause = null;
                    }
                    Author.CurrentStateManager.setAnswerBasedOnInteraction(sourceAction.Name, sourceAction.Value, sourceAction.Value);
                    Author.CurrentStateManager.CurrentLessonNode.onSkipElement();
                }
                else {
                    Author.log("No current element or not in a sequence node, can't skip an Element");
                }
                break;
            case NavigationTypes.AudioOnOff:
                break;
            case NavigationTypes.SynchOnOff:
                break;
        }
    },
    changeAction:function (changeAction) {
        if (!changeAction.IsDisplayable || !changeAction.IsChangeAction) {
            Author.log(Ext.String.format("Invalid change action:\n{0}", changeAction));
            return;
        }
        var orginalAction = Author.CurrentStateManager.getActionByID(changeAction.OrginalID);
        if (orginalAction) {
            orginalAction.applyChange(changeAction);
        }
        else {
            if (changeAction.ObjectType == 'BACKGROUND') {
                orginalAction = Author.LessonManager.AuthorLesson.LessonRoot.BackgroundList.Actions.getAt(0);
                if (orginalAction) {
                    orginalAction.applyChange(changeAction);
                }
            }
            Author.log(Ext.String.format("DisplayManager.changeAction: orginalAction can't find in current list.\n{0}", changeAction));
        }
    },
    restoreAction:function (fromAction, toActionID, isVisibleBeforeChange) {
        var oldAction = Author.CurrentStateManager.getActionByID(toActionID);
        if (oldAction) {
            fromAction.restoreToAction(oldAction, isVisibleBeforeChange);
        }
        else {
            Author.log("DisplayManager.RestoreToAction.Can't find old Action: " + toActionID);
        }
    },
    changeBackground:function (changeBackgroundAction) {
        if (this.BackgroundObject) {
            if (!changeBackgroundAction.IsChangeAction) {
                Author.log("DisplayManager.changebackground: changebackgroundaction is not a change action.");
            }
            this.BackgroundObject.applyBackground(changeBackgroundAction);
        }
        else {
            Author.log("DisplayManager.changeBackground.NoBackgroundObject.");
        }
    }
});
