var app = angular.module('nasa-page-scraper',['ngRoute']);

app.config(function($routeProvider){

});

app.controller('scrapeController',function($scope, $http, $timeout){
	var pageUrl = 'http://crossorigin.me/http://technology.nasa.gov/svr/search.php?d=patent&q=&p=';
	var patentUrl = 'http://crossorigin.me/http://technology.nasa.gov/svr/search.php?d=patent&r=geturl&q=';
    $scope.results = [];
    $scope.currentPage = 0;
    $scope.pageCount = 0;
    $scope.total = 0;
    $scope.itemsToLoad = [];
    $scope.startTime = 0;
    $scope.timeRemain = 0;
    $scope.vm = {toggle: 0};

	$scope.loadNextPage = function() {
	  if ($scope.vm.toggle % 2 === 0 || $scope.itemsToLoad.length > 0 || ($scope.pageCount > 1 && $scope.currentPage > $scope.pageCount)) return;

	  $http.get(pageUrl + $scope.currentPage).
		  then(function(response) {
		    // this callback will be called asynchronously
		    // when the response is available
		    $scope.itemsToLoad = response.data.results;
		    if (!$scope.pageCount) {
		      $scope.total = response.data.total;
		      $scope.pageCount = Math.ceil(response.data.total / response.data.page_ln);
		      $scope.startTime = new Date();
		    }
            $timeout($scope.loadNextItem, 50);

		  }, function(response) {
		    // called asynchronously if an error occurs
		    // or server returns response with an error status.
		  });
	}

    $scope.$watch('vm.toggle', $scope.loadNextPage);

    $scope.loadNextItem = function(){
    	var item = $scope.itemsToLoad.pop();
    	if (item)
    	{
          var search = item[4];
          if (search.indexOf('patent_') < 0) {
            search = item[1];
          }
          
    	  $scope.loadItem(search);
    	}
    	else {
    		// load next page		
    		$scope.currentPage++;
    		$timeout($scope.loadNextPage, 500);
    	}

		$scope.duration = ((new Date().getTime()) - $scope.startTime.getTime());
		$scope.timeRemain = ($scope.pageCount - $scope.currentPage) * ($scope.duration /($scope.currentPage + 1)) / 1000;
    }

	$scope.loadItem = function(v){
		// Simple GET request example :
		$http.get(patentUrl + v).
		  then(function(response) {
		    // this callback will be called asynchronously
		    // when the response is available
            var item = response.data.results[0];
            if (item){
              if (item.abstract)
                 item.abstract = item.abstract.replace('\n', ' ').replace('\r', ' ');
              if (item.title)
                 item.title = item.title.replace('\n', ' ').replace('\r', ' ');

		      $scope.results.push(item);
            }
          
		    $timeout($scope.loadNextItem, 300);
		  }, function(response) {
		    // called asynchronously if an error occurs
		    // or server returns response with an error status.
		    $timeout($scope.loadNextItem, 300);
		  });
	}

	$scope.getContact = function(a){

	  var contact;
      var c = (a || '').toLowerCase();

      switch (c) {
         case "arc":
            contact = 'kim.l.chrestenson@nasa.gov<';
            break;
         case "afrc":
         case "dfrc":
            contact = 'earl.s.adams@nasa.gov';
            break;
         case "grc":
            contact = 'jason.m.hanna@nasa.gov';
            break;
         case "gsfc":
            contact = 'techtransfer@gsfc.nasa.gov';
            break;
         case "hq":
         case "hdqs":
            contact = 'stanley.artis-1@nasa.gov';
            break;
         case "jpl":
            contact = 'brian.a.morrison@nasa.gov';
            break;
         case "jsc":
            contact = 'jsc-techtran@mail.nasa.gov';
            break;
         case "ksc":
            contact = 'roger.h.liang@nasa.gov';
            break;
         case "larc":
            contact = 'stuart.pendleton@nasa.gov';
            break;
         case "msfc":
            contact = 'msfc-sra-team@mail.nasa.gov';
            break;
         case "ssc":
            contact = 'gigi.h.savona@nasa.gov';
            break;
         default:
            contact = '';
      }
      return contact;
	}

	$scope.doSelectText = function() {
		var el = $('table');
	    var range, selection;

	    if (window.getSelection) {
	      selection = window.getSelection();
	      range = document.createRange();
	      range.selectNodeContents(el[0]);
	      selection.removeAllRanges();
	      selection.addRange(range);
	    } else if (document.body.createTextRange) {
	      range = document.body.createTextRange();
	      range.moveToElementText(el[0]);
	      range.select();
	    }	
	}

});
