// set static variables
const express = require("express");
const app = express();
const fs = require("fs");
const path = require("path");
const marked = require("marked");

app.set("view engine", "ejs");

app.get("/add", (req, res) => {
  res.render("addRecipe/index");
});

app.get("/", (req, res) => {

  // script to sync recipes
  const recipesFolder = path.join(__dirname, "database/recipes");
  fs.readdir(recipesFolder, (err, files) => {
    if (err) {
      return res.status(500).send("Error by reading recipe files!");
    }

    const txtFiles = files.filter((file) => file.endsWith(".txt"));

    const recipes = txtFiles.map((file) => {
      const content = fs.readFileSync(path.join(recipesFolder, file), "utf8");
      return {
        title: path.basename(file, ".txt"),
        content: marked.parse(content),
      };
    });

    res.render("index", { recipes });
  });

  // script to render in markdown
  
});

// middleware for add recipe
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// add recipe script
app.post("/add/create-recipe", (req, res) => {
  const { filename, content } = req.body;

  const directory = path.join(__dirname, "database/recipes");
  // left out if statement for directory check
  /*
  if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory);
  }
      */

  const filePath = path.join(directory, `${filename}.txt`);

  fs.writeFile(filePath, content, (err) => {
    if (err) {
      console.error(err);
      return res
        .status(500)
        .console.error("Error by creating file")
        .send("Error by creating file. Please check browser console!");
    }
    res.render("success", {
      filename: filename,
      path: filePath,
    });
  });
});

const recipeRouter = require("./routes/recipes");

app.use("/recipe", recipeRouter);

app.listen(3000);
