const { splitSite } = require("../middlewares");
const db = require("../models");
const RoutePathTemplate = db.route_path_template;
exports.createRoutePathTemplate = (req, res) => {
  // Validate request
  if (!req.body.name) {
    res.status(400).send({ message: "Content can not be empty!" });
    return;
  }
  const site = splitSite.findSiteNumber(req);
  // Create a Route Template
  const routePathTemplate = new RoutePathTemplate({
    name: req.body.name,
    vehicle: req.body.vehicle,
    driver: req.body.driver,
    type: req.body.type,
    route_customer_list: req.body.route_customer_list || [],
    status: req.body.status || 'active',
    site
  });
  // Save Route Template in the database
  routePathTemplate
    .save(routePathTemplate)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Route Template."
      });
    });
};
// Retrieve all Routes Templates from the database.
exports.getAllRoutesTemplates = (req, res) => {
  var condition = {};
  condition = splitSite.splitSiteGet(req, condition);
  RoutePathTemplate.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Routes."
      });
    });
};

// Get One Route Template by Id
exports.getRouteTemplate = (req, res) => {

};

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

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