const express = require('express');
const router = express.Router();

const tools = require('../tools/general');

const server_constants = require('../tools/server_constants');

const { authenticate } = require('../middleware/authenticate');

// var mongoose = require('mongoose').set('debug', false)

const { Project } = require('../models/project');
const { Todo } = require('../models/todo');
const { User } = require('../models/user');

const shared_consts = require('../tools/shared_nodejs');

const Hours = require('../models/hours');

const _ = require('lodash');

const { ObjectID } = require('mongodb');

router.post('/load', authenticate, async (req, res) => {
  let date_start = req.body.date_start;
  const date_end = req.body.date_end;
  const filter = req.body.filter;
  const idapp = req.body.idapp;

  // tools.mylog('GET REPORT : ');

  // Ottieni la reportistica
  // dei progetti
  // degli utenti Residenti
  // di tutta la settimana

  try {
    // Ottieni la lista dei Residenti
    const listaResidenti = await User.getUsersResidenti(idapp);

    // Extract all the projects of the userId only
    const objprojects = await Project.getAllProjects('', idapp);

    const arrhour = {};

    // date_start = '2021-03-04T01:37:47.969Z';

    // let mydatets = tools.dateToEpoch(date_start)
    // let mydate = new Date(tools.getstrDateYYYY_MM_DD(new Date(date_start)));
    let mydate = new Date(date_start);
    let mydatestr = mydate.toDateString();
    let mydatets = tools.dateToEpoch(mydatestr) + (new Date().getTimezoneOffset() * 60 * 1000);
    mydate = new Date(mydatets);
    let mydateyyymmdd = tools.getstrUTCDateYYYY_MM_DD(tools.AddDate(new Date(mydatestr), 1));

      let mydatets_end = tools.dateToEpoch(date_end);

    for (const myuser of listaResidenti) {
      arrhour[myuser.username] = [];
    }

    let totalacchours = [];
    for (const myuser of listaResidenti) {
      totalacchours[myuser.username] = 0;
    }

    let rectotal = {};


    while (mydatets <= mydatets_end) {
      // console.log('mydatets', mydatets, 'mydate', mydate);
      for (const myuser of listaResidenti) {
        // for (const myproj of objprojects.arrproj) {
        //let myhours = await Hours.getHoursByIdCat(idapp, myuser._id, myproj._id, date_start, date_end);
        let rechours = await Hours.getHoursByDate(idapp, myuser._id, mydate);
        let ressum = await Hours.getTotalHoursByDate(idapp, myuser.id, mydate);

        if (tools.isMondayDate(mydate)) {
          totalacchours[myuser.username] = 0;
        }

        if ((ressum > 0) || ((tools.isSundayDate(mydate)) && totalacchours[myuser.username] > 0)) {
          totalacchours[myuser.username] = totalacchours[myuser.username] + ressum;
          rectotal = {
            totalhours: ressum,
            totalacchours: 0,
            date: mydateyyymmdd,
          }

          if (tools.isSunday(mydatets)) {
            rectotal.totalacchours = totalacchours[myuser.username];
          }

          if (tools.isBitActive(filter, shared_consts.REPORT_FILT_RESP)) {
            rectotal.resp = '';
            rectotal.viceResp = '';
          }

          arrhour[myuser.username].push(rectotal);
          if (tools.isBitActive(filter, shared_consts.REPORT_FILT_ATTIVITA)) {
            for (const rec of rechours) {
              let myproj = await Project.findProjectByUserId('', rec.todoId);
              let colors = {
                themebgcolor: '',
                themecolor: ''
              }
              if (!myproj) {
                const mytodo = await Todo.findOne({ _id: rec.todoId });
                if (!!mytodo) {
                  colors.themebgcolor = mytodo.themebgcolor;
                  colors.themecolor = mytodo.themecolor;
                  myproj = await Project.findProjectByUserId('', mytodo.category);
                  if (!colors.themebgcolor && myproj) {
                    colors.themebgcolor = myproj.themebgcolor;
                    colors.themecolor = myproj.themecolor;
                  }
                }
                // E' un Todo, trova il proj
              } else {
                colors.themebgcolor = myproj.themebgcolor;
                colors.themecolor = myproj.themecolor;
              }
              if (!colors.themebgcolor || colors.themebgcolor === 'white') {
                if (myproj) {
                  colors = await Project.findColorsByProject(myproj._id);
                }
              }
              if (myproj) {
                const myrec = {
                  title: rec.hours + 'h - ' + myproj.descr,
                  details: myproj.longdescr,
                  date: tools.getstrDateYYYY_MM_DD(mydate),
                  bgcolor: colors.themebgcolor,
                  color: colors.themecolor
                }
                arrhour[myuser.username].push(myrec);
              }
            }
          }
        }
        // }
      }

      // console.log('mydatestr', mydatestr, 'mydateyyymmdd', mydateyyymmdd)
      // if (!!rectotal)
      //   console.log('TOT', rectotal.totalacchours);

      mydatets += 86400000;
      mydate = tools.AddDate(mydate, 1);
      mydatestr = mydate.toDateString();
      mydateyyymmdd = tools.getstrUTCDateYYYY_MM_DD(tools.AddDate(new Date(mydatestr), 1));
    }

    return res.send({ listaResidenti, arrhour });


  } catch (e) {
    console.log(e.message);
    res.status(400).send(e);
  }

});

module.exports = router;
