const express = require("express");
const fs = require("fs-extra");
const path = require("path");

// Classes
const Pagans = require("../models/Pagans.js");

// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");

const router = express.Router();
/**
 *  /api/models/Pagans.js
 * 
 * Managed:

/**
 * Alias exist then return public key or not 
 * @api {get} /pagans/alias/:alias - alias Get 
 * @apiName isalias
 * @apiGroup Pagans
 * @apiDescription If alias exist return its publickey
 * 
 * @param {string} alias 
 * 
 * @apiError {json} aliasdoesnotexist  
 * @apiErrorExample {json}
 * HTTP/1.1 404 Not Found
   {"status":404,"ref":"pagans","msg":"aliasdoesnotexist","data": { alias}}
 *
 * @apiSuccess {object}  indexfile content
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {"status":200, ref:"pagans","msg":"aliasexist","data": { alias, publicKey }}
 *  *
 **/
router.get("/alias/:alias", (req, res) => {
  const getalias = Pagans.getalias(req.params.alias);
  res.status(getalias.status).send(getalias);
});
/**
 * Remove serveur token
 * @api {get} /pagans/logout - pagan Logout
 * @apiName Removetoken
 * @apiGroup Pagans
 * @apiDescription Remove token 
 * 
 * @apiSuccess {object}  indexfile content
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {status: 200, ref: "Pagans", msg: "logout"
 *
 */
router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
  console.log(req.session.header);
  const logout = Pagans.logout(
    req.session.header.xalias,
    req.session.header.xtribe,
    req.session.header.xdays,
    req.session.header.xhash
  );
  res.status(logout.status).json(logout);
});
/**
 * @api {get} /pagans/isauth  - pagan isAuthenticated?
 * @apiName isAuth
 * @apiGroup Pagans
 * @apiDescription Check if pagan's token is still valid
 *
 * @apiError (400) missingheaders
 * @apiError (400) xaliasdoesnotexist
 * @apiError (400) signaturefailled
 * @apiError (401) aliasanonymous
 * @apiError (404) tribedoesnotexist
 *
 * @apiSuccess (200) valid
 * {object} data contains indexfile requested
 *
 */
router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
  res.status(200).send({
    status: 200,
    ref: "headers",
    msg: "authenticated",
    data: {
      xalias: req.session.header.xalias,
      xprofils: req.session.header.xprofils,
    },
  });
});

/**
 * @api {post} /pagans  - pagan Post
 * @apiName addpagan
 * @apiGroup Pagans
 * @apiDescription
 *  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
 * 
 * @apiError {json} objectNotfound the file does not exist 
 * @apiErrorExample {json}
 * HTTP/1.1 404 Not Found
   {"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
 *
 * @apiSuccess {object}  indexfile content
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
 * 
 */
router.post("/", checkHeaders, isAuthenticated, (req, res) => {
  //console.log("pass ici", req.body);
  const objpagan = { alias: req.body.alias, publickey: req.body.publickey };
  const newpagan = Pagans.create(objpagan, {
    xalias: req.session.header.xalias,
    xprofils: req.session.header.xprofils,
  });
  if (newpagan.status == 200) {
    if (req.body.email) {
      const emailsent = Pagans.sendmailkey(
        req.body.alias,
        req.body.privatekey,
        req.session.header.xtribe,
        req.body.passphrase,
        req.body.publickey,
        req.body.email
      );
    }
    if (req.body.trustedtribe) {
      const personup = Pagans.personupdate(
        req.body.alias,
        req.body.trustedtribe,
        {
          recoveryauth: {
            email: req.body.email,
            privatekey: req.body.privatekey,
            publickey: req.body.publickey,
            passphrase: req.body.passphrase,
          },
        }
      );
      if (personup.status !== 200)
        console.log("Warning no recovery registration", personup);
    }
    if (emailsent && emailsent.status != 200) {
      newpagan.msg = "successfulcreatewithoutemail";
      res.status(newpagan.status).json(newpagan);
    }
  } else {
    //error to create pagan certaily already exist
    res.status(newpagan.status).json(newpagan);
  }
});
/**
 * @api {delete} /pagans/alias/:alias - pagan Delete
 * @apiName deletepagan
 * @apiGroup Pagans
 * @apiDescription
 *  Delete an alias and his publickey 
 * */
router.delete("/alias/:alias", checkHeaders, isAuthenticated, (req, res) => {
  console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
  const result = Pagans.deletealias(req.params.id, req.session.header);
  res.status(result.status).send(result.data);
});
router.delete("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
  console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
  const result = Pagans.deleteperson(req.params.id, req.session.header);
  res.status(result.status).send(result.data);
});

/**
 * @api {get} /pagans/person:alias - person Get
 * @apiName getpersondata
 * @apiDescription Get person information from his alias for a xtribe (data and profils per apps) 
 * @apiGroup Pagans
 *
 * @apiParam {string} alias
 * 
 * @apiSuccess (200) personExist
 * @apiSuccessExample {json}
 * {status:200, ref:"pagans",msg:"personexist",data: { person } }
 * 
 * @apiError (404) Notfound
 * @apiErrorExample {json}
 *  {status: 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
 * */
router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
  const getperson = Pagans.getperson(
    req.session.header.xtribe,
    req.params.alias,
    { xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
  );
  res.status(getperson.status).send(getperson);
});

/**
 * @api {post} /pagans/person - person Post
 * @apiName addperson
 * @apiGroup Pagans
 * @apiDescription
 * add a person = alias + tribe with specific accessright and specific schema link to tribe
 * 
 * 
 * 
 * @todo add tribe/schema/person.json
 */
router.post("/person", checkHeaders, isAuthenticated, (req, res) => {
  //console.log(req.body);
  const persoad = Pagans.personcreate(
    req.session.header.xtribe,
    req.body.alias,
    req.body,
    { xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
  );
  res.status(persoad.status).json(persoad);
});

/**
 * @api {put} /pagans/person - person Put
 * @apiName updateperson
 * @apiGroup Pagans
 * @apiDescription 
 * update a person = alias + tribe with specific accessright and specific schema link to tribe

* @todo add tribe/schema/person.json
 */
router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
  //console.log(req.body);
  const persoup = Pagans.personupdate(
    req.session.header.xtribe,
    req.body.alias,
    req.body,
    { xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
  );
  res.status(persoup.status).json(persoup);
});


/**
 * @api {get} /pagans/keyrecovery/tribe/email - recovery key by email
 * @apiName  recoveryKey
 * @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
 *
 */
router.get("/keyrecovery/:tribeid/:email", checkHeaders, (req, res) => {
  res.send(Pagans.keyrecovery(req.params.tribeId, req.params.email));
});
module.exports = router;
