//com.tts.initial.html5.navigation.progress
define(["jquery", "./locals"],function (jq, uiText) {

	"use strict";

	return function (context, metadata) {

	    var ElementIds = {
    	        "main" : "mainPathProgress",
                "sub" : "parallelPathProgress",
                "both" : "bothPathProgress"
            },
            VisibilityUtil = {
                checkMainPathProgressVisibility : function( config ){
                    return ( config.learningPathVisibility === "both" ) || ( config.learningPathVisibility === "main" && config.currentStepIsInMainPath );
                },

                checkSubPathProgressVisibility : function( config ){
                    return !config.currentStepIsInMainPath && ( config.learningPathVisibility === "sub" || config.learningPathVisibility === "both" );
                },
                progressIsVisible : function( config ) {

                    if( config.learningPathVisibility === "both" ) {
                        return true;
                    }

                    if( config.currentStepIsInMainPath ) {
                        return config.learningPathVisibility === "main";
                    }

                    return config.learningPathVisibility === "sub";
                }
            };

		function ProgressBarBuilder( config ){

            function createMainProgressBar(){

                var pe = createProgressElement()
                    .css( "background-color", config.barMainBackgroundColor );

                pe.html("<div></div>")
                    .children()
                    .first()
                    .css({
                        "height": "100%",
                        "background-color": config.barMainProgressColor
                    });

                return pe;
            }

            function createProgressElement() {
                return jq(document.createElement("div"))
                    .css({
                        "position": "absolute",
                        "left": "0px",
                        "top": "0px",
                        "width": "100%",
                        "height": "100%"
                    })
                    // test id
                    .addClass( ElementIds["main"] );
            }

            function createSubProgressBar(){

                var pe = createSubProgressElement();

                pe.css({
                    // use 50% height in case the main path is also displayed
                    "height": config.learningPathVisibility === "sub" ? "100%" : "50%",
                    "background-color": config.barSubBackgroundColor
                })
                    .html("<div></div>")
                    .children()
                    .first()
                    .css({
                        "height" : "100%",
                        "background-color" :  config.barSubProgressColor
                    });


                return pe;
            }

            function createSubProgressElement() {
                return jq(document.createElement("div"))
                    .css({
                        "position" : "absolute",
                        "right": "0px",
                        "top" : config.learningPathVisibility === "sub" ? "0" : "50%",
                        "width": "100%"
                    })
                    // test id
                    .addClass( ElementIds["sub"] );
            }

            function setProgressWidth( progressElement, progress ){
                jq(progressElement).children().first().css({"width": progress + "%"});
            }

            return {
				build : function( shellElement ){

                    if( !VisibilityUtil.progressIsVisible(config) ){
                        if( context.stage.isInAuthoringMode() ){
                            shellElement.css( "border", "1px dotted #ff0000" );
                        }
                        return;
                    }

                    if( VisibilityUtil.checkMainPathProgressVisibility(config) ){
                        var mainProgressElement = createMainProgressBar();
                        setProgressWidth( mainProgressElement, config.progressMain );
                        shellElement.append( mainProgressElement );
                    }

                    if( VisibilityUtil.checkSubPathProgressVisibility(config) ){
                        var subProgressElement = createSubProgressBar();
                        shellElement.append( subProgressElement );
                        setProgressWidth( subProgressElement, config.progressSub );
                    }
                }
            };
        }

        function ProgressTextBuilder( config ) {

		    function getTestId(){

                if( config.learningPathVisibility === "both" ){
                    return config.currentStepIsInMainPath ? "main" : "sub";
                }

                return config.learningPathVisibility;
            }

            function getTextId(){

                if( config.learningPathVisibility === "both" ){
                    return config.currentStepIsInMainPath ? "main" : "both";
                }

                return config.learningPathVisibility;
            }


            function createProgressElement() {

                var testId = ElementIds[ getTestId() ];
                return jq(document.createElement("div"))
                    .css({
                        "position" : "absolute",
                        "left": "0px",
                        "top": "0px",
                        "width": "100%",
                        "height": "100%"
                    })
                    .addClass( testId );
            }

            function addProgressTextStyles( element ) {
                return jq(element)
                    .css({
                        "color" : config.textColor,
                        "font-size" : config.fontSize,
                        "font-family" : getFontFamilyString( config.fontFamily ),
                        "text-align" : config.textAlign
                    });
            }

            function getFontFamilyString(fontFamily) {
                switch (parseInt(fontFamily)) {
                    case 2:
                        return "'Times New Roman', Times, serif";
                    case 3:
                        return "Verdana, Geneva, sans-serif";
                    case 4:
                        return "'Courier New', Courier, monospace";
                    case 1:
                    default:
                }
                return "Arial, Helvetica, sans-serif";
            }

            function getDisplayText(){

                var stageVarMainPathPos = context.stage.variable.get('mainPathCurrentPage', 'Progress'),
                    stageVarMainPathAllCount = context.stage.variable.get('mainPathAllPagesCount', 'Progress'),
                    mainPathPos = stageVarMainPathPos === null ? 0 : stageVarMainPathPos,
                    currentMainPathAllCount = stageVarMainPathAllCount === null ? 0 : stageVarMainPathAllCount,
                    textKey = "player.navigation.progress." + config.textMode + "." + getTextId(),
                    textContent = uiText.get( textKey, mContentLanguage ),
                    numberLength = mAllPagesCount.toString().length;

                textContent = textContent.replace( "#currentPage#", number_pad( config.currentPos, numberLength ) );
                textContent = textContent.replace( "#maxPages#", config.allPagesCount );

                numberLength = currentMainPathAllCount.toString().length;
                textContent = textContent.replace( "#mainCurrentPage#", number_pad( mainPathPos, numberLength ) );
                textContent = textContent.replace( "#mainMaxPages#", currentMainPathAllCount );

                // Percent
                textContent = textContent.replace( "#currentPathPercent#", config.currentStepIsInMainPath ? config.progressMain : config.progressSub );
                textContent = textContent.replace( "#mainPathPercent#", config.progressMain );

                return textContent;
            }

            return {
                build: function (shellElement) {

                    if( !VisibilityUtil.progressIsVisible(config) ){
                        if( context.stage.isInAuthoringMode() ){
                            shellElement.css( "border", "1px dotted #ff0000" );
                        }
                        return;
                    }

                    var progressElement = createProgressElement();
                    progressElement.text( getDisplayText() );
                    addProgressTextStyles( progressElement );
                    shellElement.append( progressElement );
                }
            };
        }

		var mProgressMain = 0,
			mProgressSub = 0,
			mCurrentPos = 0,
			mAllPagesCount = 0,
			mIsStandardPlayer = context.getPlayerName() === "standard",
			mContentLanguage = metadata.stage.getContentLanguage(),
			mParameters = metadata.parameters,
			mDisplayMode = mParameters.get("displayMode", "bar"),
            mTextMode = mParameters.get("textMode", "textLong");

		function currentStepIsInMainPath(){

			if( mIsStandardPlayer ) {
                var currentLearningPath = getCurrentLearningPath();
                if( currentLearningPath ) {
                    return currentLearningPath.isMainLearningPath();
                }
            }

            return true;
		}

		function getCurrentLearningPath(){
            if( mIsStandardPlayer ){
                return metadata.page.getLearningPath ? metadata.page.getLearningPath() : null;
            }

            return metadata.stage;
		}

		function initProgressValues(){

			var myId = metadata.page.getId(),
				currentLearningPath = getCurrentLearningPath();

			if( !currentLearningPath ){
			    return;
            }

			// get pages count
            mAllPagesCount = 0;
            jq.each( currentLearningPath.pages, function(k,p){
				mAllPagesCount++;
				// if this is current position, set current page count
				if (p.getId() === myId) {
					mCurrentPos = mAllPagesCount;
				}
            });

			if( currentStepIsInMainPath() ){
				mProgressMain = (mAllPagesCount > 0) ? Math.round((mCurrentPos / mAllPagesCount) * 100) : 0;
				mProgressSub = 0;
				// remember current main progress so we can use it within sub path
				context.stage.variable.set('mainPathCurrentPage', mCurrentPos, 'Progress');
				context.stage.variable.set('mainPathAllPagesCount', mAllPagesCount, 'Progress');
				context.stage.variable.set('subPathCurrentPage', 0, 'Progress');
				context.stage.variable.set('subPathAllPagesCount', 0, 'Progress');
			}
			else {
				mProgressMain = (context.stage.variable.get('mainPathAllPagesCount', 'Progress') > 0) ? Math.round((context.stage.variable.get('mainPathCurrentPage', 'Progress') / context.stage.variable.get('mainPathAllPagesCount', 'Progress')) * 100) : 0;
				mProgressSub = (mAllPagesCount > 0) ? Math.round((mCurrentPos / mAllPagesCount) * 100) : 0;
				context.stage.variable.set('subPathCurrentPage', mCurrentPos, 'Progress');
				context.stage.variable.set('subPathAllPagesCount', mAllPagesCount, 'Progress');
			}
		}

		function number_pad(num, size) {
			if( mParameters.asBool("leadingZeros", false) === true ) {
				var s = num + "";
				while (s.length < size){
					s = "0" + s;
                }
				return s;
			} else {
				return num;
			}
		}

		// is neccessary testing
		function getSCTestWrapperSelectors(){
			return "progressBarWrapper showProgressOnPathType_" + mParameters.get("useLearningPathMode", "both") +  " displayAs_" + (mDisplayMode === "bar" ? mDisplayMode : mTextMode)
		}

		function createHTML() {

			var shellElement = jq(context.getElement())
				// can be used to identify progress bar type from outside of the component (ex. integration tests)
				.addClass(getSCTestWrapperSelectors());

            shellElement.children( "." + ElementIds["main"] ).remove();
            shellElement.children( "." + ElementIds["sub"] ).remove();

            if( mDisplayMode === "bar" ){
                new ProgressBarBuilder({
                    currentStepIsInMainPath : currentStepIsInMainPath(),
                    learningPathVisibility : mParameters.get("useLearningPathMode", "both"),
                    progressMain : mProgressMain,
                    progressSub : mProgressSub,
                    barMainBackgroundColor : mParameters.asCssColor("backgroundMainPath", "#5d5d5d"),
                    barMainProgressColor : mParameters.asCssColor("colorMainPath", "#0398e6"),
                    barSubBackgroundColor : mParameters.asCssColor("backgroundParallelPath", "#7a7a7a"),
                    barSubProgressColor : mParameters.asCssColor("colorParallelPath", "#b1cfdd")
                }).build( shellElement );
			}
			else {
                new ProgressTextBuilder({
                    currentStepIsInMainPath : currentStepIsInMainPath(),
                    learningPathVisibility : mParameters.get("useLearningPathMode", "both"),
                    textMode : mTextMode,
                    textColor :  mParameters.asCssColor("color", "#000000"),
                    fontSize : mParameters.asNumber( "fontSize", 14) + "px",
                    fontFamily : mParameters.asNumber( "fontFamily", 1),
                    textAlign : mParameters.get("textOrientation", "center"),
                    currentPos : mCurrentPos,
                    allPagesCount : mAllPagesCount,
                    progressMain : mProgressMain,
                    progressSub : mProgressSub
                }).build( shellElement );
			}
		}

        // revealing public API
		return {
            onLoading : function() {
                if (context.stage.isInAuthoringMode()) {
                    context.page.event.bindOnEnter( this );
                    createHTML();
                }
                else {
                    initProgressValues();
                    createHTML();
                }
            },

            onEnterPage : function() {
                initProgressValues();
                createHTML();
            }
		};
	};
});
