const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const layout = require("express-layout");
const compression = require("compression");
const forceSSL = require("./app/helpers/forceSSL");

const { Storage } = require("@google-cloud/storage");
const validate = require("validate.js");
const cors = require("cors");

const {
  APP_PORT,
  CRAWLER_INTERVAL,
  STOP_CRAWLER
} = require("./app/config/appConfig");
const routes = require("./app/routes");
const { crawlAll } = require("./app/crawler/crawl");
const { checkUpNotify } = require("./app/services/notificationService");
const {
  notifyForNewRealEstates
} = require("./app/services/notificationService");

const app = express();

app.use(cors());

app.use(forceSSL());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.set("views", path.join(__dirname, "/app/views"));
app.set("view engine", "ejs");
app.use(layout());

app.use(compression());
app.use("/", routes);

app.use("/assets", express.static("./app/public"));

app.listen(APP_PORT, () =>
  console.log(`Example app listening on port ${APP_PORT}!`)
);

let crawlerRunning = STOP_CRAWLER;
const crawl = () => {
  if (!crawlerRunning) {
    crawlerRunning = true;
    crawlAll().then(newRealEstates => {
      crawlerRunning = false;
      notifyForNewRealEstates(newRealEstates);
    });
  }
};

setInterval(crawl, CRAWLER_INTERVAL * 1000);

setInterval(checkUpNotify, 1000 * 60 * 60 * 24);

//Google storage req
const PROJECT_ID = "marketalarm";
const KEY_FILENAME = ""; //relative path
const BUCKET_NAME = "marketalarm-photos";
const storage = new Storage();

const bucket = storage.bucket(BUCKET_NAME);

app.get("/generateSignedURL", (req, res) => {
  async function generateSignedUrl() {
    // console.log("Started server function!");

    const options = {
      //Tried to define Google ID and private key while debugging
      version: "v2", //tried v4 also
      action: "write",
      contentType: "image/*", //tried without and with specific image/png ex.
      expires: Date.now() + 86400000
    };
    const filename = req.query.filename;

    // console.log("Filename: ", filename);
    // console.log("Bucket name:", bucket.name);

    const [url] = await bucket.file(filename).getSignedUrl(options);

    //console.log(`The signed url is ${url}.`);

    res.status(200).send(url);
  }
  generateSignedUrl().catch(console.error);
});
