const { cleanURL, cleanPath,getJwt } = require("../utilities/utils");
const { createProxyMiddleware } = require("http-proxy-middleware");
var serialize = require('serialize-javascript');
var _ = require("lodash");
const express = require("express");

async function configAdmin() {
  return new Promise((resolve, reject) => {
    var contentTypes = [];
    var Path = cleanPath(process.cwd() + "/admin/collections/*.js");
   // console.log("Path to collections", Path);
    glob(Path, {}, function (er, files) {
      files.map((file) => {
        let collection = require(file);
        contentTypes.push(collection);
      });
    });

    var config = {
      configCollections: {
        contentTypes: contentTypes,
      },
    };

    resolve(config);
  });
}

async function loadAdminPanel(config) {
  //console.log(process.env.proxy)

  var configPanel = await configAdmin();
  var app = config.app;

  
  //
 // app.get("/___CRTL_ADMIN___", (req, res) => {
   
  //  res.send(JSON.stringify(serialize(configPanel)));
  //});

  if (config.routes.admin?.enabled) {
    app.get("/", (req, res) => {
      res.sendFile(__dirname + "/spa/index.html");
    });
    app.use("/", express.static(__dirname + "/spa"));
    // Extend Admin panel
    if (config.routes.admin.extendAdmin) {
      const apiProxy = createProxyMiddleware({
        target: config.routes.admin.extendTarget,
        changeOrigin: true,
      });
      app.use(config.routes.admin.extendPath, apiProxy);
    } 
  }
}

module.exports = {
  loadAdminPanel,
};
