// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
const fs = require("fs")
// if (process.platform === 'linux') {
//   app.commandLine.appendSwitch('enable-transparent-visuals');
//   app.commandLine.appendSwitch('disable-gpu');
// }

var debug_flag = false;
//debug_flag = true;

//二重起動の防止
const doubleboot = app.requestSingleInstanceLock();
if(!doubleboot){
  app.quit();
}

global.sendghostasset = null;

// ウィンドウ位置保存用ファイル
let boundsFile = path.join(
  app.getPath('userData'), 'bounds.json'
);
//-> 保存しておいたウィンドウ位置の取得
let bounds = {};
try {
  bounds = JSON.parse(
    fs.readFileSync(boundsFile, 'utf8')
  );
} catch (e) {
  bounds = {x: 500, y: 500};
}

let mainWindow, balloonWindow, menuWindow;
function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow(Object.assign(
    bounds, {
    width: (debug_flag ? 1400 : 140),
    height: (debug_flag ? 800 : 140),
    transparent: true,
    frame: false,
    toolbar: false,
    hasShadow: false,
    resizable: false,
    icon: path.join(__dirname, 'ghost/neko/asset/default.png'),
    alwaysOnTop: true,
    useContentSize: true,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true
    }
  }))

  ipcMain.on("ghostsize-message", (event, arg) => {
    var b = mainWindow.getBounds();
    bounds.x = b.x;
    bounds.y = b.y;
    //console.log(Object.assign(bounds, JSON.parse(arg)));
    if (!debug_flag) {
      mainWindow.setBounds(Object.assign(bounds, JSON.parse(arg)));
    }
    event.reply("ghostsize-reply", "ghostsize : " + arg)
  })

  ipcMain.on("ghostconf-message", (event, arg) => {
    //event.reply("ghostconf-reply", arg);
    mainWindow.webContents.send("_ghostconf-message", arg);
  })

  ipcMain.on("ghostquit-message", (event, arg) => {
    app.quit();
  });

  setInterval(function() {
    var bb = balloonWindow.getBounds();
    var b = mainWindow.getBounds();
    bb.x = b.x;
    bb.y = b.y - b.height;
    bb.width = 300;
    bb.heght = 200;
    //console.log(b.x, b.y);
    balloonWindow.setBounds(bb);
  }, 500);

  //mainWindow.setIgnoreMouseEvents(true);

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  mainWindow.on("close", function() {
    balloonWindow.destroy();
    menuWindow.destroy();
    app.quit();
  });
  mainWindow.on("minimize", function() {
    if (!balloonWindow.isMinimized()) {
      balloonWindow.minimize();
    }
    if (!menuWindow.isMinimized()) {
      menuWindow.minimize();
    }
  });
  mainWindow.on("restore", function() {
    if (balloonWindow.isMinimized()) {
      balloonWindow.restore();
    }
  });

  // Open the DevTools.
  if (debug_flag) {
    mainWindow.webContents.openDevTools()
  }
}

function createBalloonWindow () {
  // Create the browser window.
  balloonWindow = new BrowserWindow(Object.assign(
    bounds, {
      width: (debug_flag ? 1400 : 140),
      height: (debug_flag ? 800 : 140),
      transparent: true,
      frame: false,
      toolbar: false,
      hasShadow: false,
      resizable: false,
      //icon: path.join(__dirname, 'icon/icon.png'),
      alwaysOnTop: true,
      useContentSize: true,
      parent: mainWindow,
      webPreferences: {
        nodeIntegration: true,
        preload: path.join(__dirname, 'preload_balloon.js'),
        contextIsolation: true
      }
    }))
  balloonWindow.setIgnoreMouseEvents(true);
  // and load the index.html of the app.
  balloonWindow.loadFile('balloon.html')

  ipcMain.on("ghostasset-message", (event, arg) => {
    mainWindow.webContents.send("_ghostasset-message", arg);
  });

  balloonWindow.on("close", function() {
    mainWindow.destroy();
    menuWindow.destroy();
    app.quit();
  })
  balloonWindow.on("minimize", function() {
    if (!mainWindow.isMinimized()) {
      mainWindow.minimize();
    }
    if (!menuWindow.isMinimized()) {
      menuWindow.minimize();
    }
  });
  balloonWindow.on("restore", function() {
    if (mainWindow.isMinimized()) {
      mainWindow.restore();
    }
  });

  // Open the DevTools.
  if (debug_flag) {
    balloonWindow.webContents.openDevTools()
  }
}

function createMenuWindow () {
  menuWindow = new BrowserWindow({
    width: (debug_flag ? 1400 : 300),
    height: 400,
    transparent: false,
    frame: true,
    toolbar: false,
    hasShadow: false,
    //show: false,
    resizable: false,
    //icon: path.join(__dirname, 'icon/icon.png'),
    alwaysOnTop: true,
    useContentSize: true,
    //parent: mainWindow,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload_menu.js'),
      contextIsolation: true
    }
  });
  menuWindow.setMenu(null);
  menuWindow.loadFile('menu.html');
  menuWindow.once("ready-to-show", function() {
    menuWindow.minimize();
  });
  menuWindow.on("close", function(e) {
    balloonWindow.destroy();
    mainWindow.destroy();
    app.quit();
    //e.preventDefault();
    //menuWindow.minimize();
  });
  // Open the DevTools.
  if (debug_flag) {
    menuWindow.webContents.openDevTools()
  }
}


// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  setTimeout(function() {
    createWindow();
    createBalloonWindow();
    createMenuWindow();
  }, 1000);
  //createWindow()
  app.on('activate', function () {

    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})



app.on('before-quit', function() {
  var b = mainWindow.getBounds();
  bounds.x = b.x;
  bounds.y = b.y;
  fs.writeFileSync(
    boundsFile, JSON.stringify(bounds)
  );
})


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})


// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
