'use strict';

/**
 * @ngdoc function
 * @name leagueComparerApp.controller:ResultsCtrl
 * @description
 * # ResultsCtrl
 * Controller of the leagueComparerApp
 */
angular.module('leagueComparerApp')
  .controller('ResultsCtrl', function($scope, transferData, championManager, $location) {
    // Gets summoners names using the transferData service
    $scope.summonerName1 = transferData.get(0);
    $scope.summonerName2 = transferData.get(1);

    $scope.isCollapsed = true;

    // Gets both summoner's status using a champion using championManager service
    $scope.champData1 = championManager.getChampionStats(0);
    $scope.champData2 = championManager.getChampionStats(1);

    // Gets name and title of the selected champion
    $scope.champName;

    // If fails to get any information needed, redirect to the main view
    if ($scope.summonerName1 === undefined || $scope.summonerName2 === undefined || $scope.champData1 === undefined || $scope.champData2 === undefined) {
      $location.path('/');
    }

    // Store score of summoners
    var score = {
      summoner1: 0,
      summoner2: 0
    };

    // Decides which summoner has won
    $scope.statSummoner = function(summoner) {
      var stat = 'summoner-same';
      if(summoner === 1) {
        if (score.summoner1 > score.summoner2) {
          stat = 'summoner-bigger';
        } else if (score.summoner1 < score.summoner2) {
          stat = 'summoner-lower';
        }
      } else {
        if (score.summoner2 > score.summoner1) {
          stat = 'summoner-bigger';
        } else if (score.summoner2 < score.summoner1) {
          stat = 'summoner-lower';
        }
      }
      return stat;
    }

    // Decides if summoner has bigger, lower or same stats. 1: summoner1 - 2: summoner2
    $scope.statClass = function(summoner, key) {
      var stat = 'stat-same';
      var trueSummoner = summoner;
      if (shouldBeAverage(key)) {
        if (shouldRevert(key)) {
          summoner === 1 ? summoner = 2 : summoner = 1;
        }
        if (summoner === 1) {
          if (simpleAverage($scope.champData1[key], $scope.champData1.totalSessionsPlayed) > simpleAverage($scope.champData2[key], $scope.champData2.totalSessionsPlayed)) {
            stat = 'stat-bigger';
          } else if (simpleAverage($scope.champData1[key], $scope.champData1.totalSessionsPlayed) < simpleAverage($scope.champData2[key], $scope.champData2.totalSessionsPlayed)) {
            stat = 'stat-lower';
          }
        } else if (summoner === 2) {
          if (simpleAverage($scope.champData2[key], $scope.champData2.totalSessionsPlayed) > simpleAverage($scope.champData1[key], $scope.champData1.totalSessionsPlayed)) {
            stat = 'stat-bigger';
          } else if (simpleAverage($scope.champData2[key], $scope.champData2.totalSessionsPlayed) < simpleAverage($scope.champData1[key], $scope.champData1.totalSessionsPlayed)) {
            stat = 'stat-lower';
          }
        }
      }
      else {
        if (shouldRevert(key)) {
          summoner === 1 ? summoner = 2 : summoner = 1;
        }
        if (summoner === 1) {
          if ($scope.champData1[key] > $scope.champData2[key]) {
            stat = 'stat-bigger';
          } else if ($scope.champData1[key] < $scope.champData2[key]) {
            stat = 'stat-lower';
          }
        } else if (summoner === 2) {
          if ($scope.champData2[key] > $scope.champData1[key]) {
            stat = 'stat-bigger';
          } else if ($scope.champData2[key] < $scope.champData1[key]) {
            stat = 'stat-lower';
          }
        }
      }

      if (trueSummoner === 1 && stat === 'stat-bigger') {
        score.summoner1++;
      } else if (trueSummoner === 2 && stat === 'stat-bigger') {
        score.summoner2++;
      }
      updateScore();
      return stat;
    };

    // Returns average results
    $scope.getAverage = function(value, key, summoner) {
      var finalVal = value;
      if (shouldBeAverage(key) && summoner === 1) {
        // .toFixed rounds the number with the given quantity of numbers after the floating point
        finalVal = (value / $scope.champData1.totalSessionsPlayed).toFixed(4);
      } else if (shouldBeAverage(key) && summoner === 2) {
        finalVal = (value / $scope.champData2.totalSessionsPlayed).toFixed(4);
      }
      return finalVal;
    }

    function simpleAverage(value, matches) {
      return value/matches;
    }

    // Colors scores
    $scope.scoreClass = function(summoner) {
      var desiredClass = 'score-same';
      if (summoner === 1) {
        if (score.summoner1/3 > score.summoner2/3) {
          desiredClass = 'score-bigger';
        }
        else if (score.summoner1/3 < score.summoner2/3) {
          desiredClass = 'score-lower';
        }
      }
      if (summoner === 2) {
        if (score.summoner2/3 > score.summoner1/3) {
          desiredClass = 'score-bigger';
        }
        else if (score.summoner2/3 < score.summoner1/3) {
          desiredClass = 'score-lower'
        }
      }
      return desiredClass;
    }

    // Decides if data should be displayed as an average value
    function shouldBeAverage(key) {
      var shouldntBeAverage = ['totalSessionsPlayed', 'maxChampionsKilled', 'maxNumDeaths', 'mostChampionsKillsPerSession', 'mostSpellCast'];
      if ($.inArray(key, shouldntBeAverage) === -1) {
        return true;
      }
      return false;
    }

    // Decides if the comparison should be reversed
    function shouldRevert(comparison) {
      var shouldRevert = ['maxNumDeaths', 'totalDamageTaken', 'totalDeathsPerSession', 'totalSessionsLost'];
      if ($.inArray(comparison, shouldRevert) !== -1) {
        return true;
      }
      return false;
    }

    // Add score to the view via jquery
    function updateScore() {
      var comparisons = Object.keys($scope.champData1).length;
      $('#score1').html(' ' + $('#stats1 .stat-bigger').length + '/' + comparisons);
      $('#score2').html(' ' + $('#stats2 .stat-bigger').length + '/' + comparisons);
    }

    //Does the request to display the desired champion's name and description on the results screen
    $.ajax('https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/' + transferData.get(2) + '?api_key=0c2f29fd-b02f-4fdf-b0c5-c4b27f532efc', {
      dataType: 'json',
      async: false,
      success: function(data) {
        $scope.champName = data.name + ', ' + data.title;
      },
      error: function() {
        console.log('An error occurred while getting champion data.');
      }
    });

  });
