const db = require("../models");
const Ad = db.ads;
const User = db.users;
const slugify = require('slugify');

// go to create page
exports.goToCreate= (req, res) => {
  res.render('../views/ad/createupdate.twig')
}


// Create a new Ad
exports.create = (req, res) => {
  
    const title = req.body.titre
    const ad = new Ad({

      titre: title,
      slug: '' + slugify(title + ''),
      type: req.body.type,
      statusPublication : req.body.statusPub,
      statusBien : req.body.statusBien,
      description: req.body.description,
      prix: req.body.prix,
      date: req.body.dateDispo,
      images : req.files.map(f=>f.filename),
      id_user : req.session.passport.user,
      questions:[]
    });

    // Save Ad in the database
    ad
      .save(ad)
      .then(data => {
        res.redirect('/show/'+ad.slug+'/'+ad.id)
      })
      .catch(err => {
        res.render('../views/ad/createupdate.twig', { error: err.message })
        
      });
};




//update an Ad
exports.update = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }

  const id = req.params.id;
  
  //add images and data to body 
  req.body.images=(req.body.aimages).split(',').concat(req.files.map(f=>f.filename))
  
  req.body.slug = slugify(''+req.body.titre)  
  req.body.id=id
  console.log(req.body.aimages )
  console.log(req.body )

  Ad.findByIdAndUpdate(id, req.body, { runValidators: true })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: 'Cannot update Tutorial with id=${id}. Maybe Tutorial was not found!'
        });
      } else res.redirect('/show/'+data.slug+'/'+data.id);
    })
    .catch(err => {
      //res.redirect(req.originalUrl)
      res.render('../views/ad/createupdate.twig',{ad:req.body, error:err.message })
      
    });
};



// go to update ad page  
exports.findOneUpdate = (req, res) => {
  const id = req.params.id;

  Ad.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Ad with id " + id });
      else {
        console.log(req.params.error)
        res.render('../views/ad/createupdate.twig', { ad: data, error: req.params.error});
      }
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Ad with id=" + id });
    });
};




//find an Ad and send it
exports.findOne = (req, res) => {
  const id = req.params.id;

  Ad.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Ad with id " + id });
      else res.render('../views/ad/show.twig', {ad: data});
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Ad with id=" + id });
    });
};



//findAll Ads
exports.findAll = (req, res) => {
 
  Ad.find({}, function (err, result) {
    if (err) {
      console.log(err);
    } else {
      res.render('index', { results: result })
    }
  });
};


// delete an Ad
exports.delete = (req, res) => {
  const id = req.params.id;

  Ad.findByIdAndRemove(id)
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot delete AD with id=${id}. Maybe Tutorial was not found!`
        });
      } else {
        res.redirect('/users/user')
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Tutorial with id=" + id
      });
    });
};

//allow to ask a question
exports.question =(req, res)=>{
  const id = req.params.id

  Ad.findById(id, function (err, ad) {
    ad.questions.push({username:req.body.username, question:req.body.question})
    Ad.findByIdAndUpdate(id, ad, { runValidators: true })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: 'Cannot update Tutorial with id=${id}. Maybe Tutorial was not found!'
        });
      } else res.redirect("/show/"+data.slug+"/"+data.id)
    })
    .catch(err => {
      //res.redirect(req.originalUrl)
      res.send("not commpented");
      //res.status(500).send({
        //message: "Error updating Tutorial with id=" + id
      //});
    });
  });
}
