import * as cookieParser from "cookie-parser";
import * as express from "express";
import * as createError from "http-errors";
import * as low from "lowdb";
import * as FileSync from "lowdb/adapters/FileSync";
import * as logger from "morgan";
import * as path from "path";
import * as uuidv4 from "uuid/v4";

import * as indexRouter from "./routes/index";
import * as usersRouter from "./routes/users";

const app = express();
const adapter = new FileSync("db.json")
const db = low(adapter);
db.defaults({users: []})
  .write();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use((req, res, next) => {
  const user = db.get("users").find({id: req.cookies.uid}).value();
  if (!req.cookies || !req.cookies.uid || !user) {
    const id = uuidv4();
    db.get("users")
      .push({id, age: -1, sex: "na", cocktails: []})
      .write();
    res.cookie("uid", id, { maxAge: 21474836470000, httpOnly: true });
  }
  next();
});
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
