const express = require("express");
const glob = require("glob");
const fs = require("fs-extra");
const path = require("path");
const conf = require(`${process.env.dirtown}/conf.json`);
const Odmdb = require("../models/Odmdb.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const hasAccessrighton = require("../middlewares/hasAccessrighton");
const router = express.Router();

router.get(
  "/:objectname/idx/:indexname",
  checkHeaders,
  isAuthenticated,
  (req, res) => {
    /**
     * @api {get} /odmdb/idx/:indexname
     * @apiName Get index file for an object
     * @apiGroup Odmdb
     *
     * @apiUse apxHeader
     * @objectname {string} Mandatory
     * @apiParam {String} indexname Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname/idx/indexname indexname contains the ObjectName .*_ (before the first _)
     *
     * @apiError (404) {string} status the file does not exist
     * @apiError (404) {string} ref objectmodel to get in the right language
     * @apiError (404) {string} msg key to get template from objectmodel
     * @apiError (404) {object} data use to render lg/objectmodel_lg.json
     *
     * @apiSuccess (200) {object} data contains indexfile requested
     *
     */
    console.log("pzasse");
    // indexname = objectname_key_value.json
    let objectLocation = "../../nationchains/";
    if (!conf.api.nationObjects.includes(req.params.objectname)) {
      objectLocation += `tribes/${req.session.headers.xtribe}/`;
      // check if accessright
    }
    const indexpath = `${objectLocation}/${req.params.objectname}/idx/${req.params.indexname}`;
    if (fs.existsSync(indexpath)) {
      res.status(200).json({ data: fs.readJsonSync(indexpath) });
    } else {
      res.status(404).json({
        ref: "Odmdb",
        msg: "objectfiledoesnotexist",
        data: { indexpath },
      });
    }
  }
);
router.get(
  "/:objectname/itm/:primaryindex",
  checkHeaders,
  isAuthenticated,
  (req, res) => {
    /**
     * @api {get} /odmdb/item/:objectname/:primaryindex
     * @apiName Get index file for an object
     * @apiGroup Odmdb
     *
     * @apiUse apxHeader
     *
     * @apiParam {String} objectname name Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname
     * @apiParam {String} primaryindex the unique id where item is store
     * @apiError (404) {string} status the file does not exist
     * @apiError (404) {string} ref objectmodel to get in the right language
     * @apiError (404) {string} msg key to get template from objectmodel
     * @apiError (404) {object} data use to render lg/objectmodel_lg.json
     *
     * @apiSuccess (200) {object} data contains indexfile requested
     *
     */
    // indexname = objectname_key_value.json
    const objectName = req.params.objectname;
    const objectId = req.params.primaryindex;
    let objectLocation = "../../nationchains/";
    if (!conf.api.nationObjects.includes(objectName)) {
      objectLocation += `tribes/${req.session.headers.xtribe}/${objectName}`;
      // check if accessright on object on item
      // in case not res.status(403)
    }
    const objectpath = `${objectLocation}/${objectName}/itm/${objectId}`;

    if (fs.existsSync(objectpath)) {
      res.status(200).json({ data: fs.readJsonSync(objectpath) });
    } else {
      res.status(404).json({
        ref: "Odmdb",
        msg: "objectfiledoesnotexist",
        data: { objectpath },
      });
    }
  }
);

router.post(":objectname/itm", checkHeaders, isAuthenticated, (req, res) => {
  // Create an item of an object
});
router.get(
  "/searchitems/:objectname/:question",
  checkHeaders,
  isAuthenticated,
  (req, res) => {
    /**
     *
     *
     */
    console.log(
      "route referentials get all language" +
        req.params.objectname +
        "-" +
        req.params.question
    );
    const getref = Referentials.getref(
      true,
      req.params.source,
      req.params.idref,
      req.session.header.xworkon,
      req.session.header.xlang
    );
    // Return any status the data if any erreur return empty object
    res.jsonp(getref.payload.data);
  }
);

router.get("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {get} /odmdb/schema/:objectname
   * @apiName GetSchema
   * @apiGroup Odmdb
   *
   * @apiUse apxHeader
   *
   * @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into  ./tribes/xworkon/
   *
   * @apiError (404) {string} status a key word to understand not found schema
   * @apiError (404) {string} ref objectmodel to get in the right language
   * @apiError (404) {string} msg key to get template from objectmodel
   * @apiError (404) {object} data use to render lg/objectmodel_lg.json
   *
   * @apiSuccess (200) {object} data contains schema requested
   *
   */
  const fullpath = path.resolve(
    `${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
  );
  if (fs.existsSync(fullpath)) {
    res.status(200).json({ data: fs.readJsonSync(fullpath) });
  } else {
    res
      .status(404)
      .json({ msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
  }
});
router.put("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
  /**
   * @api {put} /odmdb/schema/:objectname
   * @apiName putSchema
   * @apiGroup Odmdb
   *
   * @apiUse apxHeader
   *
   * @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into  ./tribes/xworkon/
   * @apiBody {string} schemapath where to store schema .../schema
   * @apiBody {string} objectpath where to store object ...objectname/idx/conf.json
   * @apiBody {json} schema content
   * @apiBody {json} schemalang content in lg
   * @apiBody {string} lang define which schemalg is (2 letters)
   *
   * @apiError (404) {string} status a key word to understand not found schema
   * @apiError (404) {string} ref objectmodel to get in the right language
   * @apiError (404) {string} msg key to get template from objectmodel
   * @apiError (404) {object} data use to render lg/objectmodel_lg.json
   *
   *
   * @apiSuccess (200) {object} data contains schema requested
   *
   */
  const fullpath = path.resolve(
    `${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
  );
  const set = Odmdb.setObject(
    path.resolve(`${__dirname}/tribes/${req.session.header.xworkon}`)
  );

  if (fs.existsSync(fullpath)) {
    res.status(200).json({ data: fs.readJsonSync(fullpath) });
  } else {
    res
      .status(404)
      .json({ msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
  }
});

module.exports = router;
