'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.default = undefined;var _slicedToArray = function () {function sliceIterator(arr, i) {var _arr = [];var _n = true;var _d = false;var _e = undefined;try {for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"]) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}return function (arr, i) {if (Array.isArray(arr)) {return arr;} else if (Symbol.iterator in Object(arr)) {return sliceIterator(arr, i);} else {throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();var _createClass = 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);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}(); // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.

// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity.  If not, see <http://www.gnu.org/licenses/>.

var _lodash = require('lodash');
var _store = require('store');var _store2 = _interopRequireDefault(_store);

var _contracts = require('../../../contracts');var _contracts2 = _interopRequireDefault(_contracts);
var _registry = require('../../../contracts/abi/registry.json');var _registry2 = _interopRequireDefault(_registry);
var _subscribeToEvents = require('../../../util/subscribe-to-events');var _subscribeToEvents2 = _interopRequireDefault(_subscribeToEvents);

var _actions = require('./actions');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");}}

var STORE_KEY = '_parity::reverses';var

RegistryMiddleware = function () {








  function RegistryMiddleware(api) {var _this = this;_classCallCheck(this, RegistryMiddleware);this.addressesToCheck = {};this.















































































    checkReverses = function () {
      Object.
      keys(_this.addressesToCheck).
      forEach(function (address) {
        _this.contract.
        instance.
        reverse.
        call({}, [address]).
        then(function (reverse) {
          _this.store.dispatch((0, _actions.setReverse)(address, reverse));
        });
      });

      _this.addressesToCheck = {};
    };this.

    onLog = function (log) {
      switch (log.event) {
        case 'ReverseConfirmed':
          _this.addressesToCheck[log.params.reverse.value] = true;

          break;
        case 'ReverseRemoved':
          delete _this.addressesToCheck[log.params.reverse.value];

          break;}

    };this.

    read = function (chain) {
      var reverses = _store2.default.get(STORE_KEY + '::' + chain + '::data');
      var lastBlock = _store2.default.get(STORE_KEY + '::' + chain + '::lastBlock');

      if (!reverses || !lastBlock) {
        return null;
      }
      return { reverses: reverses, lastBlock: lastBlock };
    };this.

    write = (0, _lodash.debounce)(function (getChain, getReverses, getLastBlock) {
      var chain = getChain();
      var reverses = getReverses();
      var lastBlock = getLastBlock();

      _store2.default.set(STORE_KEY + '::' + chain + '::data', reverses);
      _store2.default.set(STORE_KEY + '::' + chain + '::lastBlock', lastBlock);
    }, 20000);this._api = api;}_createClass(RegistryMiddleware, [{ key: 'toMiddleware', value: function toMiddleware() {var _this2 = this;return function (store) {_this2.store = store;return function (next) {return function (action) {switch (action.type) {case 'initAll':next(action);store.dispatch((0, _actions.startCachingReverses)());break;case 'startCachingReverses':_this2.cacheReverses();break;case 'stopCachingReverses':if (_this2.subscription) {_this2.subscription.unsubscribe();}if (_this2.interval) {clearInterval(_this2.interval);}if (_this2.timeout) {clearTimeout(_this2.timeout);}_this2.write.flush();break;case 'setReverse':_this2.write(function () {return store.getState().nodeStatus.netChain;}, function () {return store.getState().registry.reverse;}, function () {return +store.getState().nodeStatus.blockNumber;});next(action);break;default:next(action);}};};};} }, { key: 'cacheReverses', value: function cacheReverses() {var _this3 = this;var _Contracts$get = _contracts2.default.get(this._api),registry = _Contracts$get.registry;var cached = this.read(this.store.getState().nodeStatus.netChain);if (cached) {Object.entries(cached.reverses).forEach(function (_ref) {var _ref2 = _slicedToArray(_ref, 2),address = _ref2[0],reverse = _ref2[1];return _this3.store.dispatch((0, _actions.setReverse)(address, reverse));});}registry.getInstance().then(function (instance) {return _this3._api.newContract(_registry2.default, instance.address);}).then(function (_contract) {_this3.contract = _contract;_this3.subscription = (0, _subscribeToEvents2.default)(_this3.contract, ['ReverseConfirmed', 'ReverseRemoved'], { from: cached ? cached.lastBlock : 0 });_this3.subscription.on('log', _this3.onLog);_this3.timeout = setTimeout(_this3.checkReverses, 10000);_this3.interval = setInterval(_this3.checkReverses, 20000);}).catch(function (err) {console.error('Failed to start caching reverses:', err);throw err;});} }]);return RegistryMiddleware;}();exports.default = RegistryMiddleware;