const router = require("express").Router();
const User = require("../model/User");
const bcrypt = require("bcryptjs");
const { registerValidation, loginValidation } = require("../validation");
const jwt = require("jsonwebtoken");
const verify = require("./verifyToken");

router.post("/register", async (req, res) => {
  //Lets Validate the data before making a user
  const { error } = registerValidation(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  //Checking to see if the email already exists in Database
  const emailExist = await User.findOne({ email: req.body.email });
  if (emailExist) return res.status(400).send("This Email already exists");

  //Hash the password
  const salt = await bcrypt.genSalt(10);
  const hashedPassword = await bcrypt.hash(req.body.password, salt);

  const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: hashedPassword,
  });
  try {
    const savedUser = await user.save();
    res.status(200).send({ user: user._id });
    console.log('User' + req.body.name + ' created!');
  } catch (err) {
    res.status(400).send(err);
  }
});

//Login
router.post("/login", async (req, res) => {
  //Es validen les dades
  const { error } = loginValidation(req.body);
  if (error) return res.status(400).send(error.details[0].message);
  //Comprovem si l ’ email ja existeix dins la Base de Dades
  const user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send();
  //Is the Password correct?
  const validPass = await bcrypt.compare(req.body.password, user.password);
  if (!validPass) return res.status(400).send();
  //Create and assign a token
  const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
  res.header('auth-token',token).send({'token':token});
});

router.get("/", verify, async (req, res) => {;
  const user = await User.findOne({'_id': req.user._id});
  if(user){
    res.status(200).send({'username':user.name});
  }else{
    res.status(404).send(JSON.stringify({'message':'Invalid Credentials'}));
  }
});


router.post("/addDevice", verify, async (req, res) => {
  console.log("/addDevice");
  console.log(req.body.subscription);
  const user = await User.findOne({'_id': req.user._id});
  if(user){
    if(req.body.subscription != null){
      await User.updateOne({'_id': req.user._id},{$addToSet:{'devices': {'devicename':req.body.name, 'subscription': req.body.subscription}}});
      res.status(200).send(JSON.stringify({'message':'Device added succesfully'}));
    }else{
      console.log("ERROR: Subscription is null");
      res.status(400).send('subscription is null');
      
    }
    
  }else{
    res.status(404).send();
  }
});

router.post("/addFriend", verify, async (req, res) => {
  var friend = await User.findOne({'name': req.body.friend});
  if (!friend) return res.status(400).send();
  //Create and assign a token
  await User.updateOne({'_id': req.user._id},{$addToSet:{'friends': {'id': friend._id, 'name': req.body.friend}}});
  res.status(200).send();
  console.log(await User.findOne({'_id': req.user._id}));
});



router.get("/:id/devices", verify, async (req, res) => {
  const user = await User.findOne({'_id': req.params.id});
  if(user){
    res.send({'devices':user.devices});
  }else{
    res.status(404).send();
  }
});

router.get("/friends", verify, async (req, res) => {
  const user = await User.findOne({'_id': req.user._id});
  if(user){
    res.send({'friends':user.friends});
  }else{
    res.status(404).send();
  }
});

router.get("/devices", verify, async (req, res) => {
  const user = await User.findOne({'_id': req.user._id});
  if(user){
    res.send({'devices':user.devices});
  }else{
    res.status(404).send();
  }
});

router.delete("/devices/:name", verify, async (req, res) => {
  const user = await User.findOne({'_id': req.user._id});
  console.log(" DELETE /devices")
  if(user){
    await User.updateOne({'_id': req.user._id},{$pull:{'devices': {'devicename': req.params.name}}});
    res.status(200).send();
  }else{
    res.status(404).send();
  }
});
module.exports = router;
