var utilsSvc = angular.module('utilsSvc', []);

utilsSvc.factory('utilsSvc', function($cookies, $rootScope, $http, $q,$window, $mdDialog, $location, $mdToast, $mdMedia) {

	var utilsSvc = {};

	utilsSvc.refreshTimeout = 20000;
	utilsSvc.adminTimeout = 5000;
	utilsSvc.alreadyShowingError = false;
	

	if (utilsSvc.refreshTimeout == 200000)
		alert("Togliere refreshtimeout di test");

	utilsSvc.interactiveRefreshTimeout = 1500;
	utilsSvc.isLoading = false;

	utilsSvc.timeoutPromise = null;
	
	utilsSvc.showConfirm = function(title, text, ev) {
		var confirm = $mdDialog.confirm(
				{onComplete: function afterShowAnimation(me,$event) {
		            var $dialog = $event; //angular.element(document.querySelector('md-dialog'));
		            var $actionsSection = $dialog.find('md-dialog-actions');
		            var $cancelButton = $actionsSection.children()[0];
		            var $confirmButton = $actionsSection.children()[1];
		            angular.element($confirmButton).removeClass('md-focused');
		            angular.element($cancelButton).addClass('md-focused');
		            $cancelButton.focus();
					}})
					.title(title).htmlContent(text).ok(
				'Ok').cancel('Annulla').multiple(true);

		if (typeof ev != "undefined")
			confirm.targetEvent(ev);

		return $mdDialog.show(confirm);
	}

	utilsSvc.showConfirmYesNo = function(title, text, ev) {
			var confirm = $mdDialog.confirm({onComplete: function afterShowAnimation() {
	            var $dialog = angular.element(document.querySelector('md-dialog'));
	            var $actionsSection = $dialog.find('md-dialog-actions');
	            var $cancelButton = $actionsSection.children()[0];
	            var $confirmButton = $actionsSection.children()[1];
	            angular.element($confirmButton).removeClass('md-focused');
	            angular.element($cancelButton).addClass('md-focused');
	            $cancelButton.focus();
			}})
			.title(title).htmlContent(text).ok(
				'Si').cancel('No').multiple(true);

		if (typeof ev != "undefined")
			confirm.targetEvent(ev);

		return $mdDialog.show(confirm);
	}

	utilsSvc.handleHttpError = function(error) {
		if (!utilsSvc.alreadyShowingError) {
			utilsSvc.alreadyShowingError = true;
			if (error.status == 401)
				utilsSvc.show(
						"Sessione scaduta o non valida: rieseguire la login: "
								+ error.statusText).then(function() {
					utilsSvc.alreadyShowingError = false;
					$location.path("/");
				});
			else {
				var msg = error.statusText;
				if (error.data)
					msg = error.data;
				if (error.data.value)
					msg = error.data.value;
				
				var title = msg;
				if (error.status != 404)
					title = "Errore " + error.status
					+ " durante la richiesta al server: "
					+ msg;
				
				utilsSvc.show(title).then(function() {
					utilsSvc.alreadyShowingError = false;
				});
			}
		}
	}

	utilsSvc.CheckId = function(id) {
		if (typeof id == "undefined")
			return false;
		if (id == null || id == 0)
			return false;
		return true;
	}

	utilsSvc.showMessage = function(message) {
		return  $mdToast.show($mdToast.simple({templateUrl : 'templates/toast-template.html', controller  : 'ToastCtrl', message:message}).content(message));
	}

	utilsSvc.show = function(message) {
		return $mdToast.show($mdToast.simple({templateUrl : 'templates/toast-wait-template.html', controller  : 'ToastCtrl', message:message}).content(message).hideDelay(0).action(
				"ok"));
	}

	utilsSvc.showForever = function(message) {
		$mdToast.show($mdToast.simple({templateUrl : 'templates/toast-template.html', controller  : 'ToastCtrl', message:message}).content(message).hideDelay(0));
	}

	utilsSvc.cancelMessage = function() {
		$mdToast.hide();
	}

	utilsSvc.showWaitMessage = function(message) {
		$('#waitIndicator').show();
	}

	utilsSvc.cancelWaitMessage = function() {
		$('#waitIndicator').hide();
	}

	utilsSvc.resizeGrid = function(rows, rowHeight) {
		// This will adjust the css after the Data is loaded
		var newHeight = (rows * rowHeight) + 60;
		angular.element(document.getElementsByClassName('grid')[0]).css(
				'height', newHeight + 'px');
	};

	utilsSvc.isEmpty = function(data) {
		return data == null || data == "";
	};

	utilsSvc.downloadFile = function(mimeType,data,filename) {
		// check for IE
		if (window.navigator.msSaveBlob) {
			blobObject = new Blob([data], {type: mimeType+";charset=utf-8"});
		    window.navigator.msSaveOrOpenBlob(blobObject, filename);
		} else {
			
			//if (mimeType=="application/pdf"){
				var blob = new Blob([data], {type: mimeType+";charset=utf-8"});
			    var link = document.createElement('a');
			    link.href = window.URL.createObjectURL(blob);
			    link.download = filename;
			    link.click();
//			} else {
//				var a         = document.createElement('a');
//				a.href        = 'data:'+mimeType +  "," + encodeURIComponent(data);
//				a.target      = '_blank';
//				a.download    = filename;
//		
//				document.body.appendChild(a);
//				a.click();
//				document.body.removeChild(a);
//			}
		}
	}
	
	utilsSvc.help = function(templateUrl, event) {
		$scope.help = function(ev) {
			var helpFile = 'help/' + templateUrl;
			$mdDialog.show({
				templateUrl : helpFile,
				controller : 'helpCtrl',
				targetEvent : ev
			});
		}
	}

	utilsSvc.dateDiff = function(d1, d2) {
		var delta = Math.abs(d2 - d1) / 1000;

		var days = Math.floor(delta / 86400);
		delta -= days * 86400;

		var hours = Math.floor(delta / 3600) % 24;
		delta -= hours * 3600;

		var minutes = Math.floor(delta / 60) % 60;
		delta -= minutes * 60;

		var seconds = Math.floor(delta % 60);

		var res = (days > 0 ? days + 'd' : '') + hours + 'h' + minutes + 'm'
				+ seconds + 's';

		return res;

	}

	utilsSvc.decodeCircuitoSDD = function(cod) {
		if (typeof cod == "undefined")
			return "";
		if (cod == "1")
			return "RID SEPA";
		if (cod == "2")
			return "SDD";
		if (cod == "3")
			return "SDD Esteri";
		return "RID CBI";
	}
	
	utilsSvc.decodeTipologia = function(tipologia){
		if (tipologia=="BONIFICI")
			return "SCT";
		else if (tipologia=="RID")
			return "SDD";
		else if (tipologia=="AEA")
			return "SEDA";
		else if (tipologia=="BONIFICI_ESTERI")
			return "STPE";
		else if (tipologia=="DOM")
			return "DOM";
		else if (tipologia=="BONIFICI_INTERNI")
			return "SCT_INT";
		else
			return tipologia;
			
		return "";
	}

	utilsSvc.largeScreen =function(){
		return $mdMedia('gt-sm');
	}

	utilsSvc.veryLargeScreen =function(){
		return $mdMedia('gt-md');
	}

	utilsSvc.smallScreen =function(){
		return !$mdMedia('gt-sm');
	}

	utilsSvc.getGridHeight=function(){
		if (utilsSvc.smallScreen())
			return {'height': '40px', 'min-height':'40px'};
		else
			return {'height': '30px', 'min-height':'30px'};
	}
	
	utilsSvc.getGridWithButtonHeight=function(){
		if (utilsSvc.smallScreen())
			return {'height': '30px', 'min-height':'30px'};
		else
			return {'height': '30px', 'min-height':'30px'};
	}
	
	utilsSvc.controllaCF = function(cf){
		cf = cf.toUpperCase();
		if( cf == '' )  return true;
		if( ! /^[0-9A-Z]{16}$/.test(cf) )
			return false
		var map = [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17,
			19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23];
		var s = 0;
		for(var i = 0; i < 15; i++){
			var c = cf.charCodeAt(i);
			if( c < 65 )
				c = c - 48;
			else
				c = c - 55;
			if( i % 2 == 0 )
				s += map[c];
			else
				s += c < 10? c : c - 10;
		}
		var atteso = String.fromCharCode(65 + s % 26);
		if( atteso != cf.charAt(15) )
			return false
		return true;
	}
	
	utilsSvc.controllaPIVA = function (pi)		{
		if( pi == '' )  return true;
		if( ! /^[0-9]{11}$/.test(pi) )
			return false
		var s = 0;
		for( i = 0; i <= 9; i += 2 )
			s += pi.charCodeAt(i) - '0'.charCodeAt(0);
		for(var i = 1; i <= 9; i += 2 ){
			var c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
			if( c > 9 )  c = c - 9;
			s += c;
		}
		var atteso = ( 10 - s%10 )%10;
		if( atteso != pi.charCodeAt(10) - '0'.charCodeAt(0) )
			return false;
		return true;
	}
	
	
	utilsSvc.isNumber=function(str){
		for (var i=0;i<str.length;i++)
			if ("0123456789".indexOf(str[i])==-1)
				return false;
		return true;
	}
	
	utilsSvc.allTrim=function(string) {
		return string.replace(/ /g, '')
	}
	
	utilsSvc.only=function(string, allowedChars){
		var res="";
		for (var i=0;i<string.length;i++)
			if (allowedChars.indexOf(string[i])>=0)
				res+=string[i];
		return res;
	}
	
	utilsSvc.controllaCFoPiva=function(txt) {
		if (txt==null|| txt=='')
			return true;
		if (txt.length==11)
			return utilsSvc.controllaPIVA(txt);
		if (txt.length==16)
			return utilsSvc.controllaCF(txt);
		return false;
	}
	
	utilsSvc.controlloIban1 = function(input) {
		    var CODE_LENGTHS = {
		        AD: 24, AE: 23, AT: 20, AZ: 28, BA: 20, BE: 16, BG: 22, BH: 22, BR: 29,
		        CH: 21, CR: 21, CY: 28, CZ: 24, DE: 22, DK: 18, DO: 28, EE: 20, ES: 24,
		        FI: 18, FO: 18, FR: 27, GB: 22, GI: 23, GL: 18, GR: 27, GT: 28, HR: 21,
		        HU: 28, IE: 22, IL: 23, IS: 26, IT: 27, JO: 30, KW: 30, KZ: 20, LB: 28,
		        LI: 21, LT: 20, LU: 20, LV: 21, MC: 27, MD: 24, ME: 22, MK: 19, MR: 27,
		        MT: 31, MU: 30, NL: 18, NO: 15, PK: 24, PL: 28, PS: 29, PT: 25, QA: 29,
		        RO: 24, RS: 22, SA: 24, SE: 24, SI: 19, SK: 24, SM: 27, TN: 24, TR: 26
		    };
		    var iban = String(input).toUpperCase().replace(/[^A-Z0-9]/g, ''), // keep only alphanumeric characters
		            code = iban.match(/^([A-Z]{2})(\d{2})([A-Z\d]+)$/), // match and capture (1) the country code, (2) the check digits, and (3) the rest
		            digits;
		    // check syntax and length
		    if (!code || iban.length !== CODE_LENGTHS[code[1]]) {
		        return false;
		    }
		    // rearrange country code and check digits, and convert chars to ints
		    digits = (code[3] + code[1] + code[2]).replace(/[A-Z]/g, function (letter) {
		        return letter.charCodeAt(0) - 55;
		    });
		    // final check
		    return utilsSvc.mod97(digits);
		}
	
		utilsSvc.mod97=function (string) {
		    var checksum = string.slice(0, 2), fragment;
		    for (var offset = 2; offset < string.length; offset += 7) {
		        fragment = String(checksum) + string.substring(offset, offset + 7);
		        checksum = parseInt(fragment, 10) % 97;
		    }
		    return checksum;
		}
	

	
		
	utilsSvc.controlloIban=function(iban) {
		if (iban==null || iban=="")
			return true;
		
		iban = utilsSvc.allTrim(iban.toUpperCase());
		
		if (utilsSvc.isNumber(iban.substring(0,2)))
			return false;
		
		if (utilsSvc.only(iban, "ABCDEFGHJKILMNOPQRSTUVWXYZ0123456789 ").length != iban.length)
			return false;
		
		if (iban.substr(0,2)=="IT" || iban.substr(0,2)=="SM")   {
			if (iban.length!=27)
				return false;
		}
		
		var bufStringa = iban;
		bufStringa = bufStringa.substring(4,99) + bufStringa.substring(0,4);
		var checkIban="";
		for (var i=0;i<bufStringa.length;i++){
			console.log("Check i: " + i+ " > " + bufStringa.substring(i,i+1));
			switch(bufStringa.substring(i,i+1)) {
				case "A": checkIban+="10";break;
				case "B": checkIban+="11";break;
				case "C": checkIban+="12";break;
				case "D": checkIban+="13";break;
				case "E": checkIban+="14";break;
				case "F": checkIban+="15";break;
				case "G": checkIban+="16";break;
				
				case "H": checkIban+="17";break;
				case "I": checkIban+="18";break;
				case "J": checkIban+="19";break;
				case "K": checkIban+="20";break;
				case "L": checkIban+="21";break;
				case "M": checkIban+="22";break;
				case "N": checkIban+="23";break;
				case "O": checkIban+="24";break;
				case "P": checkIban+="25";break;
				case "Q": checkIban+="26";break;
				case "R": checkIban+="27";break;
				case "S": checkIban+="28";break;
				case "T": checkIban+="29";break;
				case "U": checkIban+="30";break;
				case "V": checkIban+="31";break;
				case "W": checkIban+="32";break;
				case "X": checkIban+="33";break;
				case "Y": checkIban+="34";break;
				case "Z": checkIban+="35";break;
				default: checkIban+=bufStringa.substring(i,i+1);break;
			}
		}
		return utilsSvc.validateIban(checkIban, 97)==1
		
	}
	
	utilsSvc.validateIban=function(iban, modulo){
		var bufModulo=0;
		var i=1;
		var numero;
		do {
			if (i==1) {
				numero=parseFloat(iban.substring(i-1,i-1+9));
				i=10
			} else {
				numero=parseFloat(bufModulo.toString()+iban.substring(i-1,i-1+9-bufModulo.toString().length))
				i+=9-bufModulo.toString().length;
			}
			
			bufModulo = numero % modulo;
		} while (i<=iban.length);
		
		return bufModulo
	}
	
	utilsSvc.controlloCin=function(cin, abi, cab, conto) {
		var coordinate=abi.padZero(5) + cab.padZero(5)+conto.toUpperCase().padZero(12);
		var pari=false;
		var sommaCaratteri=0
		for(var i=1;i<=22;i++) {
			var carattere=coordinate.substring(i-1,i);
			
			pari = (i % 2) == 0;
			
			switch(carattere){
				case "A","0": sommaCaratteri+=(pari? 0: 1);break;
				case "B","1": sommaCaratteri+=(pari? 1: 0);break;
				case "C","2": sommaCaratteri+=(pari? 2: 5);break;
				case "D","3": sommaCaratteri+=(pari? 3: 7);break;
				case "E","4": sommaCaratteri+=(pari? 4: 9);break;
				case "F","5": sommaCaratteri+=(pari? 5: 13);break;
				case "G","6": sommaCaratteri+=(pari? 6: 15);break;
				case "H","7": sommaCaratteri+=(pari? 7: 17);break;
				case "I","8": sommaCaratteri+=(pari? 8: 19);break;
				case "J","9": sommaCaratteri+=(pari? 9: 21);break;
				case "K": sommaCaratteri+=(pari? 10: 2);break;
				case "L": sommaCaratteri+=(pari? 11: 4);break;
				case "M": sommaCaratteri+=(pari? 12: 18);break;
				case "N": sommaCaratteri+=(pari? 13: 20);break;
				case "O": sommaCaratteri+=(pari? 14: 11);break;
				case "P": sommaCaratteri+=(pari? 15: 3);break;
				case "Q": sommaCaratteri+=(pari? 16: 6);break;
				case "R": sommaCaratteri+=(pari? 17: 8);break;
				case "S": sommaCaratteri+=(pari? 18: 12);break;
				case "T": sommaCaratteri+=(pari? 19: 14);break;
				case "U": sommaCaratteri+=(pari? 20: 16);break;
				case "V": sommaCaratteri+=(pari? 21: 10);break;
				case "W": sommaCaratteri+=(pari? 22: 22);break;
				case "X": sommaCaratteri+=(pari? 23: 25);break;
				case "Y": sommaCaratteri+=(pari? 24: 24);break;
				case "K": sommaCaratteri+=(pari? 25: 23);break;
			}
		}
		
		var restoSommaCaratteri = sommaCaratteri % 26;
		
		switch(restoSommaCaratteri) {
			case 0: return "A"==cin;
			case 1: return "B"==cin;
			case 2: return "C"==cin;
			case 3: return "D"==cin;
			case 4: return "E"==cin;
			case 5: return "F"==cin;
			case 6: return "G"==cin;
			case 7: return "H"==cin;
			case 8: return "I"==cin;
			case 9: return "J"==cin;
			case 10: return "K"==cin;
			case 11: return "L"==cin;
			case 12: return "M"==cin;
			case 13: return "N"==cin;
			case 14: return "O"==cin;
			case 15: return "P"==cin;
			case 16: return "Q"==cin;
			case 17: return "R"==cin;
			case 18: return "S"==cin;
			case 19: return "T"==cin;
			case 20: return "U"==cin;
			case 21: return "V"==cin;
			case 22: return "W"==cin;
			case 23: return "X"==cin;
			case 24: return "Y"==cin;
			case 25: return "Z"==cin;
			default: return false;
		}
		
				
	}
	
	
	utilsSvc.checkValuta=function(event, len){
		if ("0123456789,.".indexOf(event.key)==-1 || event.target.value.length>=len)
			event.preventDefault();
	}

	
	
	return utilsSvc;
})
.controller('ToastCtrl', function($scope, $mdToast, $mdDialog, message) {
      $scope.message = message;
      $scope.closeToast = function() {
        $mdToast
          .hide()
      };
    });
