const { currentSearchRequest } = require("../helpers/url");
const { AD_CATEGORY, AD_TYPE } = require("../common/enums");

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

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

  const title = "Filteri za pretraživanje";

  const {
    adType,
    realEstateType,
    priceMin,
    priceMax,
    sizeMin,
    sizeMax,
    gardenSizeMin,
    gardenSizeMax
  } = searchRequest;
  const category = AD_CATEGORY[realEstateType] || AD_CATEGORY.FLAT;

  const {
    hasGardenSize,
    priceSliderOptionsSale,
    priceSliderOptionsRent,
    sizeSliderOptions,
    gardenSizeSliderOptions
  } = category;

  let priceSliderOptions;
  if (adType === AD_TYPE.AD_TYPE_SALE.stringId) {
    priceSliderOptions = Object.assign({}, priceSliderOptionsSale);
  } else if (adType === AD_TYPE.AD_TYPE_RENT.stringId) {
    priceSliderOptions = Object.assign({}, priceSliderOptionsRent);
  } else {
    res.render("notFound", { title: " " });
    return;
  }

  if (priceMin || priceMax) {
    priceSliderOptions.start = [priceMin, priceMax];
  }

  if (sizeMin || sizeMax) {
    sizeSliderOptions.start = [sizeMin, sizeMax];
  }

  if (gardenSizeSliderOptions && (gardenSizeMin || gardenSizeMax)) {
    gardenSizeSliderOptions.start = [gardenSizeMin, gardenSizeMax];
  }

  res.render("realEstateFilters", {
    title,
    hasGardenSize,
    priceSliderOptions: JSON.stringify(priceSliderOptions),
    sizeSliderOptions: JSON.stringify(sizeSliderOptions),
    gardenSizeSliderOptions: JSON.stringify(gardenSizeSliderOptions)
  });
};

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

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

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

  const priceMin = parseInt(req.body.priceMin) || 0;
  const priceMax = parseInt(req.body.priceMax) || 0;
  const sizeMin = parseInt(req.body.sizeMin) || 0;
  const sizeMax = parseInt(req.body.sizeMax) || 0;

  //TODO: Filter validation

  searchRequest.priceMin = priceMin;
  searchRequest.priceMax = priceMax;
  searchRequest.sizeMin = sizeMin;
  searchRequest.sizeMax = sizeMax;

  if (
    req.body.gardenSizeMin !== undefined &&
    req.body.gardenSizeMax !== undefined
  ) {
    const gardenSizeMin = parseInt(req.body.gardenSizeMin);
    const gardenSizeMax = parseInt(req.body.gardenSizeMax);

    //TODO: Filter validation

    searchRequest.gardenSizeMin = gardenSizeMin;
    searchRequest.gardenSizeMax = gardenSizeMax;
  }

  await searchRequest.save();

  res.redirect(nextStepUrl);
};

module.exports = {
  getFilters,
  postFilters
};
