var module = angular.module('wfTimelineUI', ['ngGrid']);

function wfTimelineCtrl($scope, $http, $sce, $filter) {
	
	commonInitialize($scope, $http, $sce);
	
	initSpinner();
	
	// Set date range to [3 days before today, today] inclusive
	$scope.endDate = new Date();
	$scope.startDate = new Date();
	$scope.startDate.setDate($scope.endDate.getDate()-3);
	
	$scope.data= [];
	$scope.timeline = new links.Timeline(document.getElementById('divTimeline'));		
	$scope.timelineData = [];
	$scope.currentLog = [];
	$scope.currentLogTitle = '';
	
	$scope.formatDate = function(date) {
		var year = date.getFullYear();
		var month = ("00" + (date.getMonth() + 1)).slice(-2);
		var day = ("00" + date.getDate()).slice(-2);
		return year + '-' + month + '-' + day;
	}
	
	$scope.gridLogDetails = { 
			data: 'currentLog',
			enableCellSelection: false,
			enableRowSelection: false,
			enableCellEditOnFocus: false,
			enablePaging: false,
			sortInfo: { fields: ['name'], directions: ['asc'] },
			columnDefs: [{field: 'name', displayName: 'Key', width: '20%' },
			             {field: 'value', displayName: 'Value' }]
	};
	
	$scope.registerListener = function() {
		links.events.addListener($scope.timeline, 'select', function() {
	        var sel = $scope.timeline.getSelection();
	        if (sel.length) {
	            if (sel[0].row != undefined) {
	                var row = sel[0].row;
	                $scope.showProcess($scope.timelineData[row].procId);
	            }
	        }
	    });

        // attach an event listener using the links events handler
		links.events.addListener($scope.timeline, 'rangechanged', function(properties) {
			if ($scope.formatDate($scope.endDate) != $scope.formatDate(properties.end) || $scope.formatDate($scope.startDate) != $scope.formatDate(properties.start)) {
				$scope.endDate = properties.end;
				$scope.startDate = properties.start;
				$scope.refresh();
			}
		});
	}
		
	$scope.refresh = function() {
		$scope.showSpinner();
		$http.get('wf_journal.range?start=' + $scope.formatDate($scope.startDate) + '&end=' + $scope.formatDate($scope.endDate))
        .success(
            function(data) {
            	$scope.data = data;
                $scope.drawVisualization($scope.data);
                $scope.hideSpinner();
            }
        ).error(
            function() {
            	$scope.showError('Something really bad must have happened to our fellow hamster..');
            	$scope.hideSpinner();
            }
        );
	}
	
	$scope.resizeMainElement = function(elem) {
		var height = 0;
		var body = window.document.body;
		if (window.innerHeight) {
			height = window.innerHeight;
		} else if (body.parentElement.clientHeight) {
			height = body.parentElement.clientHeight;
		} else if (body && body.clientHeight) {
			height = body.clientHeight;
		}
		elem.style.height = ((height - elem.offsetTop - 160) + "px");
	}
	
	
	$scope.drawVisualization = function(entries) {
		$scope.timelineData = [];

		angular.forEach(entries, function(value, key) {
			var clazz = 'text-success';
			if (value.status == 'FAILURE') {
				clazz = 'text-danger';
			}
			
			var s = "";
			if (value.repo) {
				s += value.repo + " (" + value.name + ")";
			} else {
				var s = value.name;
			}
			
			var prettyDate = "not yet started";
			if (value.date > 0 && value.date < 9999999999999) { // sabato 20 novembre 2286 17.46.39 GMT
				prettyDate = $filter('date')(new Date(value.date),'yyyy-MM-dd HH:mm:ss');
			}
						
			$scope.timelineData.push({
				'title': value.name + " (" + prettyDate + ")",
				'procId': value.procId,
                'start': new Date(value.date),
                'content': s,
                'className': clazz
            });
		});
		
		$scope.timeline = new links.Timeline(document.getElementById('divTimeline'));
		$scope.registerListener();
		var opts = {'width': '100%', 
					'height': '99%', 
					'style': 'dot',
					'zoomMin': 1000000,
					'zoomMax': 1314000000, // a half month
					'start': $scope.startDate,
					'end': $scope.endDate};
		$scope.timeline.draw($filter('filter')($scope.timelineData, $scope.filterText), opts);
    }
	

	$scope.refresh();
	//$scope.timeline.setScale(links.Timeline.StepDate.SCALE.DAY, 1);
	$scope.resizeMainElement(document.getElementById('divTimeline'));
	
}

window.onresize = function() {
	var elem = document.getElementById('divTimeline');
    angular.element(elem).scope().resizeMainElement(elem);
    angular.element(elem).scope().timeline.redraw();
};