//window.addEventListener('DOMContentLoaded', () => {
window.addEventListener('load', () => {

  const path = require('path')
  const { ipcRenderer } = require('electron')
  // const { contextBridge } = require('electron')
  // contextBridge.exposeInMainWorld("electron", {
  //   ipcRenderer: ipcRenderer
  // });

  var balloon = document.getElementById("balloon");
  var balloon_ = document.getElementById("balloon_");
  var gtalk;
  var gtalkqueue = [];

  var GHOST_CONF = false;
  var GHOST_P = false;
  var TALK, GREET, GINPUT, TIMETALK;
  var INTERVAL = false;
  var USERNAME = false;
  var teiji = "";

  function clearqueue() {
    gtalkqueue = [];
    if (timeout_talk) { clearTimeout(timeout_talk); }
    if (timeout_hide) { clearTimeout(timeout_hide); }
    if (timeout_newtalk) { clearTimeout(timeout_newtalk); }
    hideballoon();
  }

  ipcRenderer.on('userinput-message', (event, arg) => {
    clearqueue();
    ghost_talk("input", true, arg);
  });

  // 特定の時間で喋る & 定時通知
  var ptimestr = "";
  var timer = setInterval(function() {
    var d = new Date();
    var m = ~~(Math.floor(d.getMinutes()/5)*5);
    var timestr = ("00" + d.getHours()).slice(-2) + ":" + ("00" + m).slice(-2);
    if (timestr != ptimestr) {
      ptimestr = timestr;
      //ipcRenderer.send("ghost-console-message", timestr);
      if (timestr == TEIJI) {
        ghost_talk("time", true, "", TTEIJI);
      } else {
        var s = TIMETALK(timestr);
        if (s) {
          clearqueue();
          ghost_talk("time", true, "", s);
        }
      }
    }
  }, 180000);

  // インターバル変更時
  ipcRenderer.on('interval-change-message', (event, arg) => {
    INTERVAL = JSON.parse(arg).interval;
  });
  // 定時変更時
  ipcRenderer.on('teiji-change-message', (event, arg) => {
    TEIJI = JSON.parse(arg).teiji;
  });
  // 設定変更時
  ipcRenderer.on("confchange-message", (e, arg) => {
    clearqueue();
    ghost_talk("time", true, "", {type: "normal", talk: [[0, arg]]});
  });

  balloon.style.display = "none";
  balloon_.style.display = "none";

  function change_ghost_size() {
    balloon.style.minWidth = GHOST_CONF.balloon.minWidth + "px";
    balloon.style.marginLeft = GHOST_CONF.balloon.marginLeft + "px";
    balloon_.style.marginLeft = ~~(GHOST_CONF.ghost.size*0.5
                                   - GHOST_CONF.balloon.trisize) + "px";
    balloon_.style.marginBottom = GHOST_CONF.balloon.marginBottom + "px";
  }

  function mkrand(max) {
    return Math.floor(Math.random()*(max+1));
  }

  function showballoon(str) {
    balloon.innerHTML = str.replace(/%username%/g, USERNAME ? USERNAME : "ユーザー");
    balloon.style.display = "block";
    balloon_.style.display = "block";
  }
  function hideballoon() {
    balloon.innerHTML = "";
    balloon.style.display = "none";
    balloon_.style.display = "none";
  }

  var timeout_talk;
  var timeout_hide;
  var timeout_newtalk;
  function _ghost_talk(str, wait, end, ast, nowait) {
    timeout_talk = setTimeout(function() {
      ipcRenderer.send('talk-asset-message', ast);
      showballoon(str);
      if (end) {
        timeout_hide = setTimeout(function() {
          hideballoon();
          if (gtalkqueue.length) {
            var g = gtalkqueue.shift();
            _ghost_talk(g[0], g[1], g[2], g[3]);
          } else {
            ghost_talk("normal");
          }
        }, end);
      } else {
        if (gtalkqueue.length) {
          var g = gtalkqueue.shift();
          _ghost_talk(g[0], g[1], g[2], g[3]);
        } else {
          timeout_newtalk = setTimeout(function() {
            ghost_talk("normal");
          }, INTERVAL);
        }
      }
    }, nowait ? 0 : wait);
  }

  function ghost_talk(ttype, nowait, uinput, _tk) {
    var tk;
    switch (ttype) {
    case "normal":
      tk = TALK[mkrand(TALK.length-1)];
      break;
    case "greet":
      tk = GREET[mkrand(GREET.length-1)];
      break;
    case "input":
      var s = GINPUT(uinput);
      if (s) {
        tk = {type: "normal", talk: [[0, s]]}
      } else {
        tk = TALK[mkrand(TALK.length-1)];
      }
      break;
    case "time":
      tk = _tk;
    }
    switch (tk.type) {
    case "normal":
      for (var i = 0; i < tk.talk.length; i++) {
        gtalkqueue.push([
          tk.talk[i][1],
          (i == 0 && nowait) ? 0
            : (i == 0 ? INTERVAL
               : tk.talk[i][0]*tk.talk[i-1][1].length),
          i == tk.talk.length - 1
            ? tk.talk[i][1].length*GHOST_CONF.balloon.disptime
            : 0,
          tk.talk[i].length > 2 ? tk.talk[i][2] : "default"
        ]);
      }
      var q = gtalkqueue.shift();
      _ghost_talk(q[0], q[1], q[2], q[3]);
      break;
    }
  }

  // 準備OKフラグ送信
  ipcRenderer.send('balloon-ready-message', "1");
  // ゴーストの種類受信 (準備OKフラグの返信として受信)
  ipcRenderer.on('balloon-ready-reply', (e, arg) => {
    var a = JSON.parse(arg);
    GHOST_CONF = require(path.join(__dirname, "..", "ghost", a.ghost, "config.js"));
    GHOST_P = require(path.join(__dirname, "..", "ghost", a.ghost, "talk", "default.js"));
    TALK = GHOST_P.TALK;
    GREET = GHOST_P.GREET;
    GINPUT = GHOST_P.GINPUT;
    TIMETALK = GHOST_P.TIMETALK;
    TTEIJI = GHOST_P.TTEIJI;
    INTERVAL = a.interval;
    TEIJI = a.teiji;
    USERNAME = a.username;
    change_ghost_size();
    ghost_talk("greet", false);
  });

})
