var module = angular.module('wfJournalUI', ['ngGrid','ui.bootstrap']);

module.directive('sliderDateRange', function($compile) {
	var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
	
	return {
		restrict: 'A',
		scope: {
			min   : '=',
			max   : '=',
			start : '=',
			end   : '=',
			updateFunction: '='
		},
		link: function(scope, elem, attrs) {
    		$(elem).dateRangeSlider({
    			valueLabels: "change",
    			delayOut: 1000,
    			"bounds" : {
					min: scope.min,
					max: scope.max
				},
				"defaultValues" : {
					min: scope.start,
					max: scope.end
				},
				"scales": [{
					first: function(value) {
						return value;
					},
					end: function(value) {
						return value;
					},
					next: function(value) {
						var next = new Date(value);
						return new Date(next.setMonth(value.getMonth() + 1));
					},
					label: function(value) {
						return months[value.getMonth()];
					},
					format:	function(tickContainer, tickStart, tickEnd) {
						tickContainer.addClass("myCustomClass");
					}
				}]
    		});
    		$(elem).bind("valuesChanged", function(e, data){
    			scope.updateFunction(data.values.min, data.values.max);
    		});
    	}
    }
});

function wfJournalCtrl($scope, $http, $sce) {
	
	commonInitialize($scope, $http, $sce);
	
	initSpinner();
	
	$scope.journal = [];
	
	$scope.currentProcId = '';
	
	$scope.family = getFamily();
	
	$scope.filterJournal = { filterText: '' };
		
	$scope.maxDate = new Date();
	$scope.minDate = new Date(2014, 0, 1);
	
	$scope.endDate = new Date();
	$scope.startDate = new Date();
	
	$scope.updateDates = function(start, end) {
		$scope.startDate = start;
		$scope.endDate = end;
		$scope.$apply();
		$scope.refresh();
	}
	
	// Set date range to [7 days before today, today] inclusive
	$scope.startDate.setDate($scope.endDate.getDate()-7);
	
	// Grid configuration
	$scope.gridWfJournal = { 
			data: 'journal',
			enableCellSelection: false,
			enableRowSelection: false,
			enableCellEditOnFocus: false,
			enablePaging: false,
			enableHighlighting: true,
			sortInfo: { fields: ['date'], directions: ['desc']},
			filterOptions: $scope.filterJournal,
			columnDefs: [{field: 'procId', displayName: 'Process ID'      , width: '15%', cellTemplate: '<div class="ngCellText"><a href="javascript:void(0)" ng-click="showProcess(row.getProperty(col.field))">{{row.getProperty(col.field)}}</a></div>'},
			             {field: 'name'  , displayName: 'Workflow name'   , width: '20%',},
			             {field: 'family', displayName: 'Workflow family' , width: '15%' },
			             {field: 'repo'  , displayName: 'Datasource'  },
			             {field: 'status', displayName: 'Status'          , width: '10%', cellTemplate: '<div class="ngCellText"><span class="label label-default" ng-class="{ \'label-success\': row.getProperty(col.field) == \'SUCCESS\', \'label-danger\': row.getProperty(col.field) == \'FAILURE\', \'label-info\': row.getProperty(col.field) == \'EXECUTING\'}">{{row.getProperty(col.field)}}</span></div>'},
			             {field: 'date'  , displayName: 'Date'            , width: '10%', cellTemplate: '<div class="ngCellText">{{ (row.getProperty("date") > 0 && row.getProperty("date") < 9999999999999) ? (row.getProperty("date") | date:"yyyy-MM-dd HH:mm:ss") : "not yet started" }}</div>'}
			            ]
	};
	
	$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.refresh = function() {
		$scope.showSpinner();
		var url = '';
		
		if ($scope.family) {
			url = 'wf_journal_byFamily.find?family=' + $scope.family;
		} else {
			url = 'wf_journal.range?start=' + $scope.formatDate($scope.startDate) + '&end=' + $scope.formatDate($scope.endDate);
		}
		$http.get(url).success(
			function(data) {
				$scope.journal = 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 - 280) + "px");
	}
	
	$scope.refresh();
	$scope.resizeMainElement(document.getElementById('wfJournalTable'));
	
	if (initProcId()) {
		$scope.showProcess(initProcId());
	}
}

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