'use strict';

const fetch = require('node-fetch');
const Promise = require('bluebird');
const _ = require('lodash');
const ms = require('ms');

fetch.Promise = Promise;

const db = require('./db');

if (process.env.ICECAST_STATUS_URL) {
  const fetchStreamStats = () => fetch(process.env.ICECAST_STATUS_URL)
  .then(res => {
    if (!res.ok) {
      return Promise.reject(new Error(`Could not fetch stream status. Response code ${res.status}`));
    }

    return res.json();
  })
  .then(json => _.get(json, 'icestats.source'))
  .map(source => {
    if (source) {
      return db.query(
        'INSERT INTO whrb_stats(server_name, server_type, listeners) VALUES($1, $2, $3)',
        [source.server_name, source.server_type, source.listeners]
      );
    }

    return null;
  })
  .catch(err => console.error('Error fetching stream stats', err));

  // set up periodic fetching of stream stats;
  fetchStreamStats();
  setInterval(fetchStreamStats, ms(process.env.STATS_INTERVAL || '5m'));
}

// middleware for fetching stream stats
module.exports = (req, res) => {
  db.query('SELECT server_name, server_type, listeners, timestamp FROM whrb_stats ORDER BY timestamp ASC', (err, result) => {
    if (err) {
      res.status(500).json(err);
    }

    const results = {};
    result.rows.forEach(entry => {
      if (!results.hasOwnProperty(entry.server_name)) {
        results[entry.server_name] = [];
      }
      results[entry.server_name].push(entry);
    });

    res.json(results);
  });
};

@@ -136,16 +136,50 @@
 e('ms');
+%0Aconst moment = require('moment');
 %0A%0Afetch.
@@ -1304,16 +1304,39 @@
 s = %7B%7D;%0A
+    const total = %7B%7D;%0A%0A
     resu
@@ -1517,16 +1517,353 @@
 y);%0A
-    %7D);%0A
+%0A      const time = moment(entry.timestamp).format('YYYY-MM-DD HH:mm:ss');%0A      if (!total.hasOwnProperty(time)) %7B%0A        total%5Btime%5D = %7B%0A          timestamp: entry.timestamp,%0A          listeners: entry.listeners,%0A        %7D;%0A      %7D else %7B%0A        total%5Btime%5D.listeners += entry.listeners;%0A      %7D%0A    %7D);%0A%0A    results.Total = _.values(total);
 %0A   

Add total listeners.