angular.module('cs.services.util', []).factory('csUtils', function(){
	var util = function(){
		this.convertToYMDHMS = function(period){
			var time = [];
			period = Math.floor(period / 1000);
			if (period < 60){
				time.push(period);
			} else {
				time.push(period % 60);
				period = Math.floor(period / 60);
				if (period < 60){
					time.push(period);
				} else {
					time.push(period % 60)
					period = Math.floor(period / 60);
					if (period < 24){
						time.push(period);
					} else {
						time.push(period % 24);
						period = Math.floor(period / 24);
						if (period < 365){
							time.push(period);
						} else {
							time.push(period % 365);
							time.push(Math.floor(period / 365));
						}
					}
				}
			}
			outTime = '';
			for (var i = 0; i < time.length - 1; i++){
				if (time[i] < 10){
					outTime = ':' + '0' + time[i] + outTime;
				} else {
					outTime = ':' + time[i] + outTime;
				}
			}
			if (time[time.length - 1] < 10){
				outTime = '0' + time[time.length - 1] + outTime;
			} else {
				outTime = time[time.length - 1] + outTime;
			}
			return outTime;
		}
		
		this.convertToReadableDate = function (miliTime){
	    	if (isNaN(miliTime))
	    		return 'cannot calculate time';
	    	
	    	
	    	var result = '';
			var seconds = miliTime/1000; 
			var minutes = seconds/60; 
			var hours = minutes/60; 
			
			if (minutes < 60){
				minutes = Math.round(minutes);
				result = minutes + ' minutes';
			}
			
			else {
				if (hours > 24 ){
					var days = Math.round(hours/24);
					result = days + ' days';
					
				}
					
				else{
					hours = Math.round(hours)
					result = hours + ' hours';
				}
			}

			
			return result;
			
		}
		
		this.updateNode = function(d, parentData){
			if (d && d.name !== 'Customer' && d.name !== 'Customer ID' && d.name !== 'Anonymous ID') {
				if (parentData.node){
					parentData.node.isSelected = false;
				}
				d.isSelected = true;
				parentData.node = d;
				parentData.timeStarted = d.subheading;
				if (d.type === 'Service') {
					parentData.id = d.service_id;
					parentData.type = d.service_type;
					parentData.taskAddable = true;
					parentData.stateAddable = true;
				} else if (d.type === 'State') {
					parentData.id = d.state_id;
					parentData.type = d.state_type;
					parentData.taskAddable = true;
					parentData.stateAddable = false;
				} else if (d.type === 'Task') {
					parentData.id = d.task_id;
					parentData.type = d.task_type;
					parentData.taskAddable = false;
					parentData.stateAddable = false;
				}
				if (d.completed) {
					parentData.completed = true;
					parentData.timeCompleted = d.completed.timestamp;
				} else {
					parentData.completed = false;
					parentData.timeCompleted = '';
				}
			}
		}
	}
	return new util();
});