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

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

  //Check if location data already exists (active request)
  //If it does then  get location is called through edit field query
  //and map should show already selected location not initial map
  let selectedLatLngBounds = {};
  let boundsSelected = false;

  const searchRequest = await currentSearchRequest(req);

  if (!searchRequest || !searchRequest.dataValues) {
    res.render("notFound", { title: " " });
    return;
  }
  const selectedArea = searchRequest.areaToSearch;
  const sw = selectedArea.coordinates[0][3];
  const ne = selectedArea.coordinates[0][1];

  if (sw[0] && ne[0]) {
    selectedLatLngBounds = {
      swLat: sw[1],
      swLng: sw[0],
      neLat: ne[1],
      neLng: ne[0]
    };
    boundsSelected = true;
  }

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

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
};
