"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

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

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

var _cmd = require("./cmd");

var _assert = _interopRequireDefault(require("assert"));

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) 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); }); }; }

_events["default"].defaultMaxListeners = 20;
var rateInterval = 60000; // 1 minute

module.exports = function (ln) {
  var lnPoll = (0, _clightningClient["default"])(ln.rpcPath),
      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 lnPoll.waitanyinvoice(last_index);

            case 3:
              inv = _context2.sent;
              _context2.next = 6;
              return (0, _cmd.attachInvoiceMeta)(lnPoll, inv);

            case 6:
              em.emit('inv-paid', inv);
              waitany(inv.pay_index);
              _context2.next = 14;
              break;

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

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

  lnPoll.client.on('connect', function (_) {
    return lnPoll.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;
    })()();
  }

  var payTracker = new PayStatusTracker(ln);
  ln.on('paying', function (paystr) {
    return payTracker.track(paystr);
  }); // 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 onInvPaid = function onInvPaid(inv) {
      return write("event:inv-paid\ndata:".concat(JSON.stringify(inv)));
    };

    em.on('inv-paid', onInvPaid);

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

    em.on('rate', onRate);
    lastRate && onRate(lastRate);

    var onPayUpdates = function onPayUpdates(pays) {
      return write("event:pay-updates\ndata:".concat(JSON.stringify(pays)));
    };

    payTracker.on('updates', onPayUpdates);
    req.once('end', function (_) {
      return em.removeListener('inv-paid', onInvPaid), em.removeListener('rate', onRate), payTracker.removeListener('updated', onPayUpdates), clearInterval(keepAlive);
    });
  };
}; // Track the status of send payments


var PayStatusTracker = /*#__PURE__*/function (_EventEmitter) {
  _inherits(PayStatusTracker, _EventEmitter);

  var _super = _createSuper(PayStatusTracker);

  function PayStatusTracker(ln) {
    var _this;

    _classCallCheck(this, PayStatusTracker);

    _this = _super.call(this);
    _this.ln = ln;
    _this.timer = null;
    _this.pendingPays = new Set();
    return _this;
  }

  _createClass(PayStatusTracker, [{
    key: "track",
    value: function track(paystr) {
      var _this2 = this;

      this.pendingPays.add({
        paystr: paystr,
        fails: 0
      }); // Allow some time for the payment to show up in `listpays` before updating

      clearInterval(this.timer);
      this.timer = setTimeout(function (_) {
        return _this2.update();
      }, 200);
    }
  }, {
    key: "update",
    value: function () {
      var _update = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
        var _this3 = this;

        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.prev = 0;
                _context4.t0 = this;
                _context4.next = 4;
                return Promise.all(_toConsumableArray(this.pendingPays).map( /*#__PURE__*/function () {
                  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(ppay) {
                    var pay;
                    return regeneratorRuntime.wrap(function _callee3$(_context3) {
                      while (1) {
                        switch (_context3.prev = _context3.next) {
                          case 0:
                            _context3.next = 2;
                            return _this3.ln._listpays(ppay.paystr);

                          case 2:
                            pay = _context3.sent.pays[0];

                            if (pay) {
                              _context3.next = 6;
                              break;
                            }

                            if (++ppay.fails > 10) _this3.pendingPays["delete"](ppay);
                            return _context3.abrupt("return");

                          case 6:
                            if (pay.status != 'pending') {
                              (0, _assert["default"])(pay.status == 'complete' || pay.status == 'failed', "Unexpected pay status ".concat(pay.status, " of ").concat(pay.payment_hash)); // Stop tracking payments when they complete or fail

                              // Stop tracking payments when they complete or fail
                              _this3.pendingPays["delete"](ppay);
                            }

                            return _context3.abrupt("return", pay);

                          case 8:
                          case "end":
                            return _context3.stop();
                        }
                      }
                    }, _callee3);
                  }));

                  return function (_x2) {
                    return _ref.apply(this, arguments);
                  };
                }()));

              case 4:
                _context4.t1 = _context4.sent.filter(Boolean);

                _context4.t0.emit.call(_context4.t0, 'updates', _context4.t1);

                _context4.next = 11;
                break;

              case 8:
                _context4.prev = 8;
                _context4.t2 = _context4["catch"](0);
                console.warn('pay status update failed:', _context4.t2);

              case 11:
                if (this.pendingPays.size) {
                  this.timer = setTimeout(function (_) {
                    return _this3.update();
                  }, 800);
                }

              case 12:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this, [[0, 8]]);
      }));

      function update() {
        return _update.apply(this, arguments);
      }

      return update;
    }()
  }]);

  return PayStatusTracker;
}(_events["default"]);