/**
 * Created by jeremyguiselin on 25/09/2016.
 */

(function (angular) {
  "use strict";

  /**
   * @ngdoc controller
   * @name Tennis Controller
   *
   * @description
   * Controller for the tennis index page.
   *
   * @ngInject
   */
  function TennisController(
    $ionicHistory,
    $scope,
    $http,
    $q,
    $ionicLoading,
    PurchaseService,
    constantConfig,
    purchaseConfig
  ) {

    /**
    Static variables
    **/

    var deregistrationCallbackList = [];
    var self = this;
    self.shouldUp = false;

    /**
    End Controller variables
    **/

    /**
    Scope variables
    **/

    $scope.pictureUrl = constantConfig.imgUrl;
    $scope.locale = window.navigator.language.split('-')[0];
    $scope.selected = [];
    $scope.price = 0;
    $scope.predictionsNumber = 0;

    /**
    End Scope variables
    **/

    /**
    Scope functions
    **/

    $scope.isUndefined = function (value) {
      return typeof value === 'undefined' || value === null;
    };

    $scope.isBought = function (league) {
      return league.device_status === 'unlock';
    };

    $scope.getLink = function (league) {
      if (league.device_status === 'unlock') {
        return 'tennis-details({leagueId:' + league.id + '})';
      }

      return '-';
    };

    $scope.isSelected = function (league) {
      return $scope.selected.indexOf(league) !== -1;
    };

    $scope.select = function (league) {
      if (!$scope.isBought(league.id)) {
        if ($scope.selected.indexOf(league) !== -1) {
          $scope.selected.splice($scope.selected.indexOf(league), 1);
          if (league.predictions_number) {
            $scope.predictionsNumber -= league.predictions_number;
          }
        } else {
          $scope.selected.push(league);
          if (league.predictions_number) {
            $scope.predictionsNumber += league.predictions_number;
          }
        }

        var list = angular.element(document.querySelector('#list-packs .list'));
        var ionContent = angular.element(document.querySelector('ion-content'))[0];
        var ionContentObj = angular.element(document.querySelector('ion-content'));
        var leagueHeight = angular.element(document.querySelector('.pack-item'))[0].scrollHeight;

        if (self.shouldUp && $scope.selected.length > 0) {
          list.css('marginBottom', '47px');
          if (ionic.Platform.isIOS()) {
            ionContentObj.css('marginBottom', '47px');
          }
        } else if (self.shouldUp && $scope.selected.length == 0) {
          list.css('marginBottom', '0');
          if (ionic.Platform.isIOS()) {
            ionContentObj.css('marginBottom', '0');
          }
        }

        if (self.shouldUp && $scope.selected.length > 0) {
          ionContent.scrollTop = ionContent.scrollHeight + 50;
        }

        var price = self.findPrice($scope.selected.length);
        $scope.price = price;
        $scope.$parent.$parent.select($scope.selected, price, $scope.predictionsNumber, 'tennis', self.findPack());
      }
    };

    $scope.getPredictionClass = function (prediction, value) {
      var percentages = [
        prediction.prediction_win_first,
        prediction.prediction_win_second
      ];
      percentages.sort(function(a, b){return a-b});
      if (percentages.indexOf(value) === 1) {
        return "main-prediction";
      }

      return '';
    };

    $scope.buyContent = function () {
      var selectedPack = '';
      if ($scope.selected.length === 1) {
        selectedPack = 'tennis';
      } else if($scope.selected.length > 1 && $scope.selected.length <= 6) {
        var packNumber = $scope.selected.length - 1;
        selectedPack = 'tennis_full_'+ packNumber;
      }

      if (selectedPack !== '') {
        PurchaseService.buyContent(constantConfig.uuid, selectedPack, $scope.selected);
      }
    };

    $scope.getTick = function (prediction) {
      var percentages = [
        prediction.prediction_win_first,
        prediction.prediction_win_second
      ];

      var ticks = [
        'red-cross',
        'green-tick'
      ];

      percentages.sort(function(a, b){return a-b});
      var predictionWin = null;
      if (prediction.winner) {
        predictionWin = prediction.prediction_win_second;
        if (prediction.first_team.id === prediction.winner) {
          predictionWin = prediction.prediction_win_first;
        }
        return ticks[percentages.indexOf(predictionWin)];
      }

      return null;
    };

    $scope.parseDate = function (date) {
      if (typeof date === 'undefined' || date == "") {
        return "";
      } else {
        var locale = window.navigator.language.split('-')[0];
        date = date.split(' ')[0].split('-');

        if (locale === "fr") {
          return date[2] + '/' + date[1] + '/' + date[0].substr(-2);
        } else {
          return date[1] + '/' + date[2] + '/' + date[0].substr(-2);
        }
      }
    };

    /**
    End Scope functions
    **/

    /**
    Controller functions
    **/

    this.parseScore = function (prediction) {
      if (prediction.score) {
        var score = prediction.score;
        var sets = score.split(' ');
        var scores = [];
        sets.forEach(function (set) {
          scores.push(set.split('-'));
        });
        prediction.score = scores;
      }
    };

    this.findPrice = function (length) {
      var packToGet = '';
      if (length === 1) {
        packToGet = 'tennis';
      } else if (length > 1 && length <= 6) {
        packToGet = 'tennis_full_' + (length - 1);
      }

      if (packToGet !== '') {
        var price = '';
        self.products.forEach(function (el) {
          if (el.productId === packToGet) {
            price = el.price;
          }
        });
        return price;
      }
    };
    
    this.findPack = function () {
      var selectedPack = '';
      if ($scope.selected.length === 1) {
        selectedPack = 'tennis';
      } else if($scope.selected.length > 1 && $scope.selected.length <= 6) {
        var packNumber = $scope.selected.length - 1;
        selectedPack = 'tennis_full_'+ packNumber;
      }
      
      return selectedPack;
    };

    /**
    End Controller functions
    **/

    /**
    Scope events
    **/

    deregistrationCallbackList.push(
      $scope.$on('$ionicView.afterEnter', function(){
        $ionicHistory.clearHistory();
      })
    );

    $scope.$on('$destroy', function(){
      angular.forEach(deregistrationCallbackList, function(deregistrationCallback){
        deregistrationCallback();
      });
      deregistrationCallbackList = null;
    });

    $scope.$on("$ionicView.beforeEnter", function(event, data){
      $ionicLoading.show({
        template: '<ion-spinner icon="ripple" class="spinner-assertive"></ion-spinner>',
        animation: 'fade-in',
        showBackdrop: true
      });

      var freePredictionsPromise = $http.get(constantConfig.apiUrl + 'predictions/tennis/free');
      var leaguesPromise = $http.get(constantConfig.apiUrl + constantConfig.uuid + '/leagues/tennis');
      var promises = [freePredictionsPromise, leaguesPromise];
      if (window.cordova) {
        var storePromise = inAppPurchase.getProducts(purchaseConfig['tennis']);
        promises.push(storePromise);
      }

      $q.all(promises).then(function (data) {
        var freePredictions = [];
        data[0]['data'].forEach(function (prediction) {
          self.parseScore(prediction);
          freePredictions.push(prediction);
        });
        $scope.freePredictions = freePredictions;
        $scope.leagues = data[1]['data'];

        if ($scope.leagues.length >= 3) {
          self.shouldUp = true;
        }

        if (window.cordova) {
          self.products = data[2];
        } else {
          self.products = purchaseConfig['mock']['tennis'];
        }
      }).finally(function () {
        $ionicLoading.hide();
      });
    });

    /**
    End Scope event
    **/

  }

  angular.module('starter')
    .controller('TennisController', TennisController);
})(angular);