import express from "express";
import connection from "../db.js";

const router = express.Router();

router.get("/getUser", async (req, res) => {
  const userId = req.query.userid;
  let results, fields;
  try {
    [results, fields] = await connection.query(
      "SELECT p.name,t.time,t.project \
    FROM Timelog t \
    INNER JOIN Project p ON p.id=t.project \
    INNER JOIN User u ON u.id=t.user \
    WHERE USER = ? ;",
      [userId],
    );
  } catch (err) {
    console.log(err);
    res.status(400).json("ERROR");
  }
  let projects = {};
  let projectIdtoName = {};
  for (let i = 0; i < results.length; i++) {
    if (results[i].project in projects) {
      projects[results[i].project] += results[i].time;
    } else {
      projects[results[i].project] = results[i].time;
      projectIdtoName[results[i].project] = results[i].name;
    }
  }
  // map projectIds to project names before sending the data
  let respData = {};
  for (let key in projects) {
    if (projects.hasOwnProperty(key)) {
      respData[projectIdtoName[key]] = projects[key];
    }
  }
  res.json(respData);
});

export default router;
