'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.HW_SCAN_INTERVAL = 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;};}();var _desc, _value, _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6; // 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 _mobx = require('mobx');

var _ledger = require('@parity/ledger');var _ledger2 = _interopRequireDefault(_ledger);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _initDefineProp(target, property, descriptor, context) {if (!descriptor) return;Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 });}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {var desc = {};Object['ke' + 'ys'](descriptor).forEach(function (key) {desc[key] = descriptor[key];});desc.enumerable = !!desc.enumerable;desc.configurable = !!desc.configurable;if ('value' in desc || desc.initializer) {desc.writable = true;}desc = decorators.slice().reverse().reduce(function (desc, decorator) {return decorator(target, property, desc) || desc;}, desc);if (context && desc.initializer !== void 0) {desc.value = desc.initializer ? desc.initializer.call(context) : void 0;desc.initializer = undefined;}if (desc.initializer === void 0) {Object['define' + 'Property'](target, property, desc);desc = null;}return desc;}function _initializerWarningHelper(descriptor, context) {throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');}

var HW_SCAN_INTERVAL = 5000;
var instance = null;var

HardwareStore = (_class = function () {




  function HardwareStore(api) {var _this = this;_classCallCheck(this, HardwareStore);_initDefineProp(this, 'isScanning', _descriptor, this);_initDefineProp(this, 'wallets', _descriptor2, this);_initDefineProp(this, 'pinMatrixRequest', _descriptor3, this);_initDefineProp(this, 'setScanning', _descriptor4, this);_initDefineProp(this, 'setWallets', _descriptor5, this);_initDefineProp(this, 'setPinMatrixRequest', _descriptor6, this);this.





























    _pollScan = function () {
      _this._pollId = setTimeout(function () {
        _this.scan().then(_this._pollScan);
      }, HW_SCAN_INTERVAL);
    };this._api = api;this._ledger = _ledger2.default.create(api);this._pollId = null;this.hwAccounts = {};this.ledgerAccounts = {};this._pollScan();this._subscribeParity();this._api.transport.on('close', function () {_this._subscribeParity();});}_createClass(HardwareStore, [{ key: 'isConnected', value: function isConnected(address) {var _this2 = this;return (0, _mobx.computed)(function () {return !!_this2.wallets[address];}).get();} }, { key: 'scanTrezor', value: function scanTrezor()

    {var _this3 = this;
      return this._api.parity.
      lockedHardwareAccountsInfo().
      then(function (paths) {
        _this3.setPinMatrixRequest(paths.map(function (path) {
          return { path: path, manufacturer: 'Trezor' };
        }));
        return {};
      }).
      catch(function (err) {
        console.warn('HardwareStore::scanTrezor', err);
        return {};
      });
    } }, { key: 'scanLedger', value: function scanLedger()

    {
      if (!this._ledger.isSupported) {
        return Promise.resolve({});
      }

      return this._ledger.
      scan().
      then(function (wallets) {
        console.log('HardwareStore::scanLedger', wallets);

        return wallets.reduce(function (hwInfo, wallet) {
          wallet.manufacturer = 'Ledger';
          wallet.name = 'Nano S';
          wallet.via = 'ledger';

          hwInfo[wallet.address] = wallet;

          return hwInfo;
        }, {});
      }).
      catch(function (error) {
        console.warn('HardwareStore::scanLedger', error);

        return {};
      });
    } }, { key: '_subscribeParity', value: function _subscribeParity()

    {var _this4 = this;
      var onError = function onError(error) {
        console.warn('HardwareStore::scanParity', error);

        return {};
      };

      return this._api.pubsub.
      subscribeAndGetResult(
      function (callback) {return _this4._api.pubsub.parity.hardwareAccountsInfo(callback);},
      function (hwInfo) {
        Object.
        keys(hwInfo).
        forEach(function (address) {
          var info = hwInfo[address];

          info.address = address;
          info.via = 'parity';
        });
        _this4.hwAccounts = hwInfo;
        _this4.updateWallets();
        return hwInfo;
      },
      onError).
      catch(onError);
    } }, { key: 'scan', value: function scan()

    {var _this5 = this;
      this.setScanning(true);
      // This only scans for locked devices and does not return open devices,
      // so no need to actually wait for any results here.
      this.scanTrezor();

      // NOTE: Depending on how the hardware is configured and how the local env setup
      // is done, different results will be retrieved via Parity vs. the browser APIs
      // (latter is Chrome-only, needs the browser app enabled on a Ledger, former is
      // not intended as a network call, i.e. hw wallet is with the user)
      return this.scanLedger().
      then(function (ledgerAccounts) {
        _this5.ledgerAccounts = ledgerAccounts;
        (0, _mobx.transaction)(function () {
          _this5.updateWallets();
          _this5.setScanning(false);
        });
      });
    } }, { key: 'updateWallets', value: function updateWallets()

    {
      this.setWallets(Object.assign({}, this.hwAccounts, this.ledgerAccounts));
    } }, { key: 'createAccountInfo', value: function createAccountInfo(

    entry) {var original = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};var
      address = entry.address,manufacturer = entry.manufacturer,name = entry.name;

      return Promise.
      all([
      original.name ?
      Promise.resolve(true) :
      this._api.parity.setAccountName(address, name),
      this._api.parity.setAccountMeta(address, Object.assign({
        description: manufacturer + ' ' + name,
        hardware: {
          manufacturer: manufacturer },

        tags: ['hardware'],
        timestamp: Date.now() },
      original.meta || {}))]).

      catch(function (error) {
        console.warn('HardwareStore::createEntry', error);
        throw error;
      });
    } }, { key: 'signLedger', value: function signLedger(

    transaction) {
      return this._ledger.signTransaction(transaction);
    } }, { key: 'pinMatrixAck', value: function pinMatrixAck(

    device, passcode) {var _this6 = this;
      return this._api.parity.
      hardwarePinMatrixAck(device.path, passcode).
      then(function (success) {
        _this6.scan();
        return success;
      });
    } }], [{ key: 'get', value: function get(

    api) {
      if (!instance) {
        instance = new HardwareStore(api);
      }

      return instance;
    } }]);return HardwareStore;}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, 'isScanning', [_mobx.observable], { enumerable: true, initializer: function initializer() {return false;} }), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, 'wallets', [_mobx.observable], { enumerable: true, initializer: function initializer() {return {};} }), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, 'pinMatrixRequest', [_mobx.observable], { enumerable: true, initializer: function initializer() {return [];} }), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, 'setScanning', [_mobx.action], { enumerable: true, initializer: function initializer() {var _this7 = this;return function (isScanning) {_this7.isScanning = isScanning;};} }), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, 'setWallets', [_mobx.action], { enumerable: true, initializer: function initializer() {var _this8 = this;return function (wallets) {_this8.wallets = wallets;};} }), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, 'setPinMatrixRequest', [_mobx.action], { enumerable: true, initializer: function initializer() {var _this9 = this;return function (requests) {_this9.pinMatrixRequest = requests;};} })), _class);exports.default = HardwareStore;exports.



HW_SCAN_INTERVAL = HW_SCAN_INTERVAL;