const got = require('got');
const time = require('../utils/time.js');

/* Stops */

// Get trips for stop.
async function getStopDepartures(id) {
	const now = time.getSeconds();
	const departures = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`, { timeout: 1000, retry: 1 })).body).data;
	if (!departures) throw new Error('Invalid response');
	
	return departures.filter((departure) => !departure.tegelik_aeg).map((departure) => ({
		tripId: departure.reis,
		routeId: departure.reis,
		name: departure.reis,
		description: departure.liin,
		type: 'train',
		time: time.toSeconds(departure.plaaniline_aeg),
		countdown: time.toSeconds(departure.plaaniline_aeg) - now,
		live: false,
		provider: 'elron'
	})).filter((departure) => now - departure.time < 600).slice(0, 15);
}

/* Routes */

// Get route by id.
async function getRoute(id) {
	const stops = JSON.parse((await got(`http://elron.ee/api/v1/trip?id=${id}`, { timeout: 600, retry: 1 })).body).data;
	if (!stops) throw new Error('Invalid response');
	if (!stops.length) return null;
	
	return {
		id,
		name: stops[0].peatus,
		description: '',
		type: 'train'
	};
}

// Get directions for route.
async function getRouteDirections(id) {
	const stops = JSON.parse((await got(`http://elron.ee/api/v1/trip?id=${id}`, { timeout: 600, retry: 1 })).body).data;
	if (!stops) throw new Error('Invalid response');
	
	return [
		{
			name: stops[0].peatus + ' - ' + stops[stops.length - 1].peatus,
			stops: stops.map((stop) => ({
				id: stop.peatus,
				name: stop.peatus,
				description: '',
				type: 'train'
			}))
		}
	];
}

module.exports = {
	getStopDepartures,
	getRoute,
	getRouteDirections
};

@@ -21,16 +21,92 @@
 'got');%0A
+const db = require('../db.js');%0Aconst cache = require('../utils/cache.js');%0A
 const ti
@@ -1459,32 +1459,155 @@
 lid response');%0A
+%09const coords = await cache.use('elron', 'coords', () =%3E db.query(%22SELECT id, lat, lng FROM stops WHERE type = 'train'%22));%0A
 %09%0A%09return %5B%0A%09%09%7B%0A
@@ -1703,19 +1703,112 @@
 top) =%3E 
-(
+%7B%0A%09%09%09%09const %7B lat, lng %7D = coords.find((coord) =%3E coord.id === stop.peatus);%0A%09%09%09%09%0A%09%09%09%09return 
 %7B%0A
+%09
 %09%09%09%09id: 
@@ -1816,24 +1816,25 @@
 top.peatus,%0A
+%09
 %09%09%09%09name: st
@@ -1848,16 +1848,17 @@
 us,%0A%09%09%09%09
+%09
 descript
@@ -1870,16 +1870,17 @@
 '',%0A%09%09%09%09
+%09
 type: 't
@@ -1888,14 +1888,40 @@
 ain'
+,
 %0A%09%09%09
+%09%09lat,%0A%09%09%09%09%09lng%0A%09%09%09%09%7D;%0A%09%09%09
 %7D
-)
 )%0A%09%09

Fix error when stop opened from train route view (api)