'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.default = undefined;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 _format = require('@parity/api/lib/util/format');

var _balancesActions = require('./balancesActions');
var _tokensActions = require('./tokensActions');

var _contracts = require('../../contracts');var _contracts2 = _interopRequireDefault(_contracts);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 instance = null;var

Tokens = function () {
  function Tokens(store, api) {_classCallCheck(this, Tokens);
    this._api = api;
    this._store = store;

    this._tokenreg = null;
    this._tokenregSubs = [];

    this._loading = false;
  }_createClass(Tokens, [{ key: 'attachToTokensEvents', value: function attachToTokensEvents(

































































    tokenreg) {
      var metaTopics = [null, (0, _format.padRight)(this._api.util.asciiToHex('IMG'), 32)];

      return Promise.
      all([
      this._attachToTokenregEvents(tokenreg, 'Registered'),
      this._attachToTokenregEvents(tokenreg, 'MetaChanged', metaTopics)]);

    } }, { key: 'getTokenRegistry', value: function getTokenRegistry()

    {
      return _contracts2.default.get(this._api).tokenReg.getContract();
    } }, { key: 'loadTokens', value: function loadTokens()

    {var _this = this;var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};var _store =
      this._store,dispatch = _store.dispatch,getState = _store.getState;

      return this.
      getTokenRegistry().
      then(function (tokenreg) {
        _this._tokenreg = tokenreg;

        return (0, _tokensActions.loadTokens)(options)(dispatch, getState);
      }).
      then(function () {return (0, _balancesActions.updateTokensFilter)()(dispatch, getState);}).
      then(function () {return _this.attachToTokensEvents(_this._tokenreg);}).
      catch(function (error) {
        console.warn('balances::loadTokens', error);
      });
    } }, { key: '_attachToTokenregEvents', value: function _attachToTokenregEvents(

    tokenreg, event) {var _this2 = this;var topics = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
      if (this._tokenregSID) {
        return Promise.resolve();
      }

      return tokenreg.instance[event].
      subscribe({
        fromBlock: 'latest',
        toBlock: 'latest',
        topics: topics,
        skipInitFetch: true },
      function (error, logs) {
        if (error) {
          return console.error('balances::attachToNewToken', 'failed to attach to tokenreg Registered', error.toString(), error.stack);
        }

        _this2._handleTokensLogs(logs);
      }).
      then(function (tokenregSID) {
        _this2._tokenregSubs.push(tokenregSID);
      });
    } }, { key: '_handleTokensLogs', value: function _handleTokensLogs(

    logs) {var _store2 =
      this._store,dispatch = _store2.dispatch,getState = _store2.getState;
      var tokenIds = logs.map(function (log) {return log.params.id.value.toNumber();});

      return (0, _tokensActions.fetchTokens)(tokenIds)(dispatch, getState).
      then(function () {return (0, _balancesActions.updateTokensFilter)()(dispatch, getState);});
    } }, { key: 'loading', get: function get() {return this._loading;} }], [{ key: 'get', value: function get(store) {if (!instance && store) {return Tokens.init(store);} else if (!instance) {throw new Error('The Tokens Provider has not been initialized yet');}return instance;} }, { key: 'init', value: function init(store) {var _store$getState = store.getState(),api = _store$getState.api;if (!instance) {instance = new Tokens(store, api);}return instance;} }, { key: 'start', value: function start() {if (!instance) {return Promise.reject(new Error('Tokens Provider has not been initiated yet'));}var self = instance;self._loading = true; // Unsubscribe from previous subscriptions
      return Tokens.stop().then(function () {return self.loadTokens();}).then(function () {self._loading = false;});} }, { key: 'stop', value: function stop() {if (!instance) {return Promise.resolve();}var self = instance; // Unsubscribe without adding the promises
      // to the result, since it would have to wait for a
      // reconnection to resolve if the Node is disconnected
      if (self._tokenreg) {var tokenregPromises = self._tokenregSubs.map(function (tokenregSID) {return self._tokenreg.unsubscribe(tokenregSID);});Promise.all(tokenregPromises).then(function () {self._tokenregSubs = [];});}return Promise.resolve();} }]);return Tokens;}();exports.default = Tokens;