
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;
            $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 (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;
        })
    })
});
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('/static/js/hsl.json')
				.then(function(data, status, headers, config) {
					$scope.arr=[];
					parse(data);
				});
		};
		var obj;
		$scope.arr=[];
		var dict=[];
		function parse(data){
			obj=data['data'];
			for(var a in obj){
				for(var b in obj[a]['lines']){
					var elem=obj[a]['lines'][b].split(":");
					dict[elem[0]]=elem[1];
				}
				for(var b in obj[a]['departures']){
					var e=true;
					var time=obj[a]['departures'][b]['time'];
					date=obj[a]['departures'][b]['date'];
					if(time<1000)
						var unit = 1;
					else
						var unit = 2;
					var hh= Math.floor(obj[a]['departures'][b]['time']/100);
					if(hh>=24){
						hh-=24;
						date++;
					}
					var mm= obj[a]['departures'][b]['time']%100;
					var c= obj[a]['departures'][b]['code'].substring(1,5);
					if(c.charAt(0)=='0')
						c=c.substring(1,4);
					z={"stop":obj[a]['name'].split(",")[0],"dist":obj[a]['dist'],"bus":c,"date":date,"time":pad(hh,2)+":"+pad(mm,2),"laststop":dict[obj[a]['departures'][b]['code']].split(",")[0].split(" ")[0]};
					for(var i= $scope.arr.length-1;i>=0;i--)
						if( $scope.arr[i]['bus']==z['bus'] && $scope.arr[i]['laststop']==z['laststop']){
							if( $scope.arr[i]['dist']==z['dist']){
								break;
							}
							else if( $scope.arr[i]['dist'] > z['dist']){
								$scope.arr.splice(i,1);
							}
							else
								e=false;
					}
					if(e){
						$scope.arr.push(z);
					}

				}
			}
			function pad(num, size) {
				var s = num+"";
				while (s.length < size) s = "0" + s;
				return s;
			}
			delOld();
		}
		function delOld(){
			f= new Date();
			for(var a=$scope.arr.length-1; a>=0; a--){
				if( $scope.arr[a]['time']<1000)
					var unit = 1;
				else
					var unit = 2;
				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]);
				if(d < f){
					$scope.arr.splice(a,1);
				}
			}
		}
		load();
		var t=$interval(delOld,2000);
		var z=$interval(load,60000);
	}
);
