const electron = require("electron");
const { app, BrowserWindow } = electron;
const express = require("express");
const body = require("body-parser");
const fs = require("fs");
const backend = express();

let win = null;

backend.use(express.static(__dirname + "/dist"));
backend.use(body.json());

backend.post("/settings", (req, res) => {
  var config = JSON.parse(
    fs.readFileSync(__dirname + "/dist/config.json", "utf8")
  );
  config.backend = req.body.backend;
  fs.writeFile(__dirname + "/dist/config.json", JSON.stringify(config), err => {
    if (err) throw err;
  });
  res.end();
});

let server = backend.listen(0, () => {
  console.log("LISTEN")
  app.whenReady().then(() => {
    createWindow()
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  });

});

app.on("window-all-closed", () => {
  if (process.platform != "darwin") {
    app.quit();
  }
});

function createWindow() {
  console.log("CREATE WINDOW")
  const WINDOW_WIDTH = 1200;
  const WINDOW_HEIGHT = 680;

  let bounds = electron.screen.getPrimaryDisplay().bounds;
  let x = bounds.x + (bounds.width - WINDOW_WIDTH) / 2;
  let y = bounds.y + (bounds.height - WINDOW_HEIGHT) / 2;

  win = new BrowserWindow({
    width: WINDOW_WIDTH,
    height: WINDOW_HEIGHT,
    x: x,
    y: y,
    icon: __dirname + "/dist/static/icon_48.png"
  });

  win.setMenuBarVisibility(false);

  let session = win.webContents.session;
  /* session.clearCache(() => {
     let url = "http://localhost:" + server.address().port;
     console.log(url)
     win.loadURL(url);
   });
 */

  let url = "http://localhost:" + server.address().port;
  console.log(url)
  win.loadURL(url);

  win.on("closed", () => {
    win = null;
  });
}
