const Overlay = require('./discord_overlay2.node');

const fs = require('fs');
const path = require('path');
const {ipcRenderer} = require('electron');
const {
  OFFSCREEN_CURSOR_CHANGED,
  OFFSCREEN_INPUT_EVENT,
  OFFSCREEN_START_DRAG,
  OFFSCREEN_STOP_DRAG,
  OFFSCREEN_WINDOW_UPDATE,
} = require('./events');

Overlay.initializeMainContext();

function cleanupHookInitLog(pid) {
  if (!pid) {
    return;
  }

  const log = path.resolve(__dirname, `overlay.init.${pid}.log`);
  if (fs.existsSync(log)) {
    try {
      fs.unlinkSync(log);
    } catch (e) {}
  }
}

let url;
let attachCallback;
let clickZoneCallback;

Overlay.setAttachCallback = function(callback) {
  attachCallback = callback;
};

Overlay.setClickZoneCallback = function(callback) {
  clickZoneCallback = callback;
};

Overlay.setEventHandler((session, pid, event) => {
  if (event.message === 'graphics_info') {
    ipcRenderer.send(OFFSCREEN_WINDOW_UPDATE, {
      session,
      width: event.width,
      height: event.height,
      frameBufferServer: event.frame_buffer_server,
    });
  } else if (event.message === 'input_event') {
    ipcRenderer.send(OFFSCREEN_INPUT_EVENT, {session, event});
  } else if (event.message === 'attached') {
    const sessionUrl = new URL(url);
    sessionUrl.searchParams.append('pid', pid.toString());
    ipcRenderer.send(OFFSCREEN_WINDOW_UPDATE, {
      session,
      url: sessionUrl.toString(),
    });
    cleanupHookInitLog(pid);
    if (attachCallback) {
      attachCallback(session);
    }
  } else if (event.message === 'detached') {
    cleanupHookInitLog(pid);
    ipcRenderer.send(OFFSCREEN_WINDOW_UPDATE, {session, destroy: true});
  } else if (event.message === 'click_zone_event') {
    if (clickZoneCallback) {
      clickZoneCallback(session, event.name);
    }
  }
});

Overlay.setURL = url_ => {
  url = url_;
};

ipcRenderer.on(OFFSCREEN_CURSOR_CHANGED, (event, session, type) => {
  let cursor;
  switch (type) {
    case 'default':
      cursor = 'IDC_ARROW';
      break;
    case 'pointer':
      cursor = 'IDC_HAND';
      break;
    case 'crosshair':
      cursor = 'IDC_CROSS';
      break;
    case 'text':
      cursor = 'IDC_IBEAM';
      break;
    case 'wait':
      cursor = 'IDC_WAIT';
      break;
    case 'help':
      cursor = 'IDC_HELP';
      break;
    case 'none':
      cursor = '';
      break;
  }

  if (cursor) {
    Overlay.sendCommand(session, {message: 'set_cursor', cursor});
  }
});

ipcRenderer.on(OFFSCREEN_START_DRAG, (event, session, image, size, offset) => {
  Overlay.sendCommand(session, {message: 'set_drag_state', dragging: true, image: image.toJSON().data, size, offset});
});

ipcRenderer.on(OFFSCREEN_STOP_DRAG, (event, session) => {
  Overlay.sendCommand(session, {message: 'set_drag_state', dragging: false});
});

module.exports = Overlay;
