const got = require('got');

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

// Get trips for stop.
async function getTrips(id) {
	
	const now = time.getSeconds(); // TODO: IMPLEMENT REALTIME
	const data = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
	
	if (!data) throw new Error("Provider 'Elron' is not returning data");
	if (data.text) throw new Error(data.text);
	
	const trips = [];
	
	for (const trip of data) if (!trip.tegelik_aeg) trips.push({
		time: time.toSeconds(trip.plaaniline_aeg),
		name: trip.reis,
		destination: trip.liin,
		type: 'train',
		live: false,
		provider: 'elron'
	});
	
	return trips.slice(0, 15);
	
};

// Get route by id.
async function getRoute(id) {
	
	return cache.use('elron-trips', id, async () => {
		
		const data = JSON.parse((await got(`http://elron.ee/api/v1/trip?id=${encodeURIComponent(id)}`)).body).data;
	
		if (!data) throw new Error("Provider 'Elron' is not returning data");
		if (data.text) throw new Error(data.text);
		
		return {
			destination: `${data[0].peatus} - ${data[data.length - 1].peatus}`,
			stops: data.map((trip) => ({
				id: trip.peatus,
				name: trip.peatus,
				type: 'train'
			}))
		};
		
	});
	
}

module.exports = {
	getTrips,
	getRoute
};

@@ -199,36 +199,8 @@
 s();
- // TODO: IMPLEMENT REALTIME
 %0A%09co
@@ -481,25 +481,49 @@
 if (
-!trip.tegelik_aeg
+time.toSeconds(trip.plaaniline_aeg) %3E now
 ) tr
@@ -578,16 +578,72 @@
 e_aeg),%0A
+%09%09countdown: time.toSeconds(trip.plaaniline_aeg) - now,%0A
 %09%09name: 

Fix Elron provider (api)