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

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

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


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

var { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate');

var mongoose = require('mongoose').set('debug', false);
const Subscription = mongoose.model('subscribers');

const _ = require('lodash');
const { MyBacheca } = require('../models/mybacheca');
var { User } = require('../models/user');
const { Reaction } = require('../models/reaction');

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

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

//GET orders
router.post('/page', authenticate_noerror, function (req, res, next) {

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

  try {
    let table = req.body.table;
    let id = req.body.id;
    let idapp = req.body.idapp;

    let username = ''
    if (req.user)
      username = req.user.username ? req.user.username : '';

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

    let mytable = null;
    if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) {
      mytable = globalTables.getTableByTableName(table);
    }


    if (mytable) {

      return mytable.getMyRecById(idapp, id).
        then(async (ris) => {

          // Se è un record singolo di tipo Reaction, 
          // allora gli devo passare anche le liste degli utenti : 
          if (globalTables.isTableReaction(table)) {
            // ...
            // const myreaction = await Reaction.find({idapp, idrec: id}).lean();
            // ris.myreaction = myreaction;

          };

          if (ris) {
            res.send(ris);

          } else {
            res.status(400).send();
          }
        }).catch((e) => {
          console.error('Err', e);
          res.status(400).send(e);
        })

    }
  } catch (e) {
    console.error('/page', e);
  }

  return null;

});

module.exports = router;
