import moment from 'moment';
import { dbAdapter } from '../../../models';

export default class StatsController {
  static async stats(ctx) {
    const MAX_STATS_PERIOD = 365 * 2; // 2 years
    const MIN_START_DATE = moment().subtract(MAX_STATS_PERIOD, 'days').format('YYYY-MM-DD');
    const DEFAULT_END_DATE = moment().format('YYYY-MM-DD');

    const data = ctx.request.query.data || 'users';
    const start_date = ctx.request.query.start_date || MIN_START_DATE;
    const end_date = ctx.request.query.end_date || DEFAULT_END_DATE;

    let start = moment(start_date);
    let end = moment(end_date);

    // adjust if the end period is in future
    if (moment().isBefore(end)) {
      end = moment();
    }

    // adjust if start is before MIN_START_DATE
    if (start.isBefore(MIN_START_DATE)) {
      start = moment(MIN_START_DATE);
    }

    // fail if end < start
    if (end.isBefore(start)) {
      throw new Error(`ERROR: end date is before the start date`);
    }

    if (end.diff(start, 'days') > MAX_STATS_PERIOD) {
      throw new Error(`ERROR: the requested period is too long`);
    }

    const stats_res = await dbAdapter.getStats(data, start.format(`YYYY-MM-DD`), end.format(`YYYY-MM-DD`));

    if (!stats_res) {
      ctx.status = 404;
      ctx.body = { stats: 'Not found' };
    }

    ctx.body = { stats: stats_res };
  }
}

@@ -206,24 +206,98 @@
 START_DATE =
+ moment('20150504');  // FreeFeed launched%0A%0A    const DEFAULT_START_DATE =
  moment().su
@@ -464,29 +464,29 @@
 users';%0A    
-const
+let %7B
  start_date 
@@ -480,24 +480,36 @@
 %7B start_date
+, end_date %7D
  = ctx.reque
@@ -520,78 +520,215 @@
 uery
-.start_date %7C%7C MIN_START_DATE;%0A    const end_date = ctx.request.query.
+;%0A%0A    if (!start_date) %7B%0A      if (end_date) %7B%0A        start_date = moment(end_date).subtract(MAX_STATS_PERIOD, 'days').format('YYYY-MM-DD');%0A      %7D else %7B%0A        start_date = DEFAULT_START_DATE;%0A        
 end_
@@ -732,18 +732,17 @@
 nd_date 
-%7C%7C
+=
  DEFAULT
@@ -751,16 +751,146 @@
 ND_DATE;
+%0A      %7D%0A    %7D%0A%0A    if (!end_date) %7B%0A      end_date = moment(start_date).add(MAX_STATS_PERIOD, 'days').format('YYYY-MM-DD');%0A    %7D
 %0A%0A    le
@@ -1191,24 +1191,153 @@
 TE);%0A    %7D%0A%0A
+    // adjust if end is before MIN_START_DATE%0A    if (end.isBefore(MIN_START_DATE)) %7B%0A      end = moment(MIN_START_DATE);%0A    %7D%0A%0A
     // fail 

Make stats older than 2 year accessible