"use strict";

var _clightningClient = _interopRequireDefault(require("clightning-client"));

var _events = _interopRequireDefault(require("events"));

var _exchangeRate = require("./exchange-rate");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

var rateInterval = 60000; // 1 minute

module.exports = function (lnPath) {
  var ln = (0, _clightningClient["default"])(lnPath),
      em = new _events["default"](); // Continuously long-poll invoice payment updates

  function waitany(_x) {
    return _waitany.apply(this, arguments);
  } // Start waitany() with the last known invoice


  function _waitany() {
    _waitany = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(last_index) {
      var inv;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              _context2.next = 3;
              return ln.waitanyinvoice(last_index);

            case 3:
              inv = _context2.sent;
              em.emit('payment', inv);
              waitany(inv.pay_index);
              _context2.next = 12;
              break;

            case 8:
              _context2.prev = 8;
              _context2.t0 = _context2["catch"](0);
              console.error(_context2.t0.stack || _context2.t0.toString());
              setTimeout(function (_) {
                return waitany(last_index);
              }, 10000);

            case 12:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 8]]);
    }));
    return _waitany.apply(this, arguments);
  }

  ln.client.on('connect', function (_) {
    return ln.listinvoices().then(function (r) {
      return Math.max.apply(Math, _toConsumableArray(r.invoices.map(function (inv) {
        return inv.pay_index || 0;
      })));
    }).then(waitany);
  }); // Periodically pull BTC<->USD exchange rate

  var lastRate;

  if (_exchangeRate.fetchRate) {
    (function () {
      var _getrate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!(em.listenerCount('rate') || !lastRate)) {
                  _context.next = 15;
                  break;
                }

                _context.prev = 1;
                _context.t0 = em;
                _context.next = 5;
                return (0, _exchangeRate.fetchRate)();

              case 5:
                _context.t1 = lastRate = _context.sent;

                _context.t0.emit.call(_context.t0, 'rate', _context.t1);

                _context.next = 12;
                break;

              case 9:
                _context.prev = 9;
                _context.t2 = _context["catch"](1);
                console.error(_context.t2.stack || _context.t2.toString());

              case 12:
                setTimeout(getrate, rateInterval);
                _context.next = 16;
                break;

              case 15:
                // set a shorter interval for the next update check if we skipped this one
                setTimeout(getrate, 10000);

              case 16:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[1, 9]]);
      }));

      function getrate() {
        return _getrate.apply(this, arguments);
      }

      return getrate;
    })()();
  } // GET /stream middleware


  return function (req, res) {
    res.set({
      'X-Accel-Buffering': 'no',
      'Cache-Control': 'no-cache',
      'Content-Type': 'text/event-stream',
      'Connection': 'keep-alive'
    }).flushHeaders();

    var write = function write(data) {
      return res.write(data + '\n\n'), res.flush();
    };

    write('retry: 3000');
    var keepAlive = setInterval(function (_) {
      return write(': keepalive');
    }, 25000);

    var onPay = function onPay(inv) {
      return write("event:inv-paid\ndata:".concat(JSON.stringify(inv)));
    };

    em.on('payment', onPay);

    var onRate = function onRate(rate) {
      return write("event:btcusd\ndata:".concat(JSON.stringify(rate)));
    };

    em.on('rate', onRate);
    lastRate && onRate(lastRate);
    req.once('end', function (_) {
      return em.removeListener('payment', onPay), em.removeListener('rate', onRate), clearInterval(keepAlive);
    });
  };
};