/**
 Description: Controller - Day Zero Wizard
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
'use strict';

angular.module('webUiDevApp').controller('DayZeroCtrl', ['$scope', 'validationService', 'dayZeroStepService','httpEndPointService', '$location','requestRoutingService','notificationService','$filter','$window','dialogService',
	function($scope, validationService, dayZeroStepService, httpEndPointService,$location,requestRoutingService,notificationService,$filter,$window,dialogService) {
		var translate = $filter("translate");
		if(navigator.language.indexOf("zh") != -1){
			kendo.culture("zh")
		}
		else if(navigator.language.indexOf("ko") != -1){
			kendo.culture("ko");
		}
		else if(navigator.language.indexOf("ja") != -1){
			kendo.culture("ja")
		}
		$scope.mainStep=true;
		$scope.welcomeScreen=false;
		$scope.$emit("WebUI::DayZeroCheck");
		               //Special case, need to relook at the implementation in phase2
                //******************************************
                var sendConfigReq = function(dayZeroConfigCli){
                        var CMD_HTTP_URL = '/ios_web_exec/commandset';
                        var requestData = "! COMMANDSET VERSION=\"1.0\"\n" +
                        "! OPTIONS BEGIN\n! MODE=\"" + "1" + "\"\n" +
                        "! OPTIONS END\n" +
                                dayZeroConfigCli + "\n" +
                        "! END\n! COMMANDSET END";
                        var d = new Date();
                        console.log(d.getTime());
                        $.ajax({
                                type: 'POST',
                                async: 'false',
                                timeout: 5000,
                                url: CMD_HTTP_URL,
                                data: requestData,
                                success: function(data){
					angular.element("body.busy").removeClass("busy");
                                		if(data.indexOf('PARSE_ERROR="2"') || data.indexOf('PARSE_ERROR="1"') || data.indexOf('PARSE_ERROR="3"')){
                                			console.log("ERROR! "+data);
                                			notificationService.showNotification("Error: ",translate('com_config_fail_title'),'error');
                                		} else {
                                			$scope.laySummary= dayZeroStepService.getLayConfig();
											$scope.ipAddressAssign=dayZeroStepService.getIpAddressAssign()
											$scope.$watch(function() {
													return dayZeroStepService.getLayConfig();
											}, function(newValue,oldValue) {
													$scope.laySummary = newValue;
											});
											if($scope.laySummary.newIpAddress){
													var vlanInterface=dayZeroStepService.getVlanInter();
													for(var i=0;i<vlanInterface.length;i++){
															var ipAddress=vlanInterface[i]['IP-Address'];
													}
													if(ipAddress!=$scope.laySummary.newIpAddress)
													commonConfirmationSwitch($scope.laySummary.newIpAddress);
											}else {
													for(var i=0;i<$scope.ipAddressAssign.length;i++){
															if($scope.ipAddressAssign[i].ipAddress){
																	commonConfirmationSwitch($scope.ipAddressAssign[i].ipAddress);
																	break;
															}
													}
											}
                                		}
                                },
                                error: function(data){
                                        //If its timed out, most likely it succeeded, assume success
                                        angular.element("body.busy").removeClass("busy");
					notificationService.showNotification(translate('day0_wizard_success_msg'),translate('com_config_success_title'),'success');
                                	$scope.laySummary= dayZeroStepService.getLayConfig();
                                	$scope.ipAddressAssign=dayZeroStepService.getIpAddressAssign()
                                	$scope.$watch(function() {
                                        	return dayZeroStepService.getLayConfig();
                                	}, function(newValue,oldValue) {
                                        	$scope.laySummary = newValue;
                                	});
                                	if($scope.laySummary.newIpAddress){
                                        	var vlanInterface=dayZeroStepService.getVlanInter();
                                        	for(var i=0;i<vlanInterface.length;i++){
                                                	var ipAddress=vlanInterface[i]['IP-Address'];
                                        	}
                                        	if(ipAddress!=$scope.laySummary.newIpAddress)
                                        	commonConfirmationSwitch($scope.laySummary.newIpAddress);
                                	}else {
                                        	for(var i=0;i<$scope.ipAddressAssign.length;i++){
                                                	if($scope.ipAddressAssign[i].ipAddress){
                                                        	commonConfirmationSwitch($scope.ipAddressAssign[i].ipAddress);
                                                        	break;
                                                	}
                                        	}
                                	}

                                }
                        });
                };
                //******************************************

		$scope.finishedWizard = function() {
			var dayZeroConfigCli=dayZeroStepService.getCli();
			console.log(dayZeroConfigCli);
			angular.element("body").addClass("busy");
                        sendConfigReq(dayZeroConfigCli);
                        return;

			var result = requestRoutingService.getConfigCmdOutput(dayZeroConfigCli);
			if( result=="" || result.errorResponse.indexOf("Written") >-1 ){
				notificationService.showNotification(translate('day0_wizard_success_msg'),translate('com_config_success_title'),'success');
				$scope.laySummary= dayZeroStepService.getLayConfig();
				$scope.ipAddressAssign=dayZeroStepService.getIpAddressAssign()
				$scope.$watch(function() {
					return dayZeroStepService.getLayConfig();
				}, function(newValue,oldValue) {
					$scope.laySummary = newValue;
				});
				if($scope.laySummary.newIpAddress){
					var vlanInterface=dayZeroStepService.getVlanInter();
					for(var i=0;i<vlanInterface.length;i++){
						var ipAddress=vlanInterface[i]['IP-Address'];
					}
					if(ipAddress!=$scope.laySummary.newIpAddress)
					commonConfirmationSwitch($scope.laySummary.newIpAddress);
				}else {
					for(var i=0;i<$scope.ipAddressAssign.length;i++){
						if($scope.ipAddressAssign[i].ipAddress){
							commonConfirmationSwitch($scope.ipAddressAssign[i].ipAddress);
							break;
						}
					}
				}
			}else{
				notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
			}
		};
		var redirectIP='';
		var commonConfirmationSwitch = function(newIP) {
			redirectIP=newIP;
			$scope.dlgSwitch = dialogService.dialog({
				content : translate("msg_redirect_confirmation")+" "+newIP,
				title : translate("msg_redirect_confirmation_window"),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "pageRedirection"

				}, {
					text : translate("com_cancel")
				}]
			});
		};

		$scope.$on("pageRedirection", function(event, data) {
			var baseUrl = $window.location.origin;
			if(baseUrl.indexOf('https') > -1)
				$window.location.href = "https://"+ redirectIP;
			else $window.location.href = "http://"+ redirectIP;
		});

		$scope.gotowelcomeScreen = function(string) {
			if (string==="towelcome") {
				$scope.myValidator = $scope.createUserValidator;
				validationService.addValidator($scope.myValidator, 1);
				if ($scope.myValidator && $scope.myValidator.validate() == true) {
					$scope.welcomeScreen=false;
				}
			} else if (string==="towizard"){
				$scope.mainStep=false;
				$scope.welcomeScreen=true;
			}
		}
		$scope.wizardValidations = {
			//TODO: make it re-usable
			rules : {

			}
		};
		$scope.getData = function(wzModel, isLastStep, stepNumber) {
			//broadcasting next button pressed event to the individual step controllers...
			$scope.$broadcast('dayZeroWizard:nextButtonPressed', isLastStep, stepNumber);
		};
		// Broadcast the event on site profile change
		$scope.$on("dayZeroWizard:notifySiteProfileChange", function(evt, siteProfile) {
			$scope.$broadcast('dayZeroWizard:siteProfileChanged', siteProfile);
		});
		// Broadcast event on wireless state change
		$scope.$on("dayZeroWizard:wirelessToggle", function(evt, wirelessState) {
			$scope.$broadcast('dayZeroWizard:wirelessStateChange', wirelessState);
		});
		// Broadcast event on wired state change
		$scope.$on("dayZeroWizard:wiredToggle", function(evt, wiredState) {
			$scope.$broadcast('dayZeroWizard:wiredStateChange', wiredState);
		});
		$scope.$on("dayZeroWizard:notifySetupToggle", function(evt) {
			$scope.$broadcast("dayZeroWizard:setupToggle");
		});
		$scope.$on("DayZeroWizard:notifyDHCPChange", function(evt, dhcpAddress) {
			$scope.$broadcast("dayZeroWizard:dhcpChanged", dhcpAddress);
		});
	}]);
