const { splitSite } = require("../middlewares");
const db = require("../models");
const MsgCustomTemplate = db.msg_custom_template;

// Create a new template
exports.create = (req, res) => {
  if (!req.body.title) {
    res.status(400).send({ message: "Title can not be empty!" });
    return;
  }
  const site = splitSite.findSiteNumber(req);
  const template = new MsgCustomTemplate({
    title: req.body.title,
    chinese: req.body.chinese || '',
    english: req.body.english || '',
    status: req.body.status || 'active',
    create_by: req.body.create_by,
    create_date: req.body.create_date || new Date(),
    edit_by: req.body.edit_by,
    edit_date: req.body.edit_date,
    site
  });
  template.save(template)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || "Some error occurred while creating the template."
      });
    });
};

// Retrieve all templates
exports.getAll = (req, res) => {
  var condition = {};
  condition = splitSite.splitSiteGet(req, condition);
  MsgCustomTemplate.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || "Some error occurred while retrieving templates."
      });
    });
};

// Get one template by id
exports.getOne = (req, res) => {
  const id = req.params.id;
  MsgCustomTemplate.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found template with id " + id });
      else res.send(data);
    })
    .catch(err => {
      res.status(500).send({ message: "Error retrieving template with id=" + id });
    });
};

// Update a template by id
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;
  MsgCustomTemplate.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({ message: `Cannot update template with id=${id}.` });
      } else res.send({ success: true, message: "Template was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({ success: false, message: "Error updating template with id=" + id });
    });
};

// Delete a template by id
exports.remove = (req, res) => {
  const id = req.params.id;
  MsgCustomTemplate.findByIdAndRemove(id)
    .then(data => {
      if (!data) {
        res.status(404).send({ message: `Cannot delete template with id=${id}.` });
      } else {
        res.send({ message: "Template was deleted successfully!" });
      }
    })
    .catch(err => {
      res.status(500).send({ message: "Could not delete template with id=" + id });
    });
};
