var app = angular.module('infoApp', ['ngAnimate', 'ngRoute', 'monospaced.qrcode']);
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){
            $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);
    }
});
app.controller('ABBController', function($scope, $http){
    $scope.jobs = [];
    var min_date = moment().subtract(30,'days').format("YYYY-MM-DD%20HH:mm:ss");
    var url = "http://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("http://sosso.fi/api/get_recent_posts/?count=" + 3 ).then(function(response)
        {
            $scope.data = response.data;
        })
});

app.controller('timetableCtrl',
    function($scope, $http, $interval) {
        function load(){
            $http.get('/infoscreen/hsl_data')
                .then(function(data, status, headers, config) {
                    $scope.arr=[];
                    parse(data);
                });
            $http.get('/infoscreen/hsl_data/settings')
                .then(function(data, status, headers, config) {
                    $scope.departureThreshold = data.data['departure_threshold'];
                    $scope.hurryThreshold = data.data['hurry_threshold'];
                });
        }
        $scope.$on('$destroy', function() {
            $interval.cancel(inter1);
            $interval.cancel(inter2);
            $interval.cancel(inter3);
        });
        var objects;
        $scope.arr=[];
        var dict=[];
        function parse(data){
            objects=data['data'];
            for(var objectIndex in objects){
                var stop = objects[objectIndex];
                
                var lineIndex;
                for (lineIndex in stop['lines']){
                    var elem=stop['lines'][lineIndex].split(":");
                    dict[elem[0]]=elem[1];
                }
                for (lineIndex in stop['departures']){
                    var line = stop['departures'][lineIndex];
                    var time = line['time'];
                    var date = line['date'];
                    var hours = Math.floor(line['time'] / 100);
                    var minutes = line['time'] % 100;
                    if (hours >= 24) {
                        hours -= 24;
                        date++;
                    }
                    var code = line['code'].substring(1, 5);
                    if (code.charAt(0) == '0') {
                        code = code.substring(1,4);
                    }

                    var departure = {
                        "stop":       stop['name'].split(",")[0],
                        "dist":       stop['dist'],
                        "bus":        code,
                        "date":       date,
                        "time":       pad(hours, 2) + ":" + pad(minutes, 2),
                        "laststop":   dict[line['code']].split(",")[0].split(" l.")[0],
                        "hurry":      false
                    };
                    if(departure['laststop']=='Otaniemi')
                        break;
                    if(departure['stop']=='Alvar Aallon puisto')
                        departure['stop']="A. A. puisto"
                    var trigger = true;
                    for (var arrIndex = $scope.arr.length - 1; arrIndex >= 0; arrIndex--) {
                        if ($scope.arr[arrIndex]['bus'] == departure['bus'] && 
                            $scope.arr[arrIndex]['laststop'] == departure['laststop']) {

                            if ($scope.arr[arrIndex]['dist'] == departure['dist']){
                                break;
                            }
                            else if ($scope.arr[arrIndex]['dist'] > departure['dist']){
                                $scope.arr.splice(arrIndex, 1);
                            }
                            else {
                                trigger = false;
                            }
                        }
                    }
                    if (trigger) {
                            $scope.arr.push(departure);
                    }
                }
            }

            function pad(num, size) {
                var s = num + "";
                while (s.length < size) {
                    s = "0" + s;
                }
                return s;
            }

            delOld();
        }
        function delOld(){
            var tooSoon = typeof($scope.departureThreshold) != 'undefined' ? $scope.departureThreshold: 0;
            var hurry = typeof($scope.hurryThreshold) != 'undefined' ? $scope.hurryThreshold : 0;
            f = new Date();
            for(var a=$scope.arr.length-1; a>=0; a--){
                var time=$scope.arr[a]['time'].split(":");
                date=$scope.arr[a]['date'].toString();
                d= new Date(f);
                d.setFullYear(date.substring(0,4),date.substring(4,6)-1,date.substring(6,8));
                d.setHours(time[0]);
                d.setMinutes(time[1]);
                var diff=(d.getTime()-f.getTime());
                $scope.arr[a]['timedelta']=Math.floor(diff/60000);
                if(diff < tooSoon*60000) {
                    $scope.arr.splice(a,1);
                }
                else if (diff < hurry*60000) {
                    $scope.arr[a]['hurry']=true;
                }
            }
        }
        function updateTime(){
            $scope.clock = Date.now();
        }
        $scope.clock = Date.now();
        load();
        var inter1=$interval(delOld,2000);
        var inter2=$interval(load,10000);
        var inter3=$interval(updateTime, 1000);
    }
);

