const router = require("koa-router")();
const core = require("@serverless-devs/core");
const Response = require("../common/Response");
const path = require("path");
const { fse, lodash } = core;
const Parse =
  require("@serverless-devs/core/dist/common/execCommand/parse").default;

const spath = process.env["template"] || path.join(__dirname, "../s.yaml");

router.get("/", async (ctx, next) => {
  await ctx.render("index");
});

router.get("/api/access/list", async (ctx, next) => {
  const content = await core.getYamlContent(
    path.join(core.getRootHome(), "access.yaml")
  );
  ctx.body = Response.sussess(content);
});

router.get("/api/originYaml", async (ctx, next) => {
  const response = await core.getYamlContent(spath);
  ctx.body = Response.sussess(response);
});

router.post("/api/globalMagic", async (ctx, next) => {
  const instance = new Parse();
  const parsedObj = await instance.beforeInit(ctx.body).init();
  // 兼容vars下的魔法变量，需再次解析
  await instance.init(parsedObj.realVariables);
  const response = instance.getGlobalMagic();
  ctx.body = Response.sussess(response);
});

router.post("/api/watchYaml", async (ctx, next) => {
  const data = fse.readFileSync(spath, "utf8");
  const response = core.modifyYaml(ctx.body, data);
  ctx.body = Response.sussess(response);
});

router.post("/api/saveYaml", async (ctx, next) => {
  const data = fse.readFileSync(spath, "utf8");
  const response = core.modifyYaml(ctx.body, data);
  fse.writeFileSync(spath, response);
  ctx.body = Response.sussess("sussess");
});

router.get("/api/schema", async (ctx, next) => {
  const newData = await core.getYamlContent(spath);
  const serviceName = ctx.query.serviceName;
  const componentName = lodash.get(
    newData,
    `services.${serviceName}.component`,
    // TODO：对于新添加的服务，后续如何获取自己的schema数据，（添加模版时指定组件？）先默认fc
    "devsapp/fc"
  );
  const response = await core.loadComponent(componentName);
  const publishPath = path.join(response.__path, "publish.yaml");
  const publishData = await core.getYamlContent(publishPath);
  ctx.body = Response.sussess(lodash.get(publishData, "Properties"));
});
module.exports = router;
