const { findRealEstateByAgencyId } = require("../helpers/db/realEstate");
const {
  bulkUpsertKiviPhotos,
  findPhotosForKiviAd
} = require("../helpers/db/kiviOriginalAdsPhotos");
const { currentKiviRealEstate } = require("../helpers/url");
const {
  notifyForNewRealEstates,
  notifyForNewAdPublish
} = require("../services/notificationService");
const validate = require("validate.js");

const {
  AD_CATEGORY,
  FURNISHING_TYPE,
  ACCESS_ROAD_TYPE,
  HEATING_TYPE
} = require("../common/enums");
const { APP_URL } = require("../config/appConfig");

const {
  BASIC_BOOLEAN_PUBLISH,
  BASIC_SEGMENT_PUBLISH,
  ADDITIONAL_BOOLEAN_PUBLISH,
  ADDITIONAL_SEGMENT_PUBLISH,
  BASIC_INPUT_PUBLISH,
  ADDITIONAL_INPUT_PUBLISH
} = require("../common/publishEnums");

const getPublishInputs = async (req, res) => {
  const kiviOriginal = await currentKiviRealEstate(req);

  const realEstate = await findRealEstateByAgencyId(
    kiviOriginal.dataValues.kiviAdId
  );

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

  const pageTitle = "Podaci o nekretnini";

  const {
    price,
    area,
    adType,
    realEstateType,
    locationLat,
    locationLong,
    accessRoadType,
    heatingType,
    balcony,
    newBuilding,
    elevator,
    recentlyAdapted,
    gardenSize,
    numberOfRooms,
    numberOfFloors,
    floor,
    water,
    electricity,
    drainageSystem,
    registeredInZkBooks,
    parking,
    garage,
    gas,
    antiTheftDoor,
    airCondition,
    phoneConnection,
    cableTV,
    internet,
    basementAttic,
    storeRoom,
    videoSurveillance,
    alarm,
    suitableForStudents,
    includingBills,
    animalsAllowed,
    pool,
    exchange,
    urbanPlanPermit,
    buildingPermit,
    furnishingType,
    shortDescription,
    streetName,
    title,
    longDescription
  } = realEstate;

  const email = kiviOriginal.dataValues.email;
  //If email is not empty - has string value, then proces of publishing has been conducted alredy
  //That means user is editing existing real estate ad not publishing new one
  let editingRealEstate = false;
  if (email) {
    editingRealEstate = true;
  }
  //If we are editing real estate ad we need to fetch and show images on server
  const urlGooglePrefix =
    "https://storage.cloud.google.com/marketalarm-photos/";
  let realEstatePhotosUrls = [];
  if (editingRealEstate) {
    const realEstatePhotosData = await findPhotosForKiviAd(
      kiviOriginal.dataValues.kiviAdId
    );
    realEstatePhotosData.map(row => {
      realEstatePhotosUrls.push(urlGooglePrefix + row.dataValues.photoUrl);
    });
  } else {
    realEstatePhotosUrls.push(false);
  }

  const category = AD_CATEGORY[realEstateType] || AD_CATEGORY.FLAT;

  // TODO: Maybe this is slow, pay attention to this
  const filterInputs = filterObject => {
    const filterCategories = filterObject.categoriesToShow;
    return filterCategories.indexOf(category) !== -1;
  };
  //Boolean inputs to be shown on Basic Data tab
  const basicBooleanPublishInputs = BASIC_BOOLEAN_PUBLISH.filter(filterInputs);
  const basicBooleanPublishValues = {
    balcony,
    elevator,
    newBuilding,
    recentlyAdapted
  };
  //Boolean inputs to be shown on Additional Data tab
  const additionalBooleanPublishInputs = ADDITIONAL_BOOLEAN_PUBLISH.filter(
    filterInputs
  );
  const additionalBooleanPublishValues = {
    water,
    electricity,
    drainageSystem,
    registeredInZkBooks,
    parking,
    garage,
    gas,
    antiTheftDoor,
    airCondition,
    phoneConnection,
    cableTV,
    internet,
    basementAttic,
    storeRoom,
    videoSurveillance,
    alarm,
    suitableForStudents,
    includingBills,
    animalsAllowed,
    pool,
    exchange,
    urbanPlanPermit,
    buildingPermit
  };
  //Segment select inputs to be shown on Basic Data tab
  const basicSegmentSelectInputs = BASIC_SEGMENT_PUBLISH.filter(filterInputs);
  const basicSegmentSelectValues = {
    furnishingType
  };
  //Segment select inputs to be shown on Additional Data tab
  const additionalSegmentSelectInputs = ADDITIONAL_SEGMENT_PUBLISH.filter(
    filterInputs
  );
  const additionalSegmentSelectValues = {
    accessRoadType,
    heatingType
  };
  //Input text type inputs to be shown on Basic Data tab
  const basicInputInputs = BASIC_INPUT_PUBLISH.filter(filterInputs);
  const basicInputValues = {
    price,
    area,
    gardenSize,
    numberOfRooms,
    numberOfFloors,
    floor,
    title,
    shortDescription,
    streetName
  };
  //Input type textare to be shown on Additional Data
  const additionalInputInputs = ADDITIONAL_INPUT_PUBLISH.filter(filterInputs);
  const additionalInputValues = {
    longDescription
  };

  res.render("publishRealEstate", {
    title: pageTitle,
    basicBooleanPublishInputs,
    basicBooleanPublishValues,
    additionalBooleanPublishInputs,
    additionalBooleanPublishValues,
    basicSegmentSelectInputs,
    basicSegmentSelectValues,
    additionalSegmentSelectInputs,
    additionalSegmentSelectValues,
    basicInputInputs,
    basicInputValues,
    additionalInputInputs,
    additionalInputValues,
    validate: validate,
    email,
    locationLat, //: locationLat || 0,
    locationLong, //: locationLong || 0,
    editingRealEstate,
    realEstatePhotosUrls
  });
};

