(function(){
    angular.module('ctfApp').controller('ScoreboardController', ['$scope', '$http', 'AppSettings', 'APIProvider', function($scope, $http, AppSettings, APIProvider) {

        var calculatePerTeam = function(data) {
            var teams = {};
            console.log("data", data);
            for (var team in data) {
                if (data.hasOwnProperty(team)) {
                    teams[team] = 0;
                    for (var level in data[team]){
                        if (data[team].hasOwnProperty(level)){
                            var score = data[team][level].map(function(o){return o.points;}).reduce(function(a,b){return a+b;});
                            teams[team] += score;
                        }
                    }
                }
            }
            return teams;
        };

        function viewGraph(maxValue){
            $('.column').css('height','0');
            // console.log($scope.teamsScores);
            setTimeout(function(){
                    $('.column').each(function(){
                        $(this).animate({width: (100 * (parseFloat($(this).attr('data-score'))/maxValue)).toString() + '%'}, 1500);
                    });
                }
            );
        }


        APIProvider.getScores(function(data){
            // console.log('Data from server', data);
            $scope.teamsScores = calculatePerTeam(data);
            // console.log('Teams scores', $scope.teamsScores);
            var maxValue = Math.max.apply(null, $.map($scope.teamsScores, function(v,k){return v;}));
            viewGraph(maxValue);
        });





    }]);

})();