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 read from "read-file";
import * as uuidv4 from "uuid/v4";

import * as adminRouter from "./routes/admin";
import * as exportRouter from "./routes/export";
import * as impressumRouter from "./routes/impressum";
import * as indexRouter from "./routes/index";
import * as recommendsRouter from "./routes/recommends";
import * as updateRouter from "./routes/update";

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




(app as any).cocktails = [];

read("data/output.csv", "utf8", (err, buffer) => {
  // console.log(buffer);
  const cocktailList = [];
  let result = buffer.split(/\n|\r|\n\r|\r\n/);
  result = result.map((line) => {
    line = line.split("\t");
    if (line.length !== 8) {
      return null;
    }
    line[0] = parseFloat(line[0]);
    line[1] = parseFloat(line[1]);
    line[4] = `${line[4].substr(0, line[4].length - 2)},${line[4].substr(-2)} €`;
    line[5] = `${line[5].substr(0, line[5].length - 2)},${line[5].substr(-2)} €`;
    cocktailList.push(line[3]);
    return line;
  });
  result = result.filter((f) => !!f);
  (app as any).cocktails = result;
  (app as any).cocktailList = cocktailList;
});




// 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: [], lastused: Date.now()})
      .write();
    res.cookie("uid", id, { maxAge: 21474836470000/*, httpOnly: true*/ });
    if (!req.cookies) {
      req.cookies = {};
    }
    req.cookies.uid = id;
  } else {
    db.get("users")
      .find({id: req.cookies.uid})
      .assign({lastused: Date.now()})
      .write();
  }
  next();
});
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/admin", adminRouter);
app.use("/export", exportRouter);
app.use("/update", updateRouter);
app.use("/recommends", recommendsRouter);
app.use("/impressum", impressumRouter);

// 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;
