const { splitSite } = require("../middlewares");
const db = require("../models");
const Label = db.label;

// Create a new Label Item
exports.createNewLabel = (req, res) => {
  // Validate request
  if (!req.body.label_name) {
    res.status(400).send({ message: "Name can not be empty!" });
    return;
  }
  const site = splitSite.findSiteNumber(req);
	// Create an Label Item
  const label = new Label({
		label_name: req.body.label_name,
		label_color: req.body.label_color,
		status: 'active',
    site
  });
  // Save label Item in the database
  label
    .save(label)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Label Record."
      });
    });
};

// Retrive all Label Records from database.
exports.getAllLabels = (req, res) => {
	var params = req.query;
	var condition = {};
	if (params.status) {
		condition.status = params.status;
	}
	 
	condition = splitSite.splitSiteGet(req, condition);
	Label.find(condition)
		.then(data => {
			res.send(data);
		})
		.catch(err => {
			res.status(500).send({
				message:
					err.message || "Some error occurred while retrieving Labels."
			});
		});
};

// Update a Label by the id in the request
exports.updateLabel = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const id = req.params.id;
  Label.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot update Label with id=${id}. Maybe Label was not found!`
        });
      } else res.send({ success: true, message: "Label was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error updating Label with id=" + id
      });
    });
};

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