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');

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

const { User } = require('../models/user');
const { MyGroup } = require('../models/mygroup');

const _ = require('lodash');

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

async function getGroupRecAdminsInfo(idapp, data) {

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

  return data;
}

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

  try {

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

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

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

    /*
    if (data.mycircuits) {
      for (let i = 0; i < data.mycircuits.length; i++) {
        const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
        data.mycircuits[i] = mycirc;
      }
    }
    */

    if (data.mycircuits) {
      for (let i = 0; i < data.mycircuits.length; i++) {
        const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
        if (mycirc)
          data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
      }
    }

    let cities = [];
    if (data) {
      cities = await MyGroup.extractCitiesName(idapp, data._id);
      if (cities && cities.length > 0) {
        cities = cities[0].mycities;
      }
    }

    data = await getGroupRecAdminsInfo(idapp, data);

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

    const users_in_group = await User.find(
      {
        idapp,
        'profile.mygroups': {
          $elemMatch: { groupname: { $eq: groupname } },
        },
      },
      whatshowUsers,
    ).lean();

    res.send({ mygroup: data, users_in_group, cities });

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

  const ris = null;

});

module.exports = router;
