var express = require("express");
var router = express.Router();

const convertToHongKongTime = (date_now) => date_now + 8 * 3600 * 1000;

// EXPLAIN: http://localhost:3001/signin
// EXPLAIN: 1. HTTP POST requests for http://localhost:3001/signin. The middleware should parse the
// EXPLAIN: body of the HTTP POST request and extract the username and password carried in request
// EXPLAIN: body. Then it checks whether the username and password match any record in the userList
// EXPLAIN: collection in the database.
//          If no, send “Login failure” in the body of the response message.
//          If yes, create a session variable “userId” and store this user’s _id in the session variable.
// EXPLAIN: Retrieve name and icon of the current user (according to the value of the “userId” session
// EXPLAIN: variable), _id, lastsavedtime and title of all notes of the current user from the respective
// EXPLAIN: collections in the MongoDB database. Send all retrieved information as a JSON string to the
// EXPLAIN: client if database operations are successful, and the error if failure. You should decide the
// EXPLAIN: format of the JSON string and parse it accordingly in the front-end code to be implemented
// EXPLAIN: in Task 2.
router.post("/signin", function (req, res, next) {
  var { db, params, body } = req;
  var collection = db.get("users");
  var { username: name, password } = body;

  console.log({ name, password });

  collection.find({ name, password }, {}, (err, docs) => {
    if (err) res.send({ msg: err });

    if (docs.length > 0) {
      req.session.userId = docs[0]._id;
      res.send({ msg: "login success", user_meta: docs[0] });
    } else {
      res.send({ msg: "login failure" });
    }
  });
});

// EXPLAIN: 2. HTTP GET requests for http://localhost:3001/logout.
// EXPLAIN: The middleware should clear the
// EXPLAIN: “userId” session variable and send an empty string back to the user.
router.get("/logout", function (req, res, next) {
  // req.session.userId = "";
  try {
    delete req.session.userId;
  } catch (error) {
    console.log("error during logout");
  }

  res.send({ msg: "logout success" });
});

// EXPLAIN: 3. HTTP GET requests for http://localhost:3001/getnote?noteid=xx.
// EXPLAIN: Retrieve _id, lastsavedtime, title and content of the note from the noteList collection based on
// EXPLAIN: the value of “nodeid” carried in the URL.
// EXPLAIN: Send retrieved information as a JSON string in the body of the
// EXPLAIN: response message if database operations are successful, and the error if failure.
// EXPLAIN: You should decide the format of the JSON string to be included in the response body.
router.get("/getnote/:note_id", function (req, res, next) {
  var { db, params, body, session } = req;
  var { userId } = session;
  var notes_collection = db.get("noteList");
  var { note_id } = params;

  console.log({ userId });

  if (note_id == "*" || note_id == "") {
    // list notes
    notes_collection.find({ userId }, { sort: { lastsavedtime: -1 } }, (err, docs) => {
      if (err) res.send({ msg: err });

      if (docs.length > 0) {
        res.send(docs);
      } else {
        res.send({ msg: "the wanted note not found" });
      }
    });
  } else {
    console.log({ note_id });
    notes_collection.find({ _id: note_id, userId: userId }, { sort: { lastsavedtime: -1 } }, (err, docs) => {
      if (err) res.send({ msg: err });

      if (docs.length > 0) {
        res.send(docs);
      } else {
        res.send({ msg: "the wanted note not found" });
      }
    });
  }
});

// EXPLAIN: 4. HTTP POST requests for http://localhost:3001/addnote.
// EXPLAIN: The middleware should parse the body of the HTTP POST request
// EXPLAIN: and extract the note title and content carried in the request body.
// EXPLAIN: Then it saves the new note into the noteList collection together with the _id of the
// EXPLAIN: current user (based on the value of “userId” session variable) and
// EXPLAIN: the current time on the server as the lastsavedtime.

