const fs = require("fs");
const path = require("path");
const uti = require("util");
const exec = uti.promisify(require("child_process").exec);

const Koa = require("koa");
const koaPug = require("koa-pug");
const koaRouter = require("koa-router");
const fetch = require("node-fetch");
const moment = require("moment-timezone");

const config = require("./config");
const util = require("../shared/util");

async function getRadioStatus() {
	try {
		let status = await fetch('http://radio.arav.home.arpa/status-json.xsl').then(r => r.json());
		return {
			server_start_iso8601: status.icestats.source.stream_start_iso8601,
			server_start_date: util.datetime(status.icestats.source.stream_start_iso8601, util.date_formats.post_date),
			song: `${status.icestats.source.artist} - ${status.icestats.source.title}`,
			listener_peak: status.icestats.source.listener_peak,
			listeners: status.icestats.source.listeners
		}
	} catch {
		return {
			server_start_iso8601: "n/a",
			server_start_date: "n/a",
			song: "n/a",
			listener_peak: "n/a",
			listeners: "n/a"
		}
	}
}

async function getLastPlayedSongs(count, tz) {
	try {
		const { stdout, _ } = await exec(`tail -n${count} /var/log/icecast/playlist.log | head -n-1 | cut -d"|" -f1,4`);
		let songs = stdout.trim().split("\n");
		for (let i = 0; i < songs.length; ++i) {
			let [t, s] = songs[i].split('|');
			t = moment(t, "DD/MMM/YYYY:HH:mm:ss ZZ").tz(tz).format("HH:mm");
			let song = s.split(' - ');
			songs[i] = { "start_time_local": t, "artist": song[0], "title": song[1] };
		}
		return songs;
	} catch {
		return [];
	}
}

function setRoutes() {
	return koaRouter().get('/', async ctx => {
		await ctx.render('index', {
			main_site: util.getServiceByHost(ctx.header.host),
			radio_status: await getRadioStatus(),
			last_songs: await getLastPlayedSongs(11, util.getClientTimezone(ctx))
		});
	})
	.get('/stats', async ctx => {
		ctx.body = await getRadioStatus();
	})
	.get('/lastsong', async ctx => {
		ctx.body = (await getLastPlayedSongs(2, util.getClientTimezone(ctx)))[0];
	});
}

const app = new Koa();
const pug = new koaPug({
	viewPath: path.join(__dirname, "views"),
	locals: {
		moment: util.datetime },
	app: app
});

app.proxy = true;
app
	.use(setRoutes().routes())
	.listen(config.port, config.host);
