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

(function (angular) {
  "use strict";

  /**
   * @ngdoc controller
   * @name FootballController
   *
   * @description
   * Controller for the football page.
   *
   * @ngInject
   */
  function FootballController(
    $ionicHistory,
    $scope,
    $http,
    $q,
    $ionicLoading,
    PurchaseService,
    NotificationService,
    constantConfig,
    purchaseConfig,
    ToastService
  ) {

    /**
     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 'football-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, 'football', self.findPack($scope.selected.length));
      }
    };


    $scope.buyContent = function () {
      var pack = self.findPack($scope.selected.length);
      console.log(self.uuid);
      PurchaseService.buyContent(self.uuid, pack, $scope.selected);
    };

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

      return '';
    };

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

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

      percentages.sort(function(a, b){return a-b});
      var predictionWin = null;
      if (prediction.winner) {
        if (prediction.winner === -1) {
          predictionWin = prediction.prediction_draw;
        } else {
          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;
        prediction.score = score.split('-');
      }
    };

    this.isAllChampionsLeague = function () {
      return $scope.selected[0].unitary_pack_name === 'champions_league'
        && $scope.selected[1].unitary_pack_name === 'champions_league';
    };

    this.containsChampionsLeague = function () {
      var contains = false;
      $scope.selected.forEach(function (league) {
        if (league.unitary_pack_name === 'champions_league') {
          contains = true;
        }
      });

      return contains;
    };

    this.findPrice = function (length) {
      var packToGet = self.findPack(length);

      if (packToGet !== '') {
        var price = '';
        this.products.forEach(function (el) {
          if (el.productId === packToGet) {
            price = el.price;
          }
        });
        return price;
      } else {
        ToastService.show('selection_not_ok', 'long', 'bottom');
      }
    };

    this.findPack = function (length) {
      var packToGet = '';

      if (length === 1) {
        packToGet = $scope.selected[0].unitary_pack_name;
      } else if (length == 2) {
        if (self.isAllChampionsLeague()) {
          packToGet = 'full_champions_league';
        } else if (self.containsChampionsLeague()) {
          ToastService.show('selection_not_ok', 'long', 'bottom');
        } else {
          packToGet = 'football_full_2';
        }
      } else if (length <= 6) {
        if (!self.containsChampionsLeague()) {
          packToGet = 'football_full_' + length;
        } else {
          ToastService.show('selection_not_ok', 'long', 'bottom');
        }
      }

      return packToGet;
    };

    /**
    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;
    });

    ionic.Platform.ready(function () {
      $ionicLoading.show({
        template: '<ion-spinner icon="ripple" class="spinner-assertive"></ion-spinner>',
        animation: 'fade-in',
        showBackdrop: true
      });

      NotificationService.registerDevice();

      self.uuid = window.cordova ? ionic.Platform.device().uuid : '7f4a6a40e5c87157';

      var freePredictionsPromise = $http.get(constantConfig.apiUrl + 'predictions/football/free');
      var leaguesPromise = $http.get(constantConfig.apiUrl + self.uuid + '/leagues/football');
      var promises = [freePredictionsPromise, leaguesPromise];
      if (window.cordova) {
        var storePromise = inAppPurchase.getProducts(purchaseConfig['football']);
        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 >= 2) {
          self.shouldUp = true;
        }

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

    });



    /**
    End Scope event
    **/
  }

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