const mongoose = require('mongoose');
const moment = require('moment');
const filterData = require('./common/filterData');
const formatData = require('./common/formatData');
const prepareStatsData = require('./common/prepareStatsData');

const Timelog = mongoose.model('Timelog');
const Project = mongoose.model('Project');

exports.getMotivationData = async (req, res) => {
  /*
   We are subtracting here to have a buffer of extra week,
   because we show data for this month, but also for the last week
  */
  const setFirstDay = moment()
    .startOf('month')
    .subtract({ days: 14 });
  const setLastDay = moment().endOf('month');

  const data = await Timelog.find({
    author: req.user._id,
    started: {
      $gte: setFirstDay,
      $lte: setLastDay
    }
  });
  const lastSunday = moment().isoWeekday(0)._d;
  const lastMonday = moment().isoWeekday(-6)._d;
  const thisMonday = moment().isoWeekday(1)._d;
  const thisSunday = moment().isoWeekday(7)._d;

  const lastWeek = filterData(data, lastMonday, lastSunday);
  const thisWeek = filterData(data, thisMonday, thisSunday);

  const formattedLastWeek = formatData(lastWeek);
  const formattedThisWeek = formatData(thisWeek);

  res.send({
    lastWeek: formattedLastWeek,
    thisWeek: formattedThisWeek,

    dataSent: true
  });
};

exports.getData = async (req, res) => {
  const { start, end } = req.query;
  const startDate = `${start} 00:00:00`;
  const endDate = `${end} 23:59:59`;
  const data = await Timelog.find({
    author: req.user._id,
    started: {
      $gte: startDate,
      $lte: endDate
    }
  }).lean();

  const projects = await Project.find({ author: req.user._id }).lean();

  const formatted = formatData(data);
  const prepared = prepareStatsData(data, projects);

  res.send({
    data: formatted,
    dataSent: true,
    myData: data,
    prepared
  });
};

@@ -1297,16 +1297,188 @@
 %7D);%0A%7D;%0A%0A
+function filterByProperty(arr, prop) %7B%0A  const f = %5B%5D;%0A  return arr.filter(%0A    obj =%3E%0A      f.indexOf(obj%5Bprop%5D.toString()) === -1 && f.push(obj%5Bprop%5D.toString())%0A  );%0A%7D%0A%0A
 exports.
@@ -1848,35 +1848,350 @@
 nst 
-formatted = formatData(data
+timelogs = filterByProperty(data, 'task').map(timelog =%3E %7B%0A    const result = %7B ...timelog %7D;%0A    const seconds = data.reduce((accum, value) =%3E %7B%0A      if (timelog.task.toString() === value.task.toString()) %7B%0A        return accum + value.seconds;%0A      %7D%0A      return accum + 0;%0A    %7D, 0);%0A    result.seconds = seconds;%0A    return result;%0A  %7D
 );%0A 
@@ -2225,20 +2225,24 @@
 atsData(
-data
+timelogs
 , projec
@@ -2272,57 +2272,18 @@
 data
-: formatted,%0A    dataSent: true,%0A    myData: data
+Sent: true
 ,%0A  

remove unnecessary data to send