import * as express from "express";

const router = express.Router();


router.use((req, res, next) => {
  if (!req.cookies || !req.cookies.uid) {
    res.status(404);
    res.send();
  } else {
    next();
  }
});

router.get("/personal", (req, res) => {
  const ageStr = req.query.age || null;
  const age = parseInt(ageStr, 10);
  const sex = req.query.sex || null;
  const result: {age?: number, sex?: string} = {};
  if (age > 15 && age < 99) {
    result.age = age;
  } else if (ageStr === "" || !isNaN(age)) {
    result.age = -1;
  }
  if (["na", "m", "w", "o"].indexOf(sex) > -1) {
    result.sex = sex;
  }
  console.log(result);
  if (!!result.age || !!result.sex) {
    (req.app as any).db.get("users")
      .find({id: req.cookies.uid})
      .assign(result)
      .write();
  }
  res.status(204);
  res.send();
});


router.get("/newcocktail", (req, res) => {
  const db = (req.app as any).db;
  const levelStr = req.query.level || null;
  const level = parseInt(levelStr, 10);
  const cocktail = req.query.cocktail || null;
  const result: {level?: number, cocktail?: string} = {};
  if (level > 0 && level < 8) {
    result.level = level;
  }
  if ((req.app as any).cocktailList.indexOf(cocktail) > -1) {
    result.cocktail = cocktail;
  }
  if (!!result.level && !!result.cocktail) {
    const findRes = db.get("users").find({id: req.cookies.uid}).get("cocktails").find({cocktail});
    if (!findRes.value()) {
      db.get("users")
        .find({id: req.cookies.uid})
        .get("cocktails")
        .push(result)
        .write();
    } else {
      findRes
        .assign(result)
        .write();
    }
  }
  res.status(204);
  res.send();
});


router.get("/getingredients", (req, res) => {
  const cocktail = req.query.cocktail || null;
  if ((req.app as any).cocktailList.indexOf(cocktail) > -1) {
    const index = (req.app as any).cocktailList.indexOf(cocktail);
    const cdetails = (req.app as any).cocktails[index][7].replace(/;/g, ", ");
    res.status(200);
    res.send(cdetails);
  } else {
    res.status(200);
    res.send("");
  }
});


router.get("/isvaliduid", (req, res) => {
  const uid = req.query.uid || null;
  const newuser = (req.app as any).db.get("users")
    .find({id: uid})
    .value();
  if (!!newuser) {
    res.status(200);
    res.send("valid");
  } else {
    res.status(200);
    res.send("invalid");
  }
});



export = router;
