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

// Classes
const Wwws = require("../models/Wwws.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");

const router = express.Router();
// GET api/wwws/conf/:tribeId/:website
// if profils accessright return the nginx conf in ${conf.dirtown}/tribes/${req.param.tribeId}/www/nginx_${req.params.tribeId}_${req.params.website}.conf
router.get(
  "/conf/:tribeId/:website",
  checkHeaders,
  isAuthenticated,
  (req, res) => {
    res.send(Www.configlist(req.params.tribeId));
  }
);
router.post(
  "/conf/:tribeId/:website",
  checkHeaders,
  isAuthenticated,
  (req, res) => {
    res.send(Wwws.create(req.params.tribeId));
  }
);

/**
 * @api {put} /adminapi/wwws/webcomponents - Get local web components
 * @apiGroup Wwws
 * @apiName getwco
 * @apiDescription Get web component from backend to localstorage for development. This is anonymous but must be authenticated with accessright to other tribe to get their web component.<br> For production  it will generate a unique id that store to add in updatelocaldb with in production space /js/uniqueid.js css/uniqueid.css pagename.html with link in it
 * 
 * @apiBody {object}  tribelistwco { wco:{tribe:[wconame]}, mode:"dev"|"prod"}
*/
router.put(
  "/updatelocalwcoanonymous",
  checkHeaders,
  (req, res) => {
    console.log("localstorage anonymous for web component", req.session.header.xalias);
    req.session.header.xprofils = ["anonymous"];
    console.log(req.session.header.xprofils);
    //ajouter une detection de changement
    const getlocal = Wwws.initlocalwco(
      req.body,
      req.session.header.xprofils,
      req.session.header.xlang
    );
    res.status(getlocal.status).json(getlocal);
  }
);

/**
 * @api {get} /adminapi/wwws/updatelocaldbanonymous/:tribe/:appname/:pagename/:version - Get localdb for app anonymous only
 * @apiGroup Wwws
 * @apiName getappcontextforanonymous
 * @apiDescription Get data base from backend to localstorage for anonymous (see Get app data model)
 *
 * @apiParams {string} tribe (adminapi,smatchit,..) to looking for
 * @apiParams {string} appname  agregate a full data referential to store localy
 * @apiParams {string} pagename app page name
 * @apiParams {interger} version  the current version
*/
router.get(
  "/updatelocaldbanonymous/:tribe/:appname/:pagename/:version",
  checkHeaders,
  (req, res) => {
    console.log("pass localstorage anonymous", req.session.header.xalias);
    req.session.header.xprofils = ["anonymous"];
    console.log(req.session.header.xprofils);
    //ajouter une detection de changement
    const getlocal = Wwws.initlocaldata(
      req.params.tribe,
      req.params.appname,
      req.params.pagename,
      req.params.version,
      req.session.header.xprofils,
      req.session.header.xlang
    );
    res.status(getlocal.status).json(getlocal);
  }
);

/**
 * @api {get} /adminapi/wwws/updatelocaldb/:tribe/:appname/:pagename/:version - Get localdb for app
 * @apiGroup Wwws
 * @apiName getappcontext
 * @apiDescription Get data base from backend to localstorage for authenticated user
 *
 * @apiParams {string} tribe (adminapi,smatchit,..) to looking for
 * @apiParams {string} appname  agregate a full data referential to store localy
 * @apiParams {string} pagename app page name
 * @apiParams {interger} version  the current version
 * @apiSuccess {object} contain new version data model for a local web app in a PWA logical in the language of the header or if no new version exist then return
 * @apiSuccessExample {json} datamodelupdate
 * {"status":200, "ref":"Wwws", "msg":"datamodelupdate", "data":{version,confpage,profils,schema,options,ref,tpl,tpldata}}
 * @apiSuccessExample {json} datamodelnoupdate
 * HTTP/1.1 200 OK
 * {"status":200, "ref":"Wwws", "msg":"datamodelupdate", "data":{version,confpage,profils,schema,options,ref,tpl,tpldata}}
 *  @apiSuccessExample {json} pagedoesnotexist
 *  {status: 200,ref: "Wwws", msg: "pagedoesnotexist", data: { pagename } }
 *  @apiSuccessExample {json} forbidenaccess
 *  {status: 200,ref: "Wwws", msg: "forbidenaccess",data: { pagename, profils } }
 */
router.get(
  "/updatelocaldb/:tribe/:appname/:pagename/:version",
  checkHeaders, isAuthenticated,
  (req, res) => {
    console.log("pass localstorage", req.session.header.xalias);
    console.log(req.session.header.xprofils);
    //ajouter une detection de changement
    const getlocal = Wwws.initlocaldata(
      req.params.tribe,
      req.params.appname,
      req.params.pagename,
      req.params.version,
      req.session.header.xprofils,
      req.session.header.xlang
    );
    res.status(getlocal.status).json(getlocal);
  }
);
/**
 * @api {get} /api/adminapi/wwws/buildpage/:tribe/:appname/:pagename - Create pagename
 * @apiGroup Wwws
 * @apiName createPagename
 * @apiDescription Create a pagename from /appscreen/template/:pagename with
 *
 * @apiParams {string} tribe (adminapi,smatchit,..) to looking for
 * @apiParams {string} appname  agregate a full data referential to store localy
 * @apiSuccess {object} contain cuurent version of the data model
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {"status":200, "ref":"Odmdb", "msg":"datamodelversion", "data":{version}
 */
router.get("/buildpage/:tribe/:appname/:pagename", checkHeaders, (req, res) => {
  console.log("pass get version localstorage");
  const localdbf = `../../${req.params.tribe}/objects/wwws/itm/${req.params.appname}`;
  if (!existsSync(localdbf)) {
    return res
      .status(404)
      .json({ status: 404, ref: "Wwws", msg: "localdbnotfound", data: {} });
  }
  res
    .status(200)
    .json({
      status: 200,
      ref: "Wwws",
      msg: "lastversion",
      data: { version: fs.readJSONSync(localdbf).version },
    });
});

module.exports = router;