'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.awaitPuzzle = exports.findLastRequested = exports.checkIfVerified = undefined;















var _subscribeToEvents = require('../util/subscribe-to-events');var _subscribeToEvents2 = _interopRequireDefault(_subscribeToEvents);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}

var checkIfVerified = exports.checkIfVerified = function checkIfVerified(contract, account) {
  return contract.instance.certified.call({}, [account]);
}; // 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 findLastRequested = exports.findLastRequested = function findLastRequested(contract, account) {var subId = null;var resolved = false;return new Promise(function (resolve, reject) {contract.subscribe('Requested', { fromBlock: 0, toBlock: 'pending', limit: 1, topics: [account] },
    function (err, logs) {
      if (err) {
        return reject(err);
      }

      resolve(logs[0] || null);
      resolved = true;

      if (subId) {
        contract.unsubscribe(subId);
      }
    }).
    then(function (_subId) {
      subId = _subId;

      if (resolved) {
        contract.unsubscribe(subId);
      }
    });
  });
};

var blockNumber = function blockNumber(api) {
  return new Promise(function (resolve, reject) {
    api.
    subscribe('eth_blockNumber', function (err, block) {
      if (err) {
        return reject(err);
      }
      resolve(block);
    }).
    then(function (subscription) {
      api.unsubscribe(subscription);
    }).
    catch(reject);
  });
};

var awaitPuzzle = exports.awaitPuzzle = function awaitPuzzle(api, contract, account) {
  return blockNumber(api).
  then(function (block) {
    return new Promise(function (resolve, reject) {
      var subscription = (0, _subscribeToEvents2.default)(contract, ['Puzzled'], {
        from: block.toNumber(),
        filter: function filter(log) {return log.params.who.value === account;} });


      subscription.once('error', reject);
      subscription.once('log', subscription.unsubscribe);
      subscription.once('log', resolve);
      subscription.once('timeout', function () {
        reject(new Error('Timed out waiting for the puzzle.'));
      });
    });
  });
};