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

        var calculatePerTeam = function(data) {
            var teams = {};
            var teamsSortable = [];
            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)){
                            teams[team] += data[team][level];
                        }
                    }
                    teamsSortable.push({name:team, score:teams[team]});
                }

            }
            teamsSortable.sort(function(a,b){return a.score < b.score;});
            return teamsSortable;
        };

        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);
                    });
                    $('#col-'+$cookieStore.get('teamname')).css('background-color', '#d33e44');
                }
            );
        }


        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, $scope.teamsScores.map(function(v){return v.score;}));
            viewGraph(maxValue);
        });





    }]);

})();