const express = require("express");
const path = require("path");

// Classes
const Towns = require("../models/Towns.js");
const Notifications = require("../models/Notifications.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/*

*/
router.get("/changeowner/:alias",checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {get} /towns/ownershipr/:alias
   * @apiName Change owner of a town mayorId
   * @apiGroup Pagans
   * @param {string} alias an alias that will become owner of a town
   * @apiSuccess (200) {object} {ref:"towns",msg:"ownerchangesuccess",data: { alias } }
   * @apiError (404)  {object}  {ref:"towns",msg:"aliasnotallow",data: { alias} }
   *
   **/
  res.send(Towns.changeowner(req.params.alias, req.session.header.xalias));
});

//=======================================================================================
router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {get} /pagans/person:alias
   * @apiName Is register check xalias and xhash
   * @apiGroup Pagans
   * @apiUse apxHeader
   * @param {string} alias  that exist
   * @param {string} tribeId that exist with a person alias
   * @apiSuccess (200) {ref:"pagans",msg:"personexist",data: { person } }
   * @apiError (404)  {ref:"pagans",msg:"persondoesnotexist",data: { person } }
   *
   * @todo check accessright  for req.session.header.xalias to see if jhe can get person data
   * if req.param.alias ==  req.session.header.xalias  => Owner
   * else need accessright to on person  set at R
   * */
  res.send(Pagans.getperson(req.params.alias, req.session.header.xtribe));
});

router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {get} /pagans/isauth
   * @apiName Is register check xalias and xhash
   * @apiGroup Pagans
   * @apiUse apxHeader
   *
   * @apiError (400) {object} status missingheaders / xalias does not exist / signaturefailled
   * @apiError (401) {object} alias anonymous (not authenticated)
   * @apiError (404) {string} tribe does not exist
   *
   * @apiSuccess (200) {object} data contains indexfile requested
   *
   */
  res.send({
    status: 200,
    ref: "headers",
    msg: "authenticated",
    data: {
      xalias: req.session.header.xalias,
    },
  });
});
router.post("/", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {post} /pagans
   * @apiName Is register check xalias and xhash
   * @apiGroup Pagans
   * @apiUse apxHeader
   *
   * Create a pagan account from alias, publickey, if trusted recovery =>
   *  Create a person in xtribe/person/xalias.json with profil.auth={email,privatekey, passphrase}
   * Middleware isAuthenticated check that:
   *  - xhash is well signed from private key linked to the publickey of alias
   *  - check that alias does not already exist (if yes then verifiedsigne would be false)
   * Need to wait next block chain to be sure that alias is register in the blokchain
   */
  console.log("pass ici", req.body);
  const feedback = { alias: req.body.alias, publickey: req.body.publickey };
  const newpagan = Pagans.create(req.body.alias, req.body.publickey);
  if (newpagan.status == 200) {
    if (req.body.email) {
      feedback.withemail = true;
      feedback.email = req.body.email;
      feedback.privatekey = req.body.privatekey;
      feedback.passphrase = req.body.passphrase;
      Notifications.send({
        type: "email",
        from: "",
        dest: [req.body.email],
        tpl: "registeremail",
        tribe: req.session.header.xtribe,
        data: feedback,
      });
    }
    if (req.body.trustedtribe) {
      if (req.app.locals.tribeids.includes(req.body.trustedtribe)) {
        delete feedback.withemail;
        const persondata = { recovery: feedback };
        res.send(
          Pagans.personupdate(req.body.alias, req.body.trustedtribe, persondata)
        );
      } else {
        res.send({
          status: 404,
          ref: "Pagans",
          msg: "tribedoesnotexist",
          data: { tribe: req.body.trustedtribe },
        });
      }
    } else {
      newpagan.data = feedback;
      res.send(newpagan);
    }
  } else {
    //error to create pagan
    res.send(newpagan);
  }
});
router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {put} /pagans/person
   * @apiName Is register check xalias and xhash
   * @apiGroup Pagans
   * @apiUse apxHeader
   *
   * add/update a person = alias + tribe with specific accessright and specific schema link to tribe
   * @todo add tribe/schema/person.json
   */
  console.log(req.body);
  res.send(
    Pagans.personupdate(req.body.alias, req.session.header.xtribe, req.body)
  );
});
router.delete("/:alias", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {delete} /pagans/:alias
   * @apiName Is register check xalias and xhash
   * @apiGroup Pagans
   * @apiUse apxHeader
   * */
  console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
  const result = Pagans.delete(req.params.id, req.session.header);
  res.status(result.status).send(result.data);
});
router.get("/keyrecovery/:tribeid/:email", checkHeaders, (req, res) => {
  /**
   * @api {get} /pagans/keyrecovery/tribe/email
   * @apiName  apxtrib
   * @apiGroup Pagans
   *
   *
   *
   * @apiError (400) {object} status missingheaders / xalias does not exist / signaturefailled
   * @apiError (401) {object} alias anonymous (not authenticated)
   * @apiError (404) {string} tribe does not exist
   *
   * @apiSuccess (200) {object} data contains indexfile requested
   *
   */
  res.send(Pagans.keyrecovery(req.params.tribeId, req.params.email));
});
module.exports = router;
