(function(){
    angular.module('ctfApp').factory('APIProvider', ['$http', 'AppSettings', function($http, AppSettings){
        var tasks, teams, scores;
        return {

            getScores: function(callback){
                $http.get('http://' + AppSettings.apiAddress + '/solutions/all').
                    success(function(data) {
                        scores = data;
                        if (callback) callback(data);
                    });
            },

            getTasks: function(callback){
                $http.get('http://' + AppSettings.apiAddress + '/tasks').
                    success(function(data) {
                        this.getMySolutions(function(solutions){
                            data.filter(function(task){
                                return Object.keys(solutions).map(function(a){return parseInt(a);}).indexOf(task.level) !== -1;
                            }).map(function(task){
                                task.completedFlags = solutions[task.level];
                                return task;
                            });
                            tasks = data;
                            if (callback) callback(data);
                        });
                    }.bind(this));
            },

            getMySolutions: function(callback){
                $http.get('http://' + AppSettings.apiAddress + '/solutions/my').
                    success(function(data) {
                        if (callback) callback(data);
                    });
            },

            getTaskById: function(id, callback){
                var result;
                if (!tasks) {
                    this.getTasks(function(data){
                        result = this.getTaskById(id, callback);
                    }.bind(this));
                }
                else {
                    result = tasks.filter(function(task){
                        return task.level == id;
                    })[0];
                }
                callback(result);
            },


            getMySubmittedFlagsForTask: function(id){

            },

            /**
             * Returns an array of completed levels' ids.
             * @param callback
             */
            getMyCompletedLevelsList: function(callback){
                $http.get('http://' + AppSettings.apiAddress + '/solutions/my/completed').
                    success(function(data) {
                        if (callback) callback(data);
                    });
            },

            /**
             *
             * @param level
             * @param flag
             * @returns {HttpPromise}
             */
            submitFlag: function(level, flag){
                return $http.post('http://' + AppSettings.apiAddress + '/solutions/' + level, flag);
            }
        };
    }]);
})();