var app = angular.module('infoApp', ['ngAnimate', 'ngRoute']);

app.controller('infoscreen_main', function($scope,$http,$timeout){
    var templates = [];
    $scope.init = function(rot){
        $scope.rotation = rot;
        get_rotation();
    }
    var get_rotation = function(){
        $scope.index = -1;
        $http.get('/infoscreen/rotation/'+$scope.rotation, {timeout:5000}).then(function(response){
            templates = response.data.instances;
            if (templates.length == 0) {
                $timeout(get_rotation, 10000);
            }
            else {
                $scope.next();
            }
        },function(response) { //eslint-disable-line no-unused-vars
            $timeout(get_rotation, 10000);
        });
    }

    $scope.next = function(){
        $scope.index++;
        if ($scope.index >= templates.length){
            return get_rotation();
        }
        var temp = templates[$scope.index];
        $scope.active = {
            template: temp.item.template_url,
            onload: function(){
                for (var key in temp.item.options){
                    $scope[key] = temp.item.options[key]
                }
            }
        };
        $timeout($scope.next, temp.duration * 1000);
    }
});

//Doing this the ugly way because Angular likes to be the special priviledged child
app.filter('trusted_url', ['$sce', function ($sce) {
    return function(url) {
        return $sce.trustAsResourceUrl(url);
    };
}]);

//Used for special characters in Sosso. This may open up XSS, so we need to trust that sosso.fi doesn't get compromised...
app.filter('unsafe', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
});

app.controller('ABBController', function($scope, $http){
    $scope.jobs = [];
    var min_date = moment().subtract(30,'days').format("YYYY-MM-DD%20HH:mm:ss");
    var url = "https://sahkoinsinoorikilta.fi/api/news.php";
    var params = "?type=11&lang=fi&title_search=ABB&min_date="+min_date
    $http.get(url+params).then(function(response){
        $scope.jobs = _.filter(response.data, function(job){
            if (job.autohide_enabled == 1){
                if (moment(job.autohide) < moment()){
                    return false;
                }
            }
            return true;
        });

        if ($scope.jobs.length > 3) {
            $scope.jobs = $scope.jobs.slice(0, 3);
        }
    });
});

app.controller('SossoController', function($scope, $http) {
    $scope.data = [];
    $http.get("https://sosso.fi/api/get_recent_posts/?count=" + 3 ).then(function(response)
        {
            $scope.data = response.data;
        })
});

app.controller('LunchController', function ($scope, $http) {
    $scope.data = [];
    var restaurants = [42];
    var restaurant_names = ["TUAS"]
    var cur_date = new Date().toISOString().split("T")[0]
    $http.get("https://kitchen.kanttiinit.fi/menus?restaurants=" + restaurants.join(",") + "&days=" + cur_date).then(function (response) {
        $scope.data = restaurant_names.map(function(n, idx) {
            return {
                name: n,
                lunch: response[idx][cur_date],
            }
        });
    })
});

app.controller('ApyController', function($scope, $http) {
    $scope.items = [];
    $http.get("/infoscreen/apyjson").then(function(response)
    {
        $scope.items = response.data.data
    })
});

app.controller('EventController', function($scope, $http) {
    $scope.data = [];
    $http.get("https://sik.ayy.fi/api/events.php?limit=10").then(function(response)
        {
            $scope.events = response.data;
            $scope.events = _.each($scope.events, function(ev){
                var time = moment(ev.event_start);
                ev.event_start = time;
                ev.event_start = time.format("ddd DD.MM.");
                // lets not trust locale
                ev.event_start = ev.event_start.replace("Mon", "Ma");
                ev.event_start = ev.event_start.replace("Tue", "Ti");
                ev.event_start = ev.event_start.replace("Wed", "Ke");
                ev.event_start = ev.event_start.replace("Thu", "To");
                ev.event_start = ev.event_start.replace("Fri", "Pe");
                ev.event_start = ev.event_start.replace("Sat", "La");
                ev.event_start = ev.event_start.replace("Sun", "Su");
            });
        })
});

app.filter('unixTimeToDifference', function() {
    return function(input) {
        var date = moment.unix(input);
        var now = moment();
        var res = date.diff(now, 'minutes');
        return res;
    }
})
