import "@std/dotenv/load";
import { Hono } from "hono";
import { getGroceryList, getRecipesList, storeRecipe } from "./services.ts";
import db from "./db.ts";
import { Layout } from "./web/tsx/layout.tsx";
import { AddRecipe, GroceryList, RecipesList } from "./web/tsx/components.tsx";
import { serveStatic } from "hono/deno";
import { basicAuth } from "hono/basic-auth";
const httpUser = Deno.env.get("HTTP_USER");
const httpPass = Deno.env.get("HTTP_PASS");
const app = new Hono();
app.use("/style.css", serveStatic({ path: "./web/static/style.css" }));
if (httpUser && httpPass)
app.use(
"/*",
basicAuth({
username: httpUser,
password: httpPass,
})
);
app.get("/", (c) => {
const recipes = getRecipesList(db);
return c.html(
);
});
app.get("/grocery", (c) => {
const url = new URL(c.req.url);
const recipeIds =
url.searchParams.get("recipeIds")?.split(",").map(Number) || [];
const recipes = getRecipesList(db, recipeIds);
const ingredients = getGroceryList(db, recipeIds);
return c.html(
Retour
);
});
app.post("/add-recipe", async (c) => {
const body = await c.req.formData();
const recipeId = body.get("recipeId");
if (!recipeId) return c.redirect("/");
try {
await storeRecipe(db, recipeId as string);
return c.redirect(
`/?msg=${encodeURIComponent("La recette a bien été ajoutée")}`
);
} catch (error) {
console.error(error);
return c.redirect(
`/?error=${encodeURIComponent("Problème lors de l'ajout")}`
);
}
});
app.post("/add-grocery-list", async (c) => {
const body = await c.req.formData();
const enabledRecipeIds = [...body.entries()]
.filter(([_, value]) => value === "on")
.map(([key]) => key);
return c.redirect(`/grocery?recipeIds=${enabledRecipeIds.join(",")}`);
});
export default app;