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

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

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

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

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

const mongoose = require('mongoose').set('debug', false);

const { User } = require('../models/user');
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');

const _ = require('lodash');

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

async function getCircuitRecAdminsInfo(idapp, data) {

  try {
    if (data && data.admins) {
      for (const admin of data.admins) {
        const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
        if (myuser && myuser.profile)
          admin.profile = { img: myuser.profile.img };
      }
    }
  } catch (e) {
    console.error(e);
    return data;
  }

  return data;
}

router.post('/load', authenticate, async (req, res) => {
  const idapp = req.body.idapp;
  const path = req.body.path;
  const usernameOrig = req.user.username;

  try {

    const { SendNotif } = require('../models/sendnotif');
    const { Movement } = require('../models/movement');

    // Check if ìs a Notif to read
    const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
    const lastdr = req.body['lastdr'] ? req.body['lastdr'] : '';
    SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);

    const whatshow = Circuit.getWhatToShow(idapp, req.user.username);
    let data = await Circuit.findOne({ idapp, path }, whatshow).lean();

    const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);

    /*let users_in_circuit = [];

    if (data) {
      users_in_circuit = await User.find(
          {
            idapp,
            'profile.mycircuits': {
              $elemMatch: {circuitname: {$eq: data.name}},
            },
          },
          whatshowUsers,
      ).lean();
    }
     */

    const users_in_circuit = await Circuit.getUsersSingleCircuit(idapp, req.user.username, data.name, data._id);

    data = await getCircuitRecAdminsInfo(idapp, data);

    if (data) {
      data.movements = await Movement.getMovsByCircuitId(idapp, usernameOrig, data._id);
    }

    if (data) {
      data.account = await Account.getAccountByUsernameAndCircuitId(idapp, '', data._id, false, false, '', data.path);
    }

    const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(req.user.username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER);
    /// E' QUIIII !!!!
    const useraccounts = await Account.getUserAccounts(idapp, req.user.username);

    await User.setLastCircuitOpened(idapp, req.user.username, path);

    res.send({ circuit: data, users_in_circuit, arrrecnotif, useraccounts });

  } catch (e) {
    console.error('Error in Circuits', e);
    return res.status(400).send(e);
  }

  const ris = null;

});

module.exports = router;
