import * as auth from "basic-auth";
import * as express from "express";

const router = express.Router();

router.use((req, res, next) => {
  const user = auth(req);
  if (user && user.name === "isi" && user.pass === "123zauberbar") { // Here you need some logic to validate authentication
    next();
  } else {
    res.set({
      "WWW-Authenticate": 'Basic realm="kuerbiskern-admin"',
    }).send(401);
  }
});


function compare(a, b) {
  if (a.levels != null && b.levels != null) {
    return a.levels.avg < b.levels.avg ? 1 : (a.levels.avg === b.levels.avg ? 0 : -1);
  } else if (a.levels != null) {
    //console.log("level a");
    return -1;
  } else if (b.levels != null) {
    //console.log("level b");
    return 1;
  }
  //console.log("name");
  const aid = parseInt(a.entry[2], 10);
  const bid = parseInt(b.entry[2], 10);
  return aid > bid ? 1 : (aid === bid ? 0 : -1);
}


router.get("/", (req, res, next) => {
  const users = (req.app as any).db.get("users").value();
  //console.log(users);
  const cList = (req.app as any).cocktailList;
  const cEntries = (req.app as any).cocktails;
  const list = cEntries.slice(0, cEntries.length);
  for (const user of users) {
    for (const ctail of (user.cocktails as Array<{level: number, cocktail: string}>)) {
      const idx = cList.indexOf(ctail.cocktail);
      if (Array.isArray(list[idx])) {
        list[idx] = ({entry: list[idx], levels: [ctail.level]} as any);
      } else {
        (list[idx] as {entry: any[], levels: number[]}).levels.push(ctail.level);
      }
    }
  }
  list.forEach((value, idx, arr) => {
    if (!Array.isArray(value)) {
      value.levels = {
        cnt: (value as any).levels.length,
        max: Math.max(...(value as any).levels),
        min: Math.min(...(value as any).levels),
        avg: (value as any).levels.reduce((a, b) => a + b, 0) / (value as any).levels.length,
      };
    } else {
      arr[idx] = {entry: value, levels: null};
    }
  });
  list.sort((a, b) => {
    const comp = compare(a, b);
    return comp;
  });
  console.log(list);
  res.render("admin", {title: "Admin", list});
});

export = router;
