'use strict';

const Promise = require('bluebird');
const fetch = require('node-fetch');
const ms = require('ms');
const NodeCache = require('node-cache');
const query = require('./db');

fetch.Promise = Promise;

const responseCache = new NodeCache({ stdTTL: 30 });

if (process.env.ICECAST_STATUS_URL) {
  const fetchStreamStats = () => {
    console.log('Fetching Stream Stats');

    return 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 => query('INSERT INTO whrb_stats_v2(stats) VALUES($1)', [json.icestats]))
    .catch(err => console.error('Error fetching stream stats', err));
  };

  const intervalMs = ms(process.env.STATS_INTERVAL || '5m');
  const intervalMins = intervalMs / 60000;

  const now = new Date();
  const nextTime = new Date();
  const currentMinute = now.getMinutes();
  const nextMinute = (currentMinute + intervalMins) - (currentMinute % intervalMins);
  nextTime.setMinutes(nextMinute, 0, 0);

  const diff = nextTime - now;
  console.log(`Starting data fetch in ${diff / 1000} seconds`);
  setTimeout(() => {
    fetchStreamStats();
    setInterval(fetchStreamStats, intervalMs);
  }, diff);
}

// middleware for fetching stream stats
module.exports = (req, res) => {
  const cached = responseCache.get('stats');
  if (cached) {
    console.log('returning cached value');
    return res.json(cached);
  }

  return query('SELECT timestamp, stats FROM whrb_stats_v2 WHERE timestamp > current_date - interval \'8 days\' ORDER BY timestamp ASC')
  .spread((rows, result, error) => {
    if (error) {
      return Promise.reject(error);
    }

    const results = {
      Total: [],
    };

    rows.forEach((entry) => {
      let total = 0;

      if (!Array.isArray(entry.stats.source)) {
        return;
      }

      entry.stats.source.forEach((statsRecord) => {
        total += statsRecord.listeners;
        if (!Array.isArray(results[statsRecord.server_name])) {
          results[statsRecord.server_name] = [];
        }

        const item = { timestamp: entry.timestamp, listeners: statsRecord.listeners };
        results[statsRecord.server_name].push(item);
      });

      results.Total.push({ timestamp: entry.timestamp, listeners: total });
    });

    responseCache.set('stats', results);
    return res.json(results);
  })
  .catch((err) => {
    console.error(err);
    res.status(500).json({ message: 'error getting stream stats' });
  });
};

@@ -1,8 +1,26 @@
+/* Deprecated */%0A%0A
 'use str
@@ -96,24 +96,27 @@
 de-fetch');%0A
+// 
 const ms = r
@@ -282,16 +282,19 @@
 30 %7D);%0A%0A
+// 
 if (proc
@@ -323,16 +323,19 @@
 _URL) %7B%0A
+// 
   const 
@@ -357,24 +357,27 @@
 s = () =%3E %7B%0A
+// 
     console.
@@ -407,20 +407,23 @@
 ats');%0A%0A
+//
     
+ 
 return f
@@ -459,16 +459,19 @@
 US_URL)%0A
+// 
     .the
@@ -479,24 +479,27 @@
 ((res) =%3E %7B%0A
+// 
       if (!r
@@ -503,24 +503,27 @@
 (!res.ok) %7B%0A
+// 
         retu
@@ -614,16 +614,19 @@
 us%7D%60));%0A
+// 
       %7D%0A
@@ -626,22 +626,25 @@
      %7D%0A%0A
+//
       
+ 
 return r
@@ -658,15 +658,21 @@
 ();%0A
+// 
     %7D)%0A
+// 
     
@@ -756,16 +756,19 @@
 tats%5D))%0A
+// 
     .cat
@@ -829,24 +829,30 @@
  err));%0A
+// 
   %7D;%0A%0A
+//
   
+ 
 const in
@@ -902,16 +902,19 @@
  '5m');%0A
+// 
   const 
@@ -949,16 +949,19 @@
 60000;%0A%0A
+// 
   const 
@@ -970,32 +970,35 @@
 w = new Date();%0A
+// 
   const nextTime
@@ -1008,24 +1008,27 @@
 new Date();%0A
+// 
   const curr
@@ -1057,18 +1057,21 @@
 utes();%0A
+//
   
+ 
 const ne
@@ -1146,16 +1146,19 @@
 lMins);%0A
+// 
   nextTi
@@ -1191,16 +1191,19 @@
 0, 0);%0A%0A
+// 
   const 
@@ -1225,16 +1225,19 @@
  - now;%0A
+// 
   consol
@@ -1292,16 +1292,19 @@
 onds%60);%0A
+// 
   setTim
@@ -1316,20 +1316,23 @@
 () =%3E %7B%0A
+//
     
+ 
 fetchStr
@@ -1343,16 +1343,19 @@
 tats();%0A
+// 
     setI
@@ -1393,16 +1393,19 @@
 valMs);%0A
+// 
   %7D, dif
@@ -1408,16 +1408,19 @@
  diff);%0A
+// 
 %7D%0A%0A// mi

Remove db write code for stream stats.