const Student = require("../models/Student");
const User = require("../models/User");

//function for trimming strings
function trim_arr(arr) {
  let newArr = arr.map((a) => {
    return a.trim();
  });
  return newArr;
}

module.exports.getProfile = async (req, res, next) => {
  try {
    //we can get the profile of the user including the courses which user has bought
    const userId = req.user._id;
    let user = await User.findById(userId);
    let student = await Student.findOne({ user: userId }).populate(
      "courses.basicInfo"
    );
    res.json({
      user: user,
      student: student,
    });
  } catch (err) {
    res.json({
      error: err,
    });
  }
};

module.exports.postProfile = async (req, res, next) => {
  try {
    //Here we are updating the profile of the user
    const userId = req.user._id;
    let interests = req.body.interests;
    let projects = req.body.projects;
    let yearofgrad = req.body.yearofgrad;
    let phoneNumber = req.body.phoneNumber;
    let institute = req.body.institute;
    let skills = req.body.skills;

    let student = await Student.findOne({ user: userId });
    if (interests) {
      student.interests = trim_arr(interests.split(","));
    }
    if (projects) {
      student.projects = trim_arr(projects.split(","));
    }
    if (skills) {
      student.skills = trim_arr(skills.split(","));
    }
    if (yearofgrad) {
      student.yearofgrad = yearofgrad.trim();
    }
    if (phoneNumber) {
      student.phoneNumber = phoneNumber.trim();
    }
    if (institute) {
      student.institute = institute.trim();
    }
    await student.save();

    res.json({
      message: "Updated profile",
    });
  } catch (err) {
    console.log(err);
    res.json({
      error: err,
    });
  }
};

module.exports.deleteUser = async (req, res, next) => {
  //here we are deleting the user
  const userId = req.user._id;
  try {
    await Student.deleteOne({ user: userId });
    await User.deleteOne({ _id: userId });
    res.json({
      message: "Successfully deleted",
    });
  } catch (err) {
    console.log(err);
    res.json({
      error: err,
    });
  }
};

module.exports.editProfile = async (req, res, next) => {
  const { _id, newFirstName, newLastName, email } = req.body;
  try {
    if (_id) {
      let user = await User.findById({ _id });
      console.log("User", user);
      if (user) {
        user.firstName = newFirstName;
        user.lastName = newLastName;
        user.email = email;
        user = await user.save();
        res.json({ message: "Profile Updated!" });
      } else {
        res.status(422).json({ error: "User Not Found with that Id" });
        return;
      }
    } else {
      res.status(422).json({ error: "User Id is Must" });
      return;
    }
  } catch {
    (err) => {
      console.log("error", err);
      res.status(422).json({ error: err });
      return;
    };
  }
};