/*************************************************************************
 *
 * ADOBE CONFIDENTIAL
 * ___________________
 *
 *  Copyright 2017 Adobe Systems Incorporated
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 **************************************************************************/

appModule.controller('MainController', ['$scope', 'Utils', function ($scope, Utils) {
    var self = this;
    Utils.mainCtrl = this;
    $scope.Utils = Utils;

    self.applicationName = "";
    self.platform = "";
    self.isHighDpi = false;
    self.contentURL;
    self.isTestWorkflow = false;
    self.environment = "PROD"
    self.autoDeleteAfterInstall = false;
	self.iconInProgressBar = false;
	

    self.imageMap = {};

    self.activeScreen = 'spinnerScreen';

    self.initialize = function (jsonData) {
        self.applicationName = jsonData.applicationName;

        self.platform = jsonData.platform;
        if (jsonData.isHighDpi == "true")
            self.isHighDpi = true;
		if (jsonData.isTestWorkflow == "true")
            self.isTestWorkflow = true;
        self.environment = jsonData.environment;
        if (jsonData.autoDeleteAfterInstall == "true")
            self.autoDeleteAfterInstall = true;
		if (jsonData.iconInProgressBar == "true")
            self.iconInProgressBar = true;

        if (self.isHighDpi) {
            self.imageMap.productIcon = "images/productIcon2x.png";
            //self.imageMap.ccIcon = "images/ccIcon2x.png";
            self.imageMap.cancelButton = "images/cancelButton2x.png";
            self.imageMap.errorIcon = "images/errorIcon2x.png";
            self.imageMap.checkEmpty = "images/checkEmpty2x.png";
            self.imageMap.checkFull = "images/checkFull2x.png";
            self.imageMap.spinner = "images/spinner2x.gif";
            self.imageMap.checkmark = "images/checkmark2x.png";
            self.imageMap.timer = "images/timer2x.png";
            self.imageMap.selectMark = "images/check.png";
            self.imageMap.carouselProductIcon = "images/productIcon4x.png";
        } else {
            self.imageMap.productIcon = "images/productIcon.png";
            //self.imageMap.ccIcon = "images/ccIcon.png";
            self.imageMap.cancelButton = "images/cancelButton.png";
            self.imageMap.errorIcon = "images/errorIcon.png";
            self.imageMap.checkEmpty = "images/checkEmpty.png";
            self.imageMap.checkFull = "images/checkFull.png";
            self.imageMap.spinner = "images/spinner.gif";
            self.imageMap.checkmark = "images/checkmark.png";
            self.imageMap.timer = "images/timer.png";
            self.imageMap.selectMark = "images/check.png";
            self.imageMap.carouselProductIcon = "images/productIcon2x.png";
        }

        self.contentURL = jsonData.contentURL;

        var OSName = "Unknown OS";
        if (self.platform == "win")
            OSName = "os-win";
        else
            OSName = "os-mac";

        Utils.addClass(document.getElementsByTagName("body").item(0), OSName);

        self.showSpinnerScreen();
        Utils.setLocale(jsonData.locale, jsonData.localizationStringMap);
    };

    self.showContainer = function () {
        $scope.$apply();
        $('.container').show();
    }

    //Spinner Screen
    self.spinnerScreenText = '';
    self.showSpinnerScreen = function (screenData) {
        if (screenData)
            self.spinnerScreenText = screenData.text;
        else
            self.spinnerScreenText = '';

        self.activeScreen = 'spinnerScreen';
    }

    self.showQuittingScreen = function() {
        self.spinnerScreenText = Utils.getLocalizedString("Quitting");
        self.activeScreen = 'spinnerScreen';
    }

    //Product Launching Screen
    self.showLaunchingProductScreen = function () {
    	//Bug fix WAM-867: Switch to launch screen even if user in on cancel confirmation prompt if product installation is complete
    	Utils.overlayCtrl.hideOverlay();
        self.activeScreen = 'launchingProductScreen';
    }

    //SSO Welcome Screen
	self.showWebSSOWelcomeScreen = function (screenData) {
		Utils.getElemById("webSSOWelcomeScreenTitle").innerHTML = Utils.getLocalizedString('InstallProduct', self.applicationName);
        self.activeScreen = 'webSSOWelcomeScreen';
        setTimeout(function () {
            Utils.getElemById("webSSOWelcomeContinueButton").focus();
        }, 10);
    }

    self.webSSOWelcomeContinueButtonClick = function () {
	    sendMessageToNative("webSSOWelcomeContinueButtonClicked", "");
    }

    //Welcome Screen
    self.socialProviders = null;
    self.showWelcomeScreen = function(screenData) {
		if(self.isTestWorkflow)
		{
			self.showTestAppWelcomeScreen();
		}
		else
		{
			Utils.getElemById("welcomeScreenHeader").innerHTML = Utils.getLocalizedString('InstallProduct', self.applicationName);
			Utils.getElemById("welcomeScreenContent").innerHTML = Utils.getLocalizedString('WelcomeText');

			self.activeScreen = 'welcomeScreen';
			if (!$.isEmptyObject(screenData))
				self.socialProviders = screenData;
			setTimeout(function () {
				Utils.getElemById("welcomeSignInButton").focus();
			}, 10);
		}
    }
	
    self.welcomeSignInButtonClick = function() {
        sendMessageToNative("welcomeSignInButtonClick", "");
    }

    self.welcomeSignUpButtonClick = function () {
        sendMessageToNative("welcomeSignUpButtonClick", "");
    }

    self.welcomeSocialSignInButtonClick = function (provider) {
        sendMessageToNative("welcomeSocialSignInButtonClick", provider);
    };

	//Test App Welcome Screen
                                        
    self.signInTestApp = 0;

	self.showTestAppWelcomeScreen = function(screenData) {
        self.activeScreen = 'testAppWelcomeScreen';
		self.contentURL = "";
		setTimeout(function () {
            Utils.getElemById("contentUrl").focus();
        }, 10);
    }
	
    //Survey Screen
	self.surveyButtonDisabled = false;

    self.surveyQuestionsAll = [
        {
            index: 0,
            value: 'skill',
            options: [
                { index: 0, value: '', name: 'SurveyQuestion1' },
                { index: 1, value: 'beginner', name: 'SurveyQuestion1Option1' },
                { index: 2, value: 'intermediate', name: 'SurveyQuestion1Option2' },
                { index: 3, value: 'experienced', name: 'SurveyQuestion1Option3' }
            ]
        },
        {
            index: 1,
            value: 'job',
            options: [
                    { index: 0, value: '', name: 'SurveyQuestion2' },
                    { index: 1, value: 'hobbyist', name: 'SurveyQuestion2Option1' },
                    { index: 2, value: 'marketing', name: 'SurveyQuestion2Option2' },
                    { index: 3, value: 'student', name: 'SurveyQuestion2Option3' },
                    { index: 4, value: 'academic', name: 'SurveyQuestion2Option4' },
                    { index: 5, value: 'printgraphicdesign', name: 'SurveyQuestion2Option5' },
                    { index: 6, value: 'photographer', name: 'SurveyQuestion2Option6' },
                    { index: 7, value: 'video', name: 'SurveyQuestion2Option7' },
                    { index: 8, value: 'developer', name: 'SurveyQuestion2Option8' },
                    { index: 9, value: 'webmobiledesign', name: 'SurveyQuestion2Option9' },
                    { index: 10, value: 'it_pro', name: 'SurveyQuestion2Option10' },
                    { index: 11, value: 'other', name: 'SurveyQuestion2Option11' }
			 ]
        },
        {
            index: 2,
            value: 'purpose',
            options: [
            { index: 0, value: '', name: 'SurveyQuestion3' },
            { index: 1, value: 'me_professional', name: 'SurveyQuestion3Option1' },
            { index: 2, value: 'org_involved', name: 'SurveyQuestion3Option2' }
            ]
        }
    ];

    self.surveyQuestions = [];
    self.surveyQuestionSelectedOption = [];

    self.showSurveyScreen = function (screenData) {
    	Utils.getElemById("surveyScreenTitle").innerHTML = Utils.getLocalizedString('InstallProduct', self.applicationName);

    	//surveyQuestionsAlreadyFilled
        //0 => No Question has been answered. So show all questions
        //1 => Common Question has been answered. So show product specific questions
        //2 => All questions has been answered

        if (screenData.surveyQuestionsAlreadyFilled == 1)
        {
            self.surveyQuestions = self.surveyQuestionsAll.slice(0, 1);
        }
        else {
            self.surveyQuestions = self.surveyQuestionsAll;

            //Randomize options
            var randomOptions = Utils.randomShuffle(self.surveyQuestions[1].options.slice(1, 11));
            for (var i = 0; i < randomOptions.length; i++) {
                self.surveyQuestions[1].options[i + 1] = randomOptions[i];
                self.surveyQuestions[1].options[i + 1].index = i + 1;
            }
        }

        for (var i = 0; i < self.surveyQuestions.length; i++) {
            self.surveyQuestionSelectedOption[i] = self.surveyQuestions[i].options[0];
        }

        self.surveySelectChanged();
        self.activeScreen = 'surveyScreen';

        setTimeout(function () {
            $(".sbHolder")[0].focus();
        }, 10);
    };

    self.surveyQuestionKeyPress = function (e, question, scope) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        switch (key) {
            case 37: //Arrow Left
            case 38: //Arrow Up
				var optionIndex = self.surveyQuestionSelectedOption[question].index;
				if (optionIndex > 0)
				{
					self.surveyQuestionSelectedOption[question] = self.surveyQuestions[question].options[optionIndex - 1];
					var surveyQuestionDiv = "li#surveyOption" + question.toString() + "-" + (optionIndex-1).toString() + " a";
					$(surveyQuestionDiv).focus();
            	}
				self.surveySelectChanged();
                e.preventDefault();
                break;	
            case 39: //Arrow Right
            case 40: //Arrow Down
				var optionIndex = self.surveyQuestionSelectedOption[question].index;
			    if (optionIndex < self.surveyQuestions[question].options.length - 1)
				{
				    self.surveyQuestionSelectedOption[question] = self.surveyQuestions[question].options[optionIndex + 1];
					var surveyQuestionDiv = "li#surveyOption" + question.toString() + "-" + (optionIndex+1).toString() + " a";
					$(surveyQuestionDiv).focus();
					
                }
				self.surveySelectChanged();
                e.preventDefault();
                break;
            case 9: //Tab
                scope.dropdownShown = false;

                //var i = parseInt($this.attr("tabindex"), 10);
                //if (!e.shiftKey) {
                //    i++;
                //} else {
                //    i--;
                //}
                //$("*[tabindex='" + i + "']").focus();
                //e.preventDefault();
                break;
        }
    };

    self.surveySelectChanged = function () {
        self.surveyButtonDisabled = false;
        for (var i = 0; i < self.surveyQuestions.length; i++) {
            if(self.surveyQuestionSelectedOption[i].index == 0)
                self.surveyButtonDisabled = true;
        }
  }

    self.surveyMouseDown = function (e) {
        var parentSbHolder = null;
        if ($(e.target).parents(".sbHolder").length > 0)
		{
			parentSbHolder = $(e.target).parents(".sbHolder")[0];
			parentSbHolder.focus();
		}
            
        $(".sbHolder").each(function (index) {
            if (this != parentSbHolder)
                $(this).scope().dropdownShown = false;
        });
    };

    self.surveyContinueButtonClick = function () {
        var surveyResponse = {};
        for (var i = 0; i < self.surveyQuestions.length; i++) {
            surveyResponse[self.surveyQuestions[i].value] = self.surveyQuestionSelectedOption[i].value;
        }

        sendMessageToNative("surveyContinueButtonClicked", JSON.stringify(surveyResponse));
    }
	
	self.testAppContinueButtonClick = function () {
		var jsonResponse = {};
     	if(self.signInTestApp){
			jsonResponse["environment"] = Utils.getElemById("testAppEnvironment").value;
			
		}			
		jsonResponse["signInClicked"] = self.signInTestApp?"true":"false";
	    sendMessageToNative("testAppContinueButtonClicked", JSON.stringify(jsonResponse));
    }

    //PII Screen
	self.showPiiScreen = function (screenData) {
		Utils.getElemById("piiScreenTitle").innerHTML = Utils.getLocalizedString('InstallProduct', self.applicationName);
		var piiScreenText1 = Utils.getLocalizedString("PiiScreenText1");
        var urlForOpening;
        if("STG" === self.environment || "STAGE" === self.environment)
            urlForOpening = Utils.getLocalizedString("PiiScreenLearnMoreStageLink");
        else
            urlForOpening = Utils.getLocalizedString("PiiScreenLearnMoreLink");
        piiScreenText1 = piiScreenText1.replace('{10}', "<a ondragstart='return false;' onclick='openUrl(event, true)' target='_blank' href='" + urlForOpening + "'>");
        piiScreenText1 = piiScreenText1.replace('{11}', "</a>");
		
        if("STG" === self.environment || "STAGE" === self.environment)
            urlForOpening = Utils.getLocalizedString("PiiAccountPreferenceStageLink");
        else
            urlForOpening = Utils.getLocalizedString("PiiAccountPreferenceLink");
		piiScreenText1 = piiScreenText1.replace('{14}', "<a ondragstart='return false;' onclick='openUrl(event, true)' target='_blank' href='" + urlForOpening + "'>");
        piiScreenText1 = piiScreenText1.replace('{15}', "</a>");
		
        Utils.getElemById("piiScreenText1").innerHTML = piiScreenText1;
        self.activeScreen = 'piiScreen';
        setTimeout(function () {
            Utils.getElemById("piiContinueButton").focus();
        }, 10);
    }

    self.piiContinueButtonClick = function () {
	    sendMessageToNative("piiContinueButtonClicked", "");
    }

    //Main Screen
    self.isIframeAdded = false;
    self.isIframeLoaded = false;
    self.isDefaultContentShown = false;
    self.isInErrorState = false;

    self.currentProgress = 0;
    self.currentProgressTemp = 0;
    self.desiredProgress = 0;
    self.minutesLeftMin = 0;
    self.minutesLeftMax = 0;
	
    self.progressUpdateTimer = function () {
        if (self.desiredProgress >= 100) {
            self.currentProgressTemp = 100;
            self.currentProgress = 100;
            $scope.$apply();
        }
        else if (self.currentProgressTemp < self.desiredProgress && Utils.overlayCtrl.isOverlayShown == false) {
            self.currentProgressTemp += (self.desiredProgress - self.currentProgressTemp) / 10;
            self.currentProgress = parseFloat(self.currentProgressTemp).toFixed(1);
            $scope.$apply();
        }

        if (self.currentProgress < 100) {
            setTimeout(self.progressUpdateTimer, self.progressUpdateTime);
        }
    };

    self.showMainScreen = function (screenData) {
        if (screenData.showCarousel == "false") {
            var jsonData = {};
            jsonData.errorURL = 'MinimalisticKaizenInstaller';
            self.showDefaultContent(jsonData, false);
        } 
		else if (self.contentURL == "") {
		    var jsonData = {};
            jsonData.errorURL = 'ie9';
            self.showDefaultContent(jsonData, false);
        }
		else if (!self.isIframeAdded) {
			if (screenData.sophiaActionUrl && screenData.sophiaActionUrl != "") {
				self.contentURL = screenData.sophiaActionUrl;
			}
            var iframe = Utils.createIframe("marketingIFrame");
            $(iframe).on('load', function () {
                if (!self.isIframeLoaded && !self.isDefaultContentShown) {
                    self.isIframeLoaded = true;

                    $('#marketingIFrameDiv').show();
                    $scope.$apply();

                    sendMessageToNative("carouselLoadComplete", "");
                }
            });
			
			iframe.src = self.contentURL;
			
            Utils.getElemById('marketingIFrameDiv').appendChild(iframe);
            self.isIframeAdded = true;

            $("#iframeSpinnerScreenText").hide();

            setTimeout(function () {
                $("#iframeSpinnerScreenText").show();
            }, 5000);

            //Show embedded default content after 30 sec
            var iFrameTimer = setTimeout(function () {
                self.showDefaultContent({}, true);
            }, 30000);
        }

        self.progressUpdateTime = parseInt(screenData.progressUpdateTime);
		self.activeScreen = 'mainScreen';
	    setTimeout(self.progressUpdateTimer, self.progressUpdateTime);

        Utils.overlayCtrl.removeBlurEffect();
    }

    self.showDefaultContent = function(jsonData, isTimeOut) {
        if (!self.isIframeLoaded && !self.isDefaultContentShown) {
            self.isDefaultContentShown = true;
            var marketingIFrame = Utils.getElemById("marketingIFrame");
            if (marketingIFrame)
                Utils.getElemById('marketingIFrameDiv').removeChild(marketingIFrame);

            var data;
            var errorURL = jsonData.errorURL;
            if (isTimeOut)
                data = "{\"timeOut\":\"true\"}";
            else
                data = "{\"timeOut\":\"false\",\"errorURL\":\"" + errorURL + "\"}";
            sendMessageToNative("defaultContentShown", data);
        }
    }

    self.updateProgress = function (progressData) {
        self.desiredProgress = parseInt(progressData.progress);
        self.minutesLeftMin = parseInt(progressData.minutesLeftMin);
        self.minutesLeftMax = parseInt(progressData.minutesLeftMax);
    }

    self.isCancelButtonEnabled = false;
    self.updateCancelButtonState = function (jsonData) {
        //self.isCancelButtonEnabled = (jsonData.enabled == "true");
    }

    self.cancelButtonClicked = function () {
        if (isCancelButtonEnabled)
            sendMessageToNative("cancelButtonClicked", "");
    }

}]);
