"use strict";

const express = require("express"),
  router = express.Router(),
  crypto = require("crypto"),
  { readFile, writeFile } = require("fs").promises,
  fs = require("fs"),
  accessSync = fs.accessSync,
  randomWords = require("random-words"),
  equal = require("fast-deep-equal");

const debug = {
  audio: false,
  get: true,
  set: true,
  update: false
};

let groupDB;

require("../db/groups").then(function(db) {
  groupDB = db;
});

/* Simple NO-OP to set session cookie so user-id can use it as the
 * index */
router.get("/", (req, res/*, next*/) => {
  let userId;
  if (!req.cookies.user) {
    userId = crypto.randomBytes(16).toString('hex');
    res.cookie('user', userId);
  } else {
    userId = req.cookies.user;
  }

  console.log(`[${userId.substring(0, 8)}]: Browser hand-shake achieved.`);

  return res.status(200).send({ user: userId });
});

router.post("/", async (req, res/*, next*/) => {
  console.log(`POST /groups/`, req.session.userId);
  return res.status(200).send(
    [ {
      id: 1,
      ownerId: 1,
      name: "Beer Tuesday",
      nextEvent: Date.now() + 86400 * 14 * 1000 /* 2 weeks from now */
    } ]
  );
});

router.post("/:id", async (req, res/*, next*/) => {
  const { id } = req.params;

  let userId;
  if (!req.cookies.user) {
    userId = crypto.randomBytes(16).toString('hex');
    res.cookie('user', userId);
  } else {
    userId = req.cookies.user;
  }

  if (id) {
    console.log(`[${userId.substring(0,8)}]: Attempting load of ${id}`);
  } else {
    console.log(`[${userId.substring(0,8)}]: Creating new group.`);
  }
  console.log(`[${userId.substring(0,8)}]: ${group.id} loaded.`);

  return res.status(200).send({ id: group.id });
});


module.exports = router;
