const { splitSite } = require("../middlewares");
const db = require("../models");
const CenterPhone = db.center_phone;
// Create and Save a new Center Phone
exports.createCenterPhone = (req, res) => {
  // Create a Center Phone
  const site = splitSite.findSiteNumber(req);
  const centerPhone = new CenterPhone({
    activated: true,
    phone_title: req.body.phone_title || '',
    phone_number: req.body.phone_number || '',
    site
  });

  // Save centerPhone in the database
  centerPhone
    .save(centerPhone)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Center phone."
      });
    });
};
// Retrieve all Phones from the database.
exports.getAllCenterPhones = (req, res) => {
  var params = req.query;
  var condition = {};
  if (params) {
    condition = splitSite.splitSiteGet(req, params);
    if (params.activated) {
      condition.activated = params.activated;
    }
  }
  CenterPhone.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving phones."
      });
    });
};
// Get One Phone by Id
exports.getCenterPhone = (req, res) => {
  const id = req.params.id;
  CenterPhone.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Center Phone with id " + id });
      else res.send(data);
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Center Phone with id=" + id });
    });
};
// Update a CenterPhone by the id in the request
exports.updateCenterPhone = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const id = req.params.id;
  CenterPhone.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot update Center Phone with id=${id}. Maybe Center Phone was not found!`
        });
      } else res.send({ success: true, message: "Center Phone was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error" + (err.message || "") + "updating Center Phone with id=" + id
      });
    });
};

