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 _ = require('lodash');

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


router.post('/', authenticate, (req, res) => {

  var body = _.pick(req.body, tools.allfieldProjectWithId());
  // tools.mylogshow('PROJ INPUT', body);
  var project = new Project(body);

  // project.expiring_at = new Date(project.expiring_at);

  tools.mylog('ID :', project._id, project.descr, project.userId, req.user._id);

  if (!('descr' in req.body)) {
    return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
  }

  const check = tools.checkUserOk(project.userId, req.user._id, res);
  if (check.exit) return check.ret;

  tools.mylog('PROJECT POST :', project.descr, project._id);

  project.modified = false;
  if (!project.descr) {
    console.log('RECORD NON VALIDO !?', req.body)
  }

  project.save().then((writeresult) => {
    let idobj = writeresult._id;
    Project.findById(idobj)
      .then(async (record) => {

        await tools.sendNotificationToUser(record.userId, '[Progetto]: ' + record.descr, record.descr, '/todo/' + record._id, '', 'todo', [])

        res.send({ record: record._doc });

        /*
        tools.sendNotificationToUser(project.userId, 'Project: ' + record.descr, record.descr, '/project/' + project.category, '', 'project', [])
          .then(ris => {
            if (ris) {
              res.send({ record });
            } else {
              // already sent the error on calling sendNotificationToUser
            }
          })

         */
      })
  }).catch((e) => {
    console.log('ERRORE in PROJECT POST', e.message);
    res.status(400).send(e);
  });
});


router.patch('/:id', authenticate, (req, res) => {
  var id = req.params.id;

  // ------------- EXAMPLES: -----------------------
  // var mionome = req.query.name;  // Esempio miosito.com?name=pippo
  // const plainText = req. body.plainText;  //
  // ----------------------------------------------------


  var body = _.pick(req.body, tools.allfieldProject());

  tools.mylogshow('PATCH PROJECT: ', id);

  if (!ObjectID.isValid(id)) {
    tools.mylog('ERROR: id not VALID', id);
    return res.status(404).send();
  }

  // check if you are able to modify this project
  if (!Project.enabletoModify(String(req.user._id), id))
    return res.status(404).send();

  Project.findByIdAndUpdate(id, { $set: body }, { new: true }).then((project) => {
    tools.mylogshow(' PROJECT TO MODIFY: ', project.descr);
    if (!project) {
      return res.status(404).send();
    }

    if (project.userId !== String(req.user._id) && project.privacywrite === server_constants.Privacy.onlyme) {
      // I'm trying to write something not mine!
      return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
    }

    project.modified = false;

    // Recalculate
    return calcSingleProject('', project)
      .then(objout => {
        tools.mylog('PATCH ', project.descr, project._id, project.progressCalc);

        return Project.findById(id).then((projectris) => {
          // console.log('projectris progressCalc', projectris.progressCalc);
          res.send({ projectris });
        });
      });

  }).catch((e) => {
    tools.mylogserr('Error patch PROJECT: ', e);
    res.status(400).send();
  })
});


router.get('/', (req, res) => {
  tools.mylog('GET ALL PROJECTS: ');
  const idapp = req.query.idapp;

  return Project.getAllProjects('', idapp).then((objprojects) => {
    if (!!objprojects.arrproj)
      tools.mylog('projects', objprojects.arrproj.length);

    return objprojects
  }).then((objprojects) => {
    res.send({ projects: objprojects.arrproj });
  }).catch((e) => {
    console.log(e.message);
    res.status(400).send(e);
  });
});

router.get('/calc/:id/:actualphase', authenticate, (req, res) => {
  var id = req.params.id;
  var actualphase = parseInt(req.params.actualphase);

  return Todo.calculateTreeTodo(actualphase, '', id, false, id, false)
    .then((rec) => {
      return res.send({ rec });
    })
    .catch((err) => {
      res.status(400).send();
    });

})
;


router.get('/:userId', authenticate, (req, res) => {
  const userId = req.params.userId;
  const idapp = req.query.idapp;


  if (!ObjectID.isValid(userId)) {
    return res.status(404).send();
  }

  if (userId !== String(req.user._id)) {
    // I'm trying to write something not mine!
    return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
  }

  // Receive the Projects only for specific Users:
  return User.isUserVisuProjects(idapp, req.user.username).then((isresidente) => {
    // Extract all the projects of the userId only
    if (!isresidente)
      return res.send({ projects: [] });

    return Project.getAllProjects(userId, idapp).then((objprojects) => {
      if (!!objprojects.arrproj)
        tools.mylog('projects', objprojects.arrproj.length);

      return objprojects

    }).then((objprojects) => {

      res.send({ projects: objprojects.arrproj });

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

  })

});


/*
// USATO SOLO LE PRIME VOLTE! O A RICHIESTA!
async function calcProjects(userId, obj) {

  // let myarr = tools.jsonCopy(obj.arrproj);
  let myarr = [...obj.arrproj];

  if (myarr.length > 0) {
    let promiseChain = Promise.resolve();

    for (const rec of myarr) {
      promiseChain = promiseChain.then(() => {
        // Find the todos for this project
        // Calculate the Progression of the Project   // sum the progression
        return Todo.calculateTreeTodo(userId, rec._id)
      })
    }
    return promiseChain
  } else {
    return new Promise((resolve, reject) => {
      resolve()
    })
  }

}
*/

// USATO SOLO LE PRIME VOLTE! O A RICHIESTA!
async function calcSingleProject(userId, myproj) {

  return await Todo.calculateTreeTodo(myproj.actualphase, userId, myproj._id, false, myproj._id, false)

}

router.delete('/:id', authenticate, (req, res) => {
  var id = req.params.id;

  const hide = true;

  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }

  if (hide) {
    Project.findByIdAndUpdate(id, { $set: { deleted: true } }).then((project) => {
      if (!project) {
        return res.status(404).send();
      }
      res.send({ project });
    }).catch((e) => {
      res.status(400).send();
    });

  } else {

    Project.findByIdAndRemove(id).then((project) => {
      if (!project) {
        return res.status(404).send();
      }

      tools.mylog('DELETED ', project.descr, project._id);

      res.send({ project });
    }).catch((e) => {
      res.status(400).send();
    });
  }
});


module.exports = router;
