const { currentSearchRequest } = require("../helpers/url");

const getLocation = async (req, res) => {
  const title = "Odaberite lokaciju";
  const nextStep = req.query.nextStep || "/";

  res.render("location", {
    nextStep,
    title
  });
};

const postLocation = async (req, res) => {
  let searchRequest = await currentSearchRequest(req);

  if (!searchRequest || !searchRequest.dataValues) {
    res.render("notFound", { title: " " });
    return;
  }

  const northWest = [req.body.west, req.body.north];
  const northEast = [req.body.east, req.body.north];
  const southEast = [req.body.east, req.body.south];
  const southWest = [req.body.west, req.body.south];

  const locationInputValue =
    req.body.locationInput && req.body.locationInput.length > 0
      ? req.body.locationInput
      : null;

  searchRequest.areaToSearch = {
    type: "Polygon",
    coordinates: [[northWest, northEast, southEast, southWest, northWest]],
    crs: { type: "name", properties: { name: "EPSG:4326" } }
  };

  let locationInputData;
  if (req.body.locationInputData) {
    try {
      locationInputData = JSON.parse(req.body.locationInputData);
    } catch (e) {
      locationInputData = null;
    }
  }

  await searchRequest.save();

  const nextStepPage = req.query.nextStep || "filteri";
  const nextStepUrl = `/${nextStepPage}/${searchRequest.id}`;

  res.redirect(nextStepUrl);
};

module.exports = {
  getLocation,
  postLocation
};
