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) {

  for (const admin of data.admins) {
    const myuser = await User.findOne({idapp, username: admin.username}).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;

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

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

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

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

  const ris = null;

});

module.exports = router;
