'use strict';

/*
  The world terminal.js is loaded into by RendererReconnectionTests.

  It fakes exactly what the page's transport touches and nothing else: a WebSocket whose every step is
  driven from the test, a clock that only moves when a test moves it, and the two DOM objects the page
  reads at load. There is no Terminal, no fit addon and no WebGL here, because nothing on the reconnection
  path builds a pane — a test that opens a session will have to add them, and should, rather than this
  file guessing now at what such a test would want.

  ◆ NOTHING HERE MAY DECLARE A NAME terminal.js ALSO DECLARES.

  Both files are evaluated as scripts into the same global scope, and the page's own `const root` against
  a `var root` here is a SyntaxError before a line of either runs. That is why the page's two elements are
  `pageRoot` and `pageBanner` below and reached through getElementById, which is how the page reaches them
  anyway.

  ◆ AND THE FAKE SOCKET'S BEHAVIOUR IS THE PART TO GET RIGHT.

  close() is the one method with a rule that is not obvious and that the tests lean on: a socket closed
  while it is still CONNECTING never fires 'close' at all, per the WebSocket specification, while one
  closed after it opened does. The page relies on exactly that — connect() closes the attempt it abandons
  and expects to hear nothing back from it — so a fake that fired 'close' either way would report the loop
  the page's guards exist to prevent, and one that fired it neither way would hide it.
*/

var clock = { now: 0, next: 1, timers: {} };

/** Every socket the page has opened, in order, live or dead. */
var sockets = [];

function listeners(target) {
  target.handlers = {};

  target.addEventListener = function (name, handler) {
    if (!target.handlers[name]) {
      target.handlers[name] = [];
    }

    target.handlers[name].push(handler);
  };

  target.fire = function (name) {
    var handlers = target.handlers[name] || [];

    for (var i = 0; i < handlers.length; i++) {
      handlers[i]({});
    }
  };

  return target;
}

function FakeSocket(url, protocols) {
  this.url = url;
  this.protocols = protocols;
  this.readyState = FakeSocket.CONNECTING;
  this.binaryType = '';

  listeners(this);
  sockets.push(this);
}

FakeSocket.CONNECTING = 0;
FakeSocket.OPEN = 1;
FakeSocket.CLOSING = 2;
FakeSocket.CLOSED = 3;

FakeSocket.prototype.send = function () {};

/** What the page calls. See the note above on why a connecting socket goes quietly. */
FakeSocket.prototype.close = function () {
  if (this.readyState === FakeSocket.CLOSED) {
    return;
  }

  var wasConnecting = this.readyState === FakeSocket.CONNECTING;
  this.readyState = FakeSocket.CLOSED;

  if (!wasConnecting) {
    this.fire('close');
  }
};

var pageBanner = { textContent: 'Connecting…' };

var pageRoot = listeners({
  dataset: { token: 'test-token', socket: 'ws://127.0.0.1:1/socket' },
  appendChild: function () {},
});

var document = listeners({
  hidden: false,
  getElementById: function (id) { return id === 'root' ? pageRoot : pageBanner; },
  createElement: function () { return { dataset: {}, style: {}, remove: function () {} }; },
});

var window = listeners({});

// The page warns through this on paths no reconnection test reaches. Present so that a test which does
// reach one fails on its own assertion rather than on a missing global.
var console = { warn: function () {}, log: function () {} };

function setTimeout(callback, delay) {
  var id = clock.next++;

  clock.timers[id] = { at: clock.now + (delay || 0), callback: callback };

  return id;
}

function clearTimeout(id) {
  delete clock.timers[id];
}

function ResizeObserver() {
  this.observe = function () {};
}

// ── What the tests drive the page with ──────────────────────────────────────────────────────────────

/**
 * Runs every timer due within the next `ms`, in the order they fall due.
 *
 * One at a time and re-scanned each round rather than collected up front, because a timer's callback
 * routinely schedules the next one — which is the whole shape of the page's retry — and a snapshot taken
 * before the first callback ran would miss it.
 */
function advance(ms) {
  var target = clock.now + ms;

  for (;;) {
    var dueId = null;
    var due = null;

    for (var id in clock.timers) {
      var timer = clock.timers[id];

      if (timer.at <= target && (due === null || timer.at < due.at)) {
        due = timer;
        dueId = id;
      }
    }

    if (due === null) {
      break;
    }

    delete clock.timers[dueId];
    clock.now = due.at;
    due.callback();
  }

  clock.now = target;
}

/** How many sockets the page has opened since it loaded. */
function attempts() {
  return sockets.length;
}

/** What the one status element says — the banner the user sees. */
function banner() {
  return pageBanner.textContent;
}

/** Whether that attempt has been closed, by the page or by the far end. */
function isClosed(index) {
  return sockets[index].readyState === FakeSocket.CLOSED;
}

/** The host accepted the upgrade. */
function accept(index) {
  sockets[index].readyState = FakeSocket.OPEN;
  sockets[index].fire('open');
}

/** An established socket goes away and the page is told. */
function drop(index) {
  sockets[index].readyState = FakeSocket.CLOSED;
  sockets[index].fire('close');
}

/** An attempt that never connects: 'error' then 'close', as a refused connection reports itself. */
function fail(index) {
  sockets[index].readyState = FakeSocket.CLOSED;
  sockets[index].fire('error');
  sockets[index].fire('close');
}

/**
 * A close arriving for a socket that died earlier — the host's takeover abort, landing late.
 *
 * Separate from drop() because the point of it is the delay: the socket is already dead by the time the
 * event is delivered, which is what a suspended renderer's queued events look like on the way back.
 */
function deliverLateClose(index) {
  sockets[index].readyState = FakeSocket.CLOSED;
  sockets[index].fire('close');
}

/** The screen the page is on goes away, and comes back. */
function becomeHidden() {
  document.hidden = true;
  document.fire('visibilitychange');
}

function becomeVisible() {
  document.hidden = false;
  document.fire('visibilitychange');
}

function takeFocus() {
  window.fire('focus');
}

function comeOnline() {
  window.fire('online');
}

var WebSocket = FakeSocket;