// EXPLAIN: Return the lastsavedtime and _id of the note document in the nodeList collection to the client in JSON
// EXPLAIN: if database operations are successful, and the error if failure.
router.post("/addnote", function (req, res, next) {
  var { db, params, body } = req;
  var { title, content } = body;
  var { userId } = req.session;

  var notes_collection = db.get("noteList");
  var local_time = Date.now() + 8 * 3600 * 1000;

  notes_collection.insert({ title, content, userId, lastsavedtime: convertToHongKongTime(Date.now()) });
  res.send({ msg: "add note success" });
});

// EXPLAIN: 5. HTTP PUT requests for http://localhost:3001/savenote/:noteid.
// EXPLAIN: The middleware should update the lastsavedtime, title and content of the note in the noteList collection
// EXPLAIN: based on the nodeid carried in the URL,
// EXPLAIN: the current time on the server and the data contained in the body of the request message.
// EXPLAIN: Return the lastsavedtime to the client if success and the error if failure.
router.put("/savenote/:noteid", (req, res) => {
  // var db = req.db;
  // var collection = db.get("noteList");
  var { db, body, params } = req;
  var notes_collection = db.get("noteList");
  var { noteid } = params;
  var { title, content } = body;

  notes_collection.update(
    { _id: noteid },
    { $set: { title, content, lastsavedtime: convertToHongKongTime(Date.now()) } },
    function (err, result) {
      if (err) console.log({ msg: "error during update note" });
      // If the update operation is successful, send “Successfully updated!” to the client;
      // otherwise, send the error in the response.

      res.send({ msg: "updated successfully" });
    }
  );
});

// EXPLAIN: 6. HTTP GET requests for http://localhost:3001/searchnotes?searchstr=xx.
// EXPLAIN: The middleware should find in the noteList collection all notes of the current user (based on the value of
// EXPLAIN: “userId” session variable) whose title or content contains the searchstr carried in the URL.
// EXPLAIN: Send _id, lastsavedtime and title of those notes in JSON to the client if database operations
// EXPLAIN: are successful, and the error if failure.
router.get("/searchnotes/:searchstr", async (req, res, next) => {
  var { db, params } = req;
  var notes_collection = db.get("noteList");
  var { searchstr } = params;

  notes_collection.find(
    { $or: [{ title: searchstr }, { content: searchstr }] },
    { sort: { lastsavedtime: -1 } },
    (err, docs) => {
      if (err) res.send({ msg: err });

      if (docs.length > 0) {
        res.send(docs);
      } else {
        res.send({ msg: "the wanted note not found" });
      }
    }
  );
});

// EXPLAIN: 7. HTTP DELETE requests for http://localhost:3001/deletenote/:noteid.
// EXPLAIN: The middleware, should delete the note from the noteList collection according to the noteid carried in the URL.
// EXPLAIN: Return an empty string to the client if success and the error if failure.
router.delete("/deletenote/:noteid", (req, res) => {
  var { db, params, body } = req;
  var { noteid } = params;
  var notes_collection = db.get("noteList");

  console.log(JSON.stringify({ noteid }));
  // // uses collection.remove({‘name’: req.params.name}) to remove the topic document from the topicList collection.
  notes_collection.remove({ _id: noteid }, function (err, result) {
    if (err) res.send({ msg: err.message });

    // If the remove operation is successful, send the string “Successfully deleted!”
    // to the client side; otherwise, send the error in the response.
    res.send({ msg: "Successfully deleted!" });
  });
});

// EXPLAIN: helloworld endpoint
router.get("/helloworld", function (req, res, next) {
  var { db, params, body, session } = req;
  var notes_collection = db.get("noteList");

  notes_collection.find(
    { _id: "6399bc615d147202753ca3b3", userId: "u9999" },
    { sort: { lastsavedtime: -1 } },
    (err, docs) => {
      if (err) res.send({ msg: err });

      if (docs.length > 0) {
        res.send(docs);
      } else {
        res.send({ msg: "the wanted note not found" });
      }
    }
  );
});

module.exports = router;