const postPublishInputs = async (req, res) => {
  const kiviOriginal = await currentKiviRealEstate(req);

  if (!kiviOriginal || !kiviOriginal.kiviAdId) {
    res.render("notFound", { title: " " });
    return;
  }
  const realEstate = await findRealEstateByAgencyId(kiviOriginal.kiviAdId);

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

  const editingRealEstate = req.body.editingRealEstate === "true";

  console.log("Editing real estate:", editingRealEstate);

  const nextStepPage = editingRealEstate
    ? req.query.nextStep || "/uspjesnaizmjena"
    : req.query.nextStep || "/uspjesnaobjava";
  //Request body
  //console.log("Body:", req.body);

  const balcony = req.body.balcony === "on";
  const elevator = req.body.elevator === "on";
  const newBuilding = req.body.newBuilding === "on";
  const recentlyAdapted = req.body.recentlyAdapted === "on";
  const water = req.body.water === "on";
  const electricity = req.body.electricity === "on";
  const drainageSystem = req.body.drainageSystem === "on";
  const registeredInZkBooks = req.body.registeredInZkBooks === "on";
  const parking = req.body.parking === "on";
  const garage = req.body.garage === "on";
  const gas = req.body.gas === "on";
  const antiTheftDoor = req.body.antiTheftDoor === "on";
  const airCondition = req.body.airCondition === "on";
  const phoneConnection = req.body.phoneConnection === "on";
  const cableTV = req.body.cableTV === "on";
  const internet = req.body.internet === "on";
  const basementAttic = req.body.basementAttic === "on";
  const storeRoom = req.body.storeRoom === "on";
  const videoSurveillance = req.body.videoSurveillance === "on";
  const alarm = req.body.alarm === "on";
  const suitableForStudents = req.body.suitableForStudents === "on";
  const includingBills = req.body.includingBills === "on";
  const animalsAllowed = req.body.animalsAllowed === "on";
  const pool = req.body.pool === "on";
  const exchange = req.body.exchange === "on";
  const urbanPlanPermit = req.body.urbanPlanPermit === "on";
  const buildingPermit = req.body.buildingPermit === "on";

  const furnishingType = req.body.furnishingType;
  //VALIDACIJA TAKO POTVRDITI DA JE ISPRAVNA VRIJEDNOST
  /* if (!FURNISHING_TYPE[furnishingType]) {
    res.render("notFound", { title: " Greška !" });
    return;
  } */
  const accessRoadType = req.body.accessRoadType;
  /*if (!ACCESS_ROAD_TYPE[accessRoadType]) {
    res.render("notFound", { title: " Greška !" });
    return;
  } */
  const heatingType = req.body.heatingType;
  /*if (!HEATING_TYPE[heatingType]) {
    res.render("notFound", { title: " Greška !" });
    return;
  }*/

  const price = parseFloat(req.body.price) || null;
  const area = parseFloat(req.body.area) || null;
  const gardenSize = parseFloat(req.body.gardenSize) || null;
  const numberOfRooms = parseInt(req.body.numberOfRooms) || null;
  const numberOfFloors = parseInt(req.body.numberOfFloors) || null;
  const floor = parseInt(req.body.floor) || null;
  const title = req.body.title || "";
  const shortDescription = req.body.shortDescription || "";
  const streetName = req.body.streetName || "";
  const longDescription = req.body.longDescription || "";

  const locationLat = req.body.lat || null;
  const locationLong = req.body.lng || null;
  //Contact email saved in other table
  const contactEmail = req.body.email || "";
  //Image urls are stored in new table
  const imageUrls =
    req.body.imageUrls.split("|").filter(url => url !== "") || [];

  const imageUrlsData = imageUrls.map(url => {
    return {
      kiviAdId: kiviOriginal.kiviAdId,
      photoUrl: url
    };
  });
  const savedImageUrls = await bulkUpsertKiviPhotos(imageUrlsData);

  realEstate.balcony = balcony;
  realEstate.elevator = elevator;
  realEstate.newBuilding = newBuilding;
  realEstate.recentlyAdapted = recentlyAdapted;
  realEstate.water = water;
  realEstate.electricity = electricity;
  realEstate.drainageSystem = drainageSystem;
  realEstate.registeredInZkBooks = registeredInZkBooks;
  realEstate.parking = parking;
  realEstate.garage = garage;
  realEstate.gas = gas;
  realEstate.antiTheftDoor = antiTheftDoor;
  realEstate.airCondition = airCondition;
  realEstate.phoneConnection = phoneConnection;
  realEstate.cableTV = cableTV;
  realEstate.internet = internet;
  realEstate.basementAttic = basementAttic;
  realEstate.storeRoom = storeRoom;
  realEstate.videoSurveillance = videoSurveillance;
  realEstate.alarm = alarm;
  realEstate.suitableForStudents = suitableForStudents;
  realEstate.includingBills = includingBills;
  realEstate.animalsAllowed = animalsAllowed;
  realEstate.pool = pool;
  realEstate.exchange = exchange;
  realEstate.urbanPlanPermit = urbanPlanPermit;
  realEstate.buildingPermit = buildingPermit;

  realEstate.furnishingType = furnishingType;
  realEstate.accessRoadType = accessRoadType;
  realEstate.heatingType = heatingType;

  realEstate.price = price;
  realEstate.area = area;
  realEstate.gardenSize = gardenSize;
  realEstate.numberOfRooms = numberOfRooms;
  realEstate.numberOfFloors = numberOfFloors;
  realEstate.floor = floor;
  realEstate.title = title;
  realEstate.shortDescription = shortDescription;
  realEstate.streetName = streetName;

  realEstate.longDescription = longDescription;

  realEstate.locationLat = locationLat;
  realEstate.locationLong = locationLong;

  kiviOriginal.email = contactEmail;

  //console.log("realEstate", realEstate);

  await realEstate.save();

  await kiviOriginal.save();

  //Calling function to notify real estate owner that ads is published or edited on Kivi page after 1 sec
  setTimeout(
    notifyForNewAdPublish,
    1000,
    realEstate,
    kiviOriginal,
    editingRealEstate
  );
  //Calling function to notify users of new real estate (or edited realestate) after 2 min
  setTimeout(notifyForNewRealEstates, 1000 * 60 * 2, [realEstate]);

  res.redirect(nextStepPage);
};

module.exports = {
  getPublishInputs,
  postPublishInputs
};
