angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {

  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  
})

.controller('SettingsCtrl', function($scope) {
  
})

.controller('CategoriesCtrl', function($scope) {
  $scope.categories = [
    { title: 'Game', name: "GAME" },
    { title: 'Entertainment', name: "ENTER" },
    { title: 'Lifestyle', name: "GAME" },
    { title: 'Shopping', name: "GAME" },
    { title: 'Weather', name: "GAME" },
    { title: 'Health and Fitness', name: "GAME" },
    { title: 'Productivity', name: "GAME" },
  ];
})

.controller('AppsCtrl', function($scope, $stateParams, $http, $ionicLoading, $state) {
  $scope.loadingShow = function() {
    $ionicLoading.show({
      template: 'Loading...',
      duration: 3000
    }).then(function(){
       console.log("The loading indicator is now displayed");
    });
  };
  $scope.loadingHide = function(){
    $ionicLoading.hide().then(function(){
       console.log("The loading indicator is now hidden");
    });
  };

  $scope.catId = $stateParams.catId;
  var query = "";
  if($scope.catId) {
    query += "/?genre=" + $scope.catId;
  }
  $scope.loadingShow();
  $http.get('https://trust4app.herokuapp.com/crawler/downloadedapps' + query).then(function(response){
    $scope.apps = response.data;
    $scope.loadingHide();
  });

  $scope.showApp = function(app) {
    $state.go('app.single', { appId : app.appId });
  }
})

.controller('SingleCtrl', function($scope, $stateParams, $http, $ionicLoading) {
  $scope.loadingShow = function() {
    $ionicLoading.show({
      template: 'Loading...',
      duration: 1000
    }).then(function(){
       console.log("The loading indicator is now displayed");
    });
  };
  $scope.loadingHide = function(){
    $ionicLoading.hide().then(function(){
       console.log("The loading indicator is now hidden");
    });
  };

  $scope.app = {};
  $scope.reputationHTI = false;
	$scope.spHTI = false;
	$scope.finalHTI = false;
  $scope.appId = $stateParams.appId;
  $scope.loadingShow();
  $http.get('https://trust4app.herokuapp.com/crawler/downloadedapps/' + $scope.appId).then(function(response){
    $scope.app = response.data;
    $scope.loadingShow();
  });
  $scope.$watch('app', function (newValue, oldValue, scope) {
		if(newValue.appId) {
			$scope.showCertainTrust();			
		}
  });

  $scope.showCertainTrust = function () { //this will just calculate the expectation of the Reputaion and SP QUality category considering the sub categories
		var f = 0.0;
		var CT_objects = [];
		var CT_names = ['ratingsCT', 'reviewsCT', 'securityRisksCT', 'privacyRisksCT'];

		var app = $scope.app;

		for (var i = 0, element; element = CT_names[i]; ++i) {
			var CT_object;

			if (-1 !== element.indexOf('ratings')) {
				CT_object = new CertainTrust(Number(app.averageRatingTrustValue.toFixed(2)), Number(app.averageRatingConfidenceValue.toFixed(2)), f, 3);
			}
			if (-1 !== element.indexOf('reviews')) {
				CT_object = new CertainTrust(Number(app.reviewsTrustValue.toFixed(2)), Number(app.reviewsConfidenceValue.toFixed(2)), f, 3);
			}
			if (-1 !== element.indexOf('security')) {
				CT_object = new CertainTrust(Number(app.sTrustValue.toFixed(2)), Number(app.sConfidenceValue.toFixed(2)), f, 3);
			}
			if (-1 !== element.indexOf('privacy')) {
				CT_object = new CertainTrust(Number(app.pTrustValue.toFixed(2)), Number(app.pConfidenceValue.toFixed(2)), f, 3);
			}

			// the result HTIs should be read-only
			var HTI = new CertainTrustHTI(CT_object, { domParent: element, readonly: true });

			CT_objects[element] = CT_object;
		}
		// ANDObserver.update();

		f = 0.9;

		var spQualityCT_result = CT_objects['securityRisksCT'].AND(CT_objects['privacyRisksCT']);
		spQualityCT_result.setF(f);
		var HTI2 = new CertainTrustHTI(spQualityCT_result, { domParent: "spQualityAndResult", readonly: true });

		
		var wFusionArr = new Array();
		wFusionArr.push(CT_objects['ratingsCT']);
		wFusionArr.push(CT_objects['reviewsCT']);

		var wFusionWeightArr = new Array();
		wFusionWeightArr.push(1/3);
		wFusionWeightArr.push(2/3);

		var repuatationWFusionCT_result = CT_objects['ratingsCT'].wFusion(wFusionArr,wFusionWeightArr);
		repuatationWFusionCT_result.setF(f);
		var HTI1 = new CertainTrustHTI(repuatationWFusionCT_result, { domParent: "reputationWFusionResult", readonly: true });

		var finalAndCT_result = repuatationWFusionCT_result.AND(spQualityCT_result);
		var HTI3 = new CertainTrustHTI(finalAndCT_result, { domParent: "finalAndResult", readonly: true });

		var ct1 = new CertainTrust("Reputation",repuatationWFusionCT_result.getT(), repuatationWFusionCT_result.getC(),repuatationWFusionCT_result.getF(),3);
		var ct2 = new CertainTrust("S&p Quality",spQualityCT_result.getT(), spQualityCT_result.getC(),spQualityCT_result.getF(),3);
		new CertainTrustTViz([ct1,ct2], { id: "tvizAnd", middle: "AND", canvas: { height: 300, width: 300 },
			onClick: function(certainTrust) {
				if (certainTrust.getName() === "Reputation") $scope.reputationHTI = true;
				else $scope.spHTI = true;
				$scope.$apply();
			},
			onMiddleClick: function(certainTrust) {
				$scope.finalHTI = true;
				$scope.$apply();
			}
		});

	}
  
});
