define(['jquery', 'dispatcher', 'model/trajectory', 'moment'], function($, Dispatcher, TrajectoryModel, moment){
	var _compute = function(drifterModels, hoursModel, daysModel, trackWay, trackMethod, dataset, depth, radius){
		var start, end; // start or end at nth-hour, integer
		if (trackWay == 'backward') {
			start = moment(hoursModel.max).diff(moment(daysModel.max), 'hours') - 1;
			end = start - moment(hoursModel.max).diff(moment(hoursModel.min), 'hours');
		} else if (trackWay == 'forward') {
			start = moment(hoursModel.min).diff(moment(daysModel.min), 'hours');
			end = start + moment(hoursModel.max).diff(moment(hoursModel.min), 'hours');
		}
		depth = depth ? parseInt(depth) : 1;
		radius = radius ? parseFloat(radius) : 0.16;
		var archive = moment(daysModel.min).format("YYYY") + '/' + moment(daysModel.min).format("YYYYMMDDHHmm");
		for(var i=0, dm; dm = drifterModels[i++];){
			(function(dm){
				var lat = dm.getLat(), lon = dm.getLon(), id = dm.getId();
				Dispatcher.dispatch({'action': 'update-drifter-status', 'data': {id: id, status: 'pending'}});
				$.ajax({
					// url: '/trajectories/',
					url: '/research/timcom/particle_tracking/flask/trajectories/',
					type: 'GET',
					data: {lat: lat, lon: lon, start: start, end: end, archive: archive, trackWay: trackWay, trackMethod: trackMethod, dataset: dataset, depth: depth, radius: radius},
					dataType: 'json',
					success: function(res){
						Dispatcher.dispatch({'action': 'add-trajectory', 'data': new TrajectoryModel(res.lats, res.lons, res.time, id, hoursModel, trackWay)});
						Dispatcher.dispatch({'action': 'update-drifter-status', 'data': {id: id, status: 'success'}});
					},
					error: function(err){
						console.info('trajectories fetch fail');
						Dispatcher.dispatch({'action': 'update-drifter-status', 'data': {id: id, status: 'fail', message: JSON.parse(err.responseText).message}});
					}
				});
			})(dm);
		}
	}

	var _clearTrajectories = function(){
		Dispatcher.dispatch({'action': 'clear-trajectories', 'data': {}});
		Dispatcher.dispatch({'action': 'update-all-drifters-status', 'data': {status: ''}});
	}

	var _downloadData = function(trajectoryModels){
		// var url = '/download/';
		var url = '/research/timcom/particle_tracking/flask/download/';
		var trajectories = [];
		for(var i=0, t; t = trajectoryModels[i++];){
			var path = t.getPath(), lats = [], lons = [], times = [];
			for(var j=0, p; p = path[j++];){
				lats.push(p.lat);
				lons.push(p.lon);
				times.push(p.humanTime)
			}
			trajectories.push({lats: lats, lons: lons, times: times});
		}
		fetch(url, {
			method: 'POST',
			body: JSON.stringify({data: trajectories})
		})
		.then(res => res.blob().then(blob => {
		    var a = document.createElement('a');
		    var url = window.URL.createObjectURL(blob);
		    var filename = 'output.zip';
		    a.href = url;
		    a.download = filename;
		    a.click();
		    window.URL.revokeObjectURL(url);
		}));
	}

	return {
		compute: _compute,
		clearTrajectories: _clearTrajectories,
		downloadData: _downloadData
	}
});