/**
 Description: Controller for software update feature
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */

'use strict';
app.controller('SWUpdateCtrl', ['$rootScope', '$scope', '$http', '$interval', 'requestRoutingService', 'gridCrudService', 'dialogService', '$filter', 'notificationService',
function($rootScope, $scope, $http, $interval, requestRoutingService, gridCrudService, dialogService, $filter, notificationService) {
	var translate = $filter("translate");
	$scope.statusFetchReq = null;
	$scope.requestData = {
		type: "webuionly",
		file: ""
	};


	$scope.$on("restartSwitch", function(event, data) {
		$scope.dlg.data("kendoWindow").close();
		var x= $scope.showRestartSuccessDialog();
		if(angular.element("#saveconfig").is(":checked")){
		  requestRoutingService.getShowCmdOutput("write memory\n reload\n")
		} else{
		  requestRoutingService.getShowCmdOutput("reload\n");
		}
	});

	$scope.$on("startSoftwareUpdate", function(event, data) {
		document.getElementById("statusMsg").innetHTML = ""; //Reset the status message if any from previous request
		var formToSubmit = document.getElementById("swUpdateForm");
		if ($scope.requestData.type === "webuiandios") {
			/* actionURL = "/archive+download-sw+%2foverwrite+%2fhttp+uploadFile%0A";
			 */
			formToSubmit.action = "/archive+download-sw+%2fhttp+uploadFile%0A";
		} else {
			formToSubmit.action = "/archive+download-file+%2fhttp+uploadFile%0A";
			var result = requestRoutingService.getShowCmdOutput("mkdir flash:/uploadFile");
			if (result != "" && result.indexOf("Created dir") < 0 && result.indexOf("File exists") < 0) {
				console.log("ERROR! " + result + ". Cannot create download directory.");
				$scope.doCleanUp(true);
				return;
			}
		}

		//SUBMIT THE FORM
		//___________________
		formToSubmit.submit();	
		//___________________

		if($scope.requestData.type === "webuiandios"){
			$scope.statusFetchReq = $interval(function(){
				var status = requestRoutingService.getShowCmdOutput("show archive status");
				console.log(status);
				var msg = document.getElementById("statusMsg").innetHTML;
				
				if(msg === undefined || msg === null || msg === ""){
					msg = translate('software_update_copyProgress');
				} else {
					var newUpdate = translate('software_update_untar');
					if((status.indexOf('VERIFY: Verifying software') >= 0 || 
						status.indexOf('EXTRACT: Extracting the image') >= 0) && msg.indexOf(newUpdate) < 0){
						msg += "\n" + newUpdate;
					}
				}
				document.getElementById("statusMsg").innetHTML = msg;	
        		}, 2000);
		}
		if($scope.dlg){
			$scope.dlg.data("kendoWindow").close();
		}
		angular.element("body").addClass("busy");
	});

	$scope.showUpdateConfirmDialog = function(input){
		console.log("in start update");
		$scope.dlg = dialogService.dialog({
                                content : translate('software_update_start_confirm'),
                                title : translate('software_update_start'),
                                messageType : "confirm",
                                actionButtons : [{
                                        text : translate("com_ok"),
                                        callback : "startSoftwareUpdate",
                                        btnClass : "dummyClass"
                                }, {
                                        text : translate("com_cancel")
                                }]
                        });
	};

	$scope.showRestartConfirmDialog = function(input){
		console.log("in restart");
		$scope.dlg = dialogService.dialog({
			content : translate('software_update_restart_confirm') + "<br/>"+ "<div class=\"col-sm-9 col-sm-offset-1 webui-centerpanel-label\"><div class=\"col-sm-4 custom-checkbox\"><span class=\"label\">"+translate('save_configuration')+"</span></div><div class=\"col-sm-1 custom-checkbox\"><input type=\"checkbox\" name=\"saveconfig\" id=\"saveconfig\" class=\"k-checkbox form-control\" ng-model=\"saveconfig\"><label class=\"k-checkbox-label\" for=\"saveconfig\"></label></div></div>" + "<br/>",
			title : translate('software_update_restart_title'),
			messageType : "confirm",
			actionButtons : [{
				text : translate("com_ok"),
				callback : "restartSwitch"
			}, {
				text : translate("com_cancel")
			}]
		});
	};

	$scope.showRestartSuccessDialog = function(input){
		$scope.dlg = dialogService.dialog({
			content : translate('software_update_restart_success'),
			title : translate('software_update_restart_title'),
			messageType : "success",
			actionButtons : [{
				text : translate("com_ok")
			}]
		});
	};
	$scope.showRestartFailDialog = function(input){
		$scope.dlg = dialogService.dialog({
			content : translate('software_update_restart_fail'),
			title : translate('software_update_restart_title'),
			messageType : "failure",
			actionButtons : [{
				text : translate("com_ok")
			}]
		});
	};


	$scope.showStatus = function(error,restart){
		var type = error?"error":"info";
		var msg="";
		if(error){
			msg = translate('software_update_failed');
		}else{
			msg = translate('software_update_successfull');
			if(restart){
				msg += "\n"+translate('software_update_restart_message');
			}else{
				msg += "\n"+translate('software_update_relaunch');
			}
		}
		 $scope.dlg = dialogService.dialog({
                                content : msg,
                                title : translate("com_status"),
                                messageType : type,
                                actionButtons : [{
                                        text : translate("com_ok")
                                }]
                        });
	};

	$scope.doCleanUp = function(error){
		var platform = $rootScope.deviceInfo.type.split('-')[1];
		if($rootScope.deviceInfo.type.indexOf("CDB")!=-1){
                        platform = $rootScope.deviceInfo.type.split('-')[0];
                }else if($rootScope.deviceInfo.type.indexOf("2960+")!=-1){
                        platform = "C2960";
                }else if($rootScope.deviceInfo.type.indexOf("2960C")!=-1 && $rootScope.deviceInfo.type.indexOf("2960CX") == -1){
                        platform = "C2960C405";
                }else if(platform == "C2960XR"){
                        platform = "C2960X";
                }
                platform = platform.toLowerCase();
                var srcFile = "flash:/uploadFile/" + platform + "-cwml.tar";
		var result = requestRoutingService.getShowCmdOutput("delete /force " + srcFile);
		document.getElementById("swUpdateForm").reset();
		$scope.clearForm();
		angular.element("body.busy").removeClass("busy");
		$scope.showStatus(error,false);
	};

	$scope.extractAndCleanFiles = function(){
		console.log("do some work for UI only files");
		var httpServerBasePath = "";
		var httpPath = requestRoutingService.getShowCmdOutput("show ip http server status | i HTTP server base path")

        	if(httpPath.indexOf("flash:/") == -1){
                	httpPath = httpPath.substr(29);
                	httpPath = "flash:/" + httpPath;
                	console.log("HTTP path is " + httpPath);
        	}else{
                	httpPath = httpPath.substr(23);
        	}
		var error = false;
        	httpServerBasePath = httpPath;
		var newPath = httpServerBasePath+".new";
		var result = requestRoutingService.getShowCmdOutput("mkdir "+newPath);
		if(result != "" && result.indexOf("Created dir") < 0 && result.indexOf("File exists") < 0 ){
			console.log("ERROR! "+result);
			error = true;	
			$scope.doCleanUp(error);
			return;
		}	

		//copy macros to running config
		var macroFile = httpServerBasePath+"/macros/extractMacro";
		var macroCommand = "copy " + macroFile + " running-config";
		var result = requestRoutingService.getShowCmdOutput(macroCommand);
		if(result.indexOf("bytes copied") < 0){
			console.log("ERROR! "+result);
                        error = true;
			$scope.doCleanUp(error);
			return;
		}

		//run macros
		//flash:/uploadFile/c2960l-cwml.tar
		var platform = $rootScope.deviceInfo.type.split('-')[1];
		if($rootScope.deviceInfo.type.indexOf("CDB")!=-1){
			platform = $rootScope.deviceInfo.type.split('-')[0];
		}else if($rootScope.deviceInfo.type.indexOf("2960+")!=-1){
			platform = "C2960";
		}else if($rootScope.deviceInfo.type.indexOf("2960C")!=-1 && $rootScope.deviceInfo.type.indexOf("2960CX") == -1){
			platform = "C2960C405";
		}else if(platform == "C2960XR"){
			platform = "C2960X";
		}		
		platform = platform.toLowerCase();
		var srcFile = "flash:/uploadFile/" + platform + "-cwml.tar";
		var result = requestRoutingService.getConfigCmdOutput("macro global apply extractMacro $SRCFILE " + srcFile +" $TARGETPATH " + newPath);
		
		//If old directory is present, delete it.
		var result = requestRoutingService.getShowCmdOutput("delete /force /recursive "+httpServerBasePath+".old");
		
		//Rename the directories. Current becomes .old, and .new extracted above becomes current
		var result = requestRoutingService.getShowCmdOutput("rename "+httpServerBasePath+" "+httpServerBasePath+".old");
		if(result != "" && result.indexOf("Destination filename") < 0 ){
			console.log("ERROR! "+result);
			error=true;
			$scope.doCleanUp(error);
			return;
		}
		var result = requestRoutingService.getShowCmdOutput("rename "+newPath+" "+httpServerBasePath);
		if(result != "" && result.indexOf("Destination filename") < 0 ){
			console.log("ERROR! "+result);
			error=true;
			$scope.doCleanUp(error);
			return;
		}

		//Do the cleanup on success as no error has occured
		$scope.doCleanUp(error);
	};

	document.getElementById('statusDetails').onload = function(resp){
		if(document.getElementById('uploadFile').files.length == 0){
			return; //Initial page load. Dont to anything and return.
		}
		var response = this.contentDocument.body.innerText;
		if(response.indexOf("Succeed: uploadFile") >= 0){ 
			//WEBUIONLY success
			$scope.extractAndCleanFiles();
		} else if (response.indexOf("All software images installed") >=0 ){
			//WEBUIANDIOS success
			if($scope.statusFetchReq){
				$interval.cancel($scope.statusFetchReq);
				$scope.statusFetchReq = null;
			}
			var msg = document.getElementById("statusMsg").innetHTML;
			msg += "\n" + translate('software_update_successfull') 
					+ " " + translate('software_update_restart_message');
			document.getElementById("statusMsg").innetHTML = msg;
			angular.element("body.busy").removeClass("busy");
			document.getElementById("swUpdateForm").reset();
			$scope.clearForm();
			$scope.showStatus(false,true);
		} else{
			//UPDATE FAILED
			var msg = document.getElementById("statusMsg").innetHTML;
			msg += "\n" + translate('software_update_failed'); 
			document.getElementById("statusMsg").innetHTML = msg;
			if($scope.statusFetchReq){
				$interval.cancel($scope.statusFetchReq);
				$scope.statusFetchReq = null;
			}
			angular.element("body.busy").removeClass("busy");
			document.getElementById("swUpdateForm").reset();
			$scope.clearForm();
			$scope.showStatus(true,false);	
		}
	};

	$scope.fileSelected = function(file){
		console.log(file);
		if(file.value != ''){
			$scope.requestData.file = file.value;
			$scope.$apply();
		}
	};

	$scope.clearForm = function(){
		$scope.requestData.type = "webuionly";
		$scope.requestData.file = "";
		$scope.statusFetchReq = null;
		//document.getElementById("statusMsg").innetHTML = "";
		$scope.$apply();
	};

	$scope.fileTypeDataSource = new kendo.data.ObservableArray([
                                {"name": translate('software_update_file_type_webui'), "value": "webuionly"},
                                {"name": translate('software_update_file_type_webuiandios'), "value": "webuiandios"}
                        ]);
}]);
