import _Promise from 'babel-runtime/core-js/promise';
import _slicedToArray from 'babel-runtime/helpers/slicedToArray';
import _regeneratorRuntime from 'babel-runtime/regenerator';
import _asyncToGenerator from 'babel-runtime/helpers/asyncToGenerator';
import _Object$getPrototypeOf from 'babel-runtime/core-js/object/get-prototype-of';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';

var _this2 = this;

import klerosArtifact from 'kleros/build/contracts/KlerosPOC';
import _ from 'lodash';

import * as ethConstants from '../../../constants/eth';
import * as errorConstants from '../../../constants/error';
import * as arbitratorConstants from '../../../constants/arbitrator';
import ContractImplementation from '../../ContractImplementation';
import deployContractAsync from '../../../utils/deployContractAsync';

/**
 * Provides interaction with a KlerosPOC contract on the blockchain.
 */

var KlerosPOC = function (_ContractImplementati) {
  _inherits(KlerosPOC, _ContractImplementati);

  /**
   * Create new KlerosPOC Implementation.
   * @param {object} web3Provider - web3 instance.
   * @param {string} contractAddress - Address of the KlerosPOC contract.
   */
  function KlerosPOC(web3Provider, contractAddress) {
    _classCallCheck(this, KlerosPOC);

    var _this = _possibleConstructorReturn(this, (KlerosPOC.__proto__ || _Object$getPrototypeOf(KlerosPOC)).call(this, web3Provider, klerosArtifact, contractAddress));

    _initialiseProps.call(_this);

    return _this;
  }

  /**
   * STATIC: Deploy a KlerosPOC contract on the blockchain.
   * @param {string} rngAddress address of random number generator contract
   * @param {string} pnkAddress address of pinakion contract
   * @param {number[]} timesPerPeriod array of 5 ints indicating the time limit for each period of contract
   * @param {string} account address of user
   * @param {number} value amout of eth to send to contract
   * @param {object} web3Provider web3 provider object NOTE: NOT Kleros Web3Wrapper
   * @returns {object} truffle-contract Object | err The contract object or error deploy
   */


  /**
   * Purchase PNK.
   * @param {string} amount - The number of pinakion to buy.
   * @param {string} account - The address of the user.
   * @returns {object} - The result transaction object.
   */


  /**
   * Get PNK Balances.
   * @param {string} account - The address of the user.
   * @returns {object} - Balance information including total PNK balance and activated tokens.
   */


  /**
   * Activate Pinakion tokens to be eligible to be a juror.
   * @param {string} amount - number of tokens to activate.
   * @param {string} account - address of user.
   * @returns {object} - PNK balance.
   */


  /**
   * Fetch the cost of arbitration.
   * @param {bytes} contractExtraData - extra data from arbitrable contract.
   * @returns {number} - The cost of arbitration.
   */


  /**
   * Call contract to move on to the next period.
   * @param {string} account - address of user.
   * @returns {Promise} - resulting object.
   */


  /**
   * Submit votes. Note can only be called during Voting period (Period 2).
   * @param {number} disputeId - index of the dispute.
   * @param {number} ruling - int representing the jurors decision.
   * @param {number[]} votes - int[] of drawn votes for dispute.
   * @param {string} account - address of user.
   * @returns {object} - The result transaction object.
   */


  /**
   * Appeal ruling on dispute.
   * @param {number} disputeId - Index of the dispute.
   * @param {string} extraData - Extra data.
   * @param {string} account - Address of user.
   * @returns {object} - The result transaction object.
   */


  /**
   * Repartition juror tokens.
   * @param {number} disputeId - index of the dispute.
   * @param {string} account - address of user.
   * @returns {object} - The result transaction object.
   */


  /**
   * Execute ruling on dispute
   * @param {number} disputeId - index of the dispute.
   * @param {string} account - address of user.
   * @returns {object} - The result transaction object.
   */


  /**
   * Get time for a period.
   * @param {number} periodNumber - int representing period.
   * @returns {number} - The seconds in the period.
   */


  /**
   * Get dispute.
   * @param {number} disputeId - The index of the dispute.
   * @returns {object} - The dispute data from the contract.
   */


  /**
   * Get number of jurors for a dispute.
   * @param {number} disputeId - Index of dispute.
   * @returns {number} - Number of jurors for a dispute.
   */


  /**
   * Get number of jurors for a dispute.
   * @param {number} disputeId - Index of dispute.
   * @param {number} draw - Int for draw.
   * @param {string} jurorAddress - Address of juror.
   * @returns {bool} - `true` indicates juror has a vote for draw, `false` indicates they do not.
   */


  /**
   * Can juror currently rule in dispute.
   * @param {number} disputeId - index of dispute.
   * @param {int[]} draws - voting positions for dispute.
   * @param {string} account - address of user.
   * @returns {bool} - Boolean indicating if juror can rule or not.
   */


  /**
   * Get number of jurors for a dispute.
   * @param {number} disputeId - Index of dispute.
   * @param {number} appeal - Index of appeal.
   * @returns {number} - Int indicating the ruling of the dispute.
   */


  /**
   * Get current period of the contract
   * @returns {number} - Int indicating the period.
   */


  /**
   * Get current session of the contract.
   * @returns {number} - Int indicating the session.
   */


  /**
   * Get disputes from Kleros contract.
   * @param {string} account - Address of user.
   * @returns {object[]} - Array of disputes.
   */


  /**
   * Fetch the votes a juror has in a dispute.
   * @param {number} disputeId - ID of the dispute.
   * @param {string} account - Potential jurors address.
   * @returns {number[]} - Array of integers indicating the draw.
   */


  /** Get all disputes that are active this session.
   * @returns {int[]} - array of active disputeId
   */


  /**
   * Gets the deadline for an arbitrator's period, which is also the deadline for all its disputes.
   * @param {number} [period=PERIODS.VOTE] - The period to get the deadline for.
   * @returns {number} - epoch timestamp
   */


  /**
   * Get data from Kleros contract.
   * TODO split these into their own methods for more flexability and speed
   * @returns {object} - Data for kleros POC from contract.
   */


  return KlerosPOC;
}(ContractImplementation);

KlerosPOC.deploy = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(rngAddress, pnkAddress) {
    var timesPerPeriod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [1, 1, 1, 1, 1];
    var account = arguments[3];
    var value = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ethConstants.TRANSACTION.VALUE;
    var web3Provider = arguments[5];
    var contractDeployed;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return deployContractAsync(account, value, klerosArtifact, web3Provider, pnkAddress, rngAddress, timesPerPeriod);

          case 2:
            contractDeployed = _context.sent;
            return _context.abrupt('return', contractDeployed);

          case 4:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, _this2);
  }));

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

var _initialiseProps = function _initialiseProps() {
  var _this3 = this;

  this.buyPNK = function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(amount) {
      var account = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return _this3.loadContract();

            case 2:
              _context2.prev = 2;
              return _context2.abrupt('return', _this3.contractInstance.buyPinakion({
                from: account,
                gas: ethConstants.TRANSACTION.GAS,
                value: _this3._Web3Wrapper.toWei(amount, 'ether')
              }));

            case 6:
              _context2.prev = 6;
              _context2.t0 = _context2['catch'](2);

              console.error(_context2.t0);
              throw new Error(errorConstants.UNABLE_TO_BUY_PNK);

            case 10:
            case 'end':
              return _context2.stop();
          }
        }
      }, _callee2, _this3, [[2, 6]]);
    }));

    return function (_x5) {
      return _ref2.apply(this, arguments);
    };
  }();

  this.getPNKBalance = function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
      var account = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this3._Web3Wrapper.getAccount(0);
      var juror, totalTokens, currentSession, activatedTokens, lockedTokens;
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return _this3.loadContract();

            case 2:
              _context3.next = 4;
              return _this3.contractInstance.jurors(account);

            case 4:
              juror = _context3.sent;

              if (juror) {
                _context3.next = 7;
                break;
              }

              throw new Error(errorConstants.ACCOUNT_NOT_A_JUROR_FOR_CONTRACT(account, _this3.contractAddress));

            case 7:

              // Total tokens
              totalTokens = _this3._Web3Wrapper.fromWei(juror[0], 'ether');

              // Activated Tokens

              _context3.next = 10;
              return _this3.contractInstance.session();

            case 10:
              currentSession = _context3.sent;
              activatedTokens = 0;

              if (juror[2].toNumber() === currentSession.toNumber()) activatedTokens = _this3._Web3Wrapper.fromWei(juror[4].toNumber() - juror[3].toNumber(), 'ether');

              // Locked Tokens
              lockedTokens = _this3._Web3Wrapper.fromWei(juror[1], 'ether');
              return _context3.abrupt('return', {
                tokenBalance: totalTokens,
                activatedTokens: activatedTokens,
                lockedTokens: lockedTokens
              });

            case 15:
            case 'end':
              return _context3.stop();
          }
        }
      }, _callee3, _this3);
    }));

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

  this.activatePNK = function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(amount) {
      var account = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return _this3.loadContract();

            case 2:
              _context4.prev = 2;
              _context4.next = 5;
              return _this3.contractInstance.activateTokens(_this3._Web3Wrapper.toWei(amount, 'ether'), {
                from: account,
                gas: ethConstants.TRANSACTION.GAS
              });

            case 5:
              _context4.next = 11;
              break;

            case 7:
              _context4.prev = 7;
              _context4.t0 = _context4['catch'](2);

              console.error(_context4.t0);
              throw new Error(errorConstants.UNABLE_TO_ACTIVATE_PNK);

            case 11:
              return _context4.abrupt('return', _this3.getPNKBalance(account));

            case 12:
            case 'end':
              return _context4.stop();
          }
        }
      }, _callee4, _this3, [[2, 7]]);
    }));

    return function (_x8) {
      return _ref4.apply(this, arguments);
    };
  }();

  this.getArbitrationCost = function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(contractExtraData) {
      var arbitrationCost;
      return _regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              _context5.next = 2;
              return _this3.loadContract();

            case 2:
              _context5.prev = 2;
              _context5.next = 5;
              return _this3.contractInstance.arbitrationCost(contractExtraData);

            case 5:
              arbitrationCost = _context5.sent;
              return _context5.abrupt('return', _this3._Web3Wrapper.fromWei(arbitrationCost, 'ether'));

            case 9:
              _context5.prev = 9;
              _context5.t0 = _context5['catch'](2);

              console.error(_context5.t0);
              throw new Error(errorConstants.UNABLE_TO_FETCH_ARBITRATION_COST);

            case 13:
            case 'end':
              return _context5.stop();
          }
        }
      }, _callee5, _this3, [[2, 9]]);
    }));

    return function (_x10) {
      return _ref5.apply(this, arguments);
    };
  }();

  this.passPeriod = function () {
    var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
      var account = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              _context6.next = 2;
              return _this3.loadContract();

            case 2:
              _context6.prev = 2;
              _context6.next = 5;
              return _this3.contractInstance.passPeriod.original({
                from: account,
                gas: ethConstants.TRANSACTION.GAS
              });

            case 5:
              return _context6.abrupt('return', _this3.getData());

            case 8:
              _context6.prev = 8;
              _context6.t0 = _context6['catch'](2);

              console.error(_context6.t0);
              throw new Error(errorConstants.UNABLE_TO_PASS_PERIOD);

            case 12:
            case 'end':
              return _context6.stop();
          }
        }
      }, _callee6, _this3, [[2, 8]]);
    }));

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

  this.submitVotes = function () {
    var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(disputeId, ruling, votes) {
      var account = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              _context7.next = 2;
              return _this3.loadContract();

            case 2:
              _context7.prev = 2;
              return _context7.abrupt('return', _this3.contractInstance.voteRuling(disputeId, ruling, votes, {
                from: account,
                gas: ethConstants.TRANSACTION.GAS
              }));

            case 6:
              _context7.prev = 6;
              _context7.t0 = _context7['catch'](2);

              console.error(_context7.t0);
              throw new Error(errorConstants.UNABLE_TO_SUBMIT_VOTES);

            case 10:
            case 'end':
              return _context7.stop();
          }
        }
      }, _callee7, _this3, [[2, 6]]);
    }));

    return function (_x12, _x13, _x14) {
      return _ref7.apply(this, arguments);
    };
  }();

  this.appealRuling = function () {
    var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(disputeId, extraData) {
      var account = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee8$(_context8) {
        while (1) {
          switch (_context8.prev = _context8.next) {
            case 0:
              _context8.next = 2;
              return _this3.loadContract();

            case 2:
              _context8.prev = 2;
              _context8.t0 = _this3.contractInstance;
              _context8.t1 = disputeId;
              _context8.t2 = extraData;
              _context8.t3 = account;
              _context8.next = 9;
              return _this3.contractInstance.appealCost(disputeId, extraData);

            case 9:
              _context8.t4 = _context8.sent;
              _context8.t5 = ethConstants.TRANSACTION.GAS;
              _context8.t6 = {
                from: _context8.t3,
                value: _context8.t4,
                gas: _context8.t5
              };
              return _context8.abrupt('return', _context8.t0.appeal.call(_context8.t0, _context8.t1, _context8.t2, _context8.t6));

            case 15:
              _context8.prev = 15;
              _context8.t7 = _context8['catch'](2);

              console.error(_context8.t7);
              throw new Error(errorConstants.UNABLE_TO_APPEAL);

            case 19:
            case 'end':
              return _context8.stop();
          }
        }
      }, _callee8, _this3, [[2, 15]]);
    }));

    return function (_x16, _x17) {
      return _ref8.apply(this, arguments);
    };
  }();

  this.repartitionJurorTokens = function () {
    var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(disputeId) {
      var account = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee9$(_context9) {
        while (1) {
          switch (_context9.prev = _context9.next) {
            case 0:
              _context9.next = 2;
              return _this3.loadContract();

            case 2:
              _context9.prev = 2;
              return _context9.abrupt('return', _this3.contractInstance.oneShotTokenRepartition(disputeId, {
                from: account,
                gas: ethConstants.TRANSACTION.GAS
              }));

            case 6:
              _context9.prev = 6;
              _context9.t0 = _context9['catch'](2);

              console.error(_context9.t0);
              throw new Error(errorConstants.UNABLE_TO_REPARTITION_TOKENS);

            case 10:
            case 'end':
              return _context9.stop();
          }
        }
      }, _callee9, _this3, [[2, 6]]);
    }));

    return function (_x19) {
      return _ref9.apply(this, arguments);
    };
  }();

  this.executeRuling = function () {
    var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(disputeId) {
      var account = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _this3._Web3Wrapper.getAccount(0);
      return _regeneratorRuntime.wrap(function _callee10$(_context10) {
        while (1) {
          switch (_context10.prev = _context10.next) {
            case 0:
              _context10.next = 2;
              return _this3.loadContract();

            case 2:
              _context10.prev = 2;
              return _context10.abrupt('return', _this3.contractInstance.executeRuling(disputeId, {
                from: account,
                gas: ethConstants.TRANSACTION.GAS
              }));

            case 6:
              _context10.prev = 6;
              _context10.t0 = _context10['catch'](2);

              console.error(_context10.t0);
              throw new Error(errorConstants.UNABLE_TO_EXECUTE_RULING);

            case 10:
            case 'end':
              return _context10.stop();
          }
        }
      }, _callee10, _this3, [[2, 6]]);
    }));

    return function (_x21) {
      return _ref10.apply(this, arguments);
    };
  }();

  this.getTimeForPeriod = function () {
    var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(periodNumber) {
      var timePerPeriod;
      return _regeneratorRuntime.wrap(function _callee11$(_context11) {
        while (1) {
          switch (_context11.prev = _context11.next) {
            case 0:
              _context11.next = 2;
              return _this3.loadContract();

            case 2:
              timePerPeriod = void 0;
              _context11.prev = 3;
              _context11.next = 6;
              return _this3.contractInstance.timePerPeriod(periodNumber);

            case 6:
              timePerPeriod = _context11.sent;
              _context11.next = 13;
              break;

            case 9:
              _context11.prev = 9;
              _context11.t0 = _context11['catch'](3);

              console.error(_context11.t0);
              throw new Error(errorConstants.UNABLE_TO_FETCH_TIME_PER_PERIOD);

            case 13:
              if (!timePerPeriod) {
                _context11.next = 15;
                break;
              }

              return _context11.abrupt('return', timePerPeriod.toNumber());

            case 15:
              throw new Error(errorConstants.PERIOD_OUT_OF_RANGE(periodNumber));

            case 16:
            case 'end':
              return _context11.stop();
          }
        }
      }, _callee11, _this3, [[3, 9]]);
    }));

    return function (_x23) {
      return _ref11.apply(this, arguments);
    };
  }();

  this.getDispute = function () {
    var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(disputeId) {
      var dispute, numberOfAppeals, rulingChoices, voteCounters, status, appeal, voteCounts, choice, _ref13, _ref14;

      return _regeneratorRuntime.wrap(function _callee12$(_context12) {
        while (1) {
          switch (_context12.prev = _context12.next) {
            case 0:
              _context12.next = 2;
              return _this3.loadContract();

            case 2:
              _context12.prev = 2;
              _context12.next = 5;
              return _this3.contractInstance.disputes(disputeId);

            case 5:
              dispute = _context12.sent;
              numberOfAppeals = dispute[2].toNumber();
              rulingChoices = dispute[3].toNumber();
              voteCounters = [];
              status = void 0;

              for (appeal = 0; appeal <= numberOfAppeals; appeal++) {
                voteCounts = [];

                for (choice = 0; choice <= rulingChoices; choice++) {
                  voteCounts.push(_this3.contractInstance.getVoteCount(disputeId, appeal, choice).then(function (v) {
                    return v.toNumber();
                  }));
                }voteCounters.push(voteCounts);
              }

              ;_context12.next = 14;
              return _Promise.all([_Promise.all(voteCounters.map(function (voteCounts) {
                return _Promise.all(voteCounts);
              })), _this3.contractInstance.disputeStatus(disputeId)]);

            case 14:
              _ref13 = _context12.sent;
              _ref14 = _slicedToArray(_ref13, 2);
              voteCounters = _ref14[0];
              status = _ref14[1];
              return _context12.abrupt('return', {
                arbitratorAddress: _this3.contractAddress,
                disputeId: disputeId,
                arbitrableContractAddress: dispute[0],
                firstSession: dispute[1].toNumber(),
                numberOfAppeals: numberOfAppeals,
                rulingChoices: rulingChoices,
                initialNumberJurors: dispute[4].toNumber(),
                arbitrationFeePerJuror: _this3._Web3Wrapper.fromWei(dispute[5], 'ether'),
                state: dispute[6].toNumber(),
                voteCounters: voteCounters,
                status: status.toNumber()
                // eslint-disable-next-line no-unused-vars
              });

            case 21:
              _context12.prev = 21;
              _context12.t0 = _context12['catch'](2);
              throw new Error(errorConstants.UNABLE_TO_FETCH_DISPUTE);

            case 24:
            case 'end':
              return _context12.stop();
          }
        }
      }, _callee12, _this3, [[2, 21]]);
    }));

    return function (_x24) {
      return _ref12.apply(this, arguments);
    };
  }();

  this.getAmountOfJurorsForDispute = function () {
    var _ref15 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(disputeId) {
      var amountOfJurors;
      return _regeneratorRuntime.wrap(function _callee13$(_context13) {
        while (1) {
          switch (_context13.prev = _context13.next) {
            case 0:
              _context13.next = 2;
              return _this3.loadContract();

            case 2:
              amountOfJurors = void 0;
              _context13.prev = 3;
              _context13.next = 6;
              return _this3.contractInstance.amountJurors(disputeId);

            case 6:
              amountOfJurors = _context13.sent;
              _context13.next = 13;
              break;

            case 9:
              _context13.prev = 9;
              _context13.t0 = _context13['catch'](3);

              console.error(_context13.t0);
              throw new Error(errorConstants.UNABLE_TO_FETCH_AMOUNT_OF_JURORS);

            case 13:
              if (!amountOfJurors) {
                _context13.next = 15;
                break;
              }

              return _context13.abrupt('return', amountOfJurors.toNumber());

            case 15:
              throw new Error(errorConstants.DISPUTE_DOES_NOT_EXIST);

            case 16:
            case 'end':
              return _context13.stop();
          }
        }
      }, _callee13, _this3, [[3, 9]]);
    }));

    return function (_x25) {
      return _ref15.apply(this, arguments);
    };
  }();

  this.isJurorDrawnForDispute = function () {
    var _ref16 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(disputeId, draw) {
      var jurorAddress = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _this3._Web3Wrapper.getAccount(0);
      var isDrawn;
      return _regeneratorRuntime.wrap(function _callee14$(_context14) {
        while (1) {
          switch (_context14.prev = _context14.next) {
            case 0:
              _context14.next = 2;
              return _this3.loadContract();

            case 2:
              _context14.next = 4;
              return _this3.contractInstance.isDrawn(disputeId, jurorAddress, draw);

            case 4:
              isDrawn = _context14.sent;
              return _context14.abrupt('return', isDrawn);

            case 6:
            case 'end':
              return _context14.stop();
          }
        }
      }, _callee14, _this3);
    }));

    return function (_x26, _x27) {
      return _ref16.apply(this, arguments);
    };
  }();

  this.canRuleDispute = function () {
    var _ref17 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(disputeId, draws, account) {
      var validDraws, lastRuling, currentSession;
      return _regeneratorRuntime.wrap(function _callee15$(_context15) {
        while (1) {
          switch (_context15.prev = _context15.next) {
            case 0:
              _context15.next = 2;
              return _this3.loadContract();

            case 2:
              _context15.next = 4;
              return _this3.contractInstance.validDraws(account, disputeId, draws);

            case 4:
              validDraws = _context15.sent;
              _context15.next = 7;
              return _this3.contractInstance.getLastSessionVote(disputeId, account);

            case 7:
              lastRuling = _context15.sent.toNumber();
              _context15.next = 10;
              return _this3.getSession(_this3.contractAddress);

            case 10:
              currentSession = _context15.sent;
              return _context15.abrupt('return', validDraws && lastRuling !== currentSession);

            case 12:
            case 'end':
              return _context15.stop();
          }
        }
      }, _callee15, _this3);
    }));

    return function (_x29, _x30, _x31) {
      return _ref17.apply(this, arguments);
    };
  }();

  this.currentRulingForDispute = function () {
    var _ref18 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(disputeId, appeal) {
      var ruling;
      return _regeneratorRuntime.wrap(function _callee16$(_context16) {
        while (1) {
          switch (_context16.prev = _context16.next) {
            case 0:
              _context16.next = 2;
              return _this3.loadContract();

            case 2:
              _context16.next = 4;
              return _this3.contractInstance.getWinningChoice(disputeId, appeal);

            case 4:
              ruling = _context16.sent;
              return _context16.abrupt('return', ruling.toNumber());

            case 6:
            case 'end':
              return _context16.stop();
          }
        }
      }, _callee16, _this3);
    }));

    return function (_x32, _x33) {
      return _ref18.apply(this, arguments);
    };
  }();

  this.getPeriod = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17() {
    var currentPeriod;
    return _regeneratorRuntime.wrap(function _callee17$(_context17) {
      while (1) {
        switch (_context17.prev = _context17.next) {
          case 0:
            _context17.next = 2;
            return _this3.loadContract();

          case 2:
            _context17.next = 4;
            return _this3.contractInstance.period();

          case 4:
            currentPeriod = _context17.sent;
            return _context17.abrupt('return', currentPeriod.toNumber());

          case 6:
          case 'end':
            return _context17.stop();
        }
      }
    }, _callee17, _this3);
  }));
  this.getSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18() {
    var currentSession;
    return _regeneratorRuntime.wrap(function _callee18$(_context18) {
      while (1) {
        switch (_context18.prev = _context18.next) {
          case 0:
            _context18.next = 2;
            return _this3.loadContract();

          case 2:
            _context18.next = 4;
            return _this3.contractInstance.session();

          case 4:
            currentSession = _context18.sent;
            return _context18.abrupt('return', currentSession.toNumber());

          case 6:
          case 'end':
            return _context18.stop();
        }
      }
    }, _callee18, _this3);
  }));

  this.getDisputesForJuror = function () {
    var _ref21 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee20(account) {
      var openDisputes, disputes;
      return _regeneratorRuntime.wrap(function _callee20$(_context20) {
        while (1) {
          switch (_context20.prev = _context20.next) {
            case 0:
              _context20.next = 2;
              return _this3.loadContract();

            case 2:
              _context20.next = 4;
              return _this3.getOpenDisputesForSession();

            case 4:
              openDisputes = _context20.sent;
              _context20.next = 7;
              return _Promise.all(openDisputes.map(function () {
                var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19(disputeData) {
                  var draws;
                  return _regeneratorRuntime.wrap(function _callee19$(_context19) {
                    while (1) {
                      switch (_context19.prev = _context19.next) {
                        case 0:
                          _context19.next = 2;
                          return _this3.getDrawsForJuror(disputeData.disputeId, account);

                        case 2:
                          draws = _context19.sent;

                          disputeData.appealDraws = disputeData.appealDraws || [];
                          disputeData.appealDraws[disputeData.numberOfAppeals] = draws;

                          return _context19.abrupt('return', disputeData);

                        case 6:
                        case 'end':
                          return _context19.stop();
                      }
                    }
                  }, _callee19, _this3);
                }));

                return function (_x35) {
                  return _ref22.apply(this, arguments);
                };
              }()));

            case 7:
              disputes = _context20.sent;
              return _context20.abrupt('return', disputes);

            case 9:
            case 'end':
              return _context20.stop();
          }
        }
      }, _callee20, _this3);
    }));

    return function (_x34) {
      return _ref21.apply(this, arguments);
    };
  }();

  this.getDrawsForJuror = function () {
    var _ref23 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee21(disputeId, account) {
      var numberOfJurors, draws, draw, isJuror;
      return _regeneratorRuntime.wrap(function _callee21$(_context21) {
        while (1) {
          switch (_context21.prev = _context21.next) {
            case 0:
              _context21.next = 2;
              return _this3.loadContract();

            case 2:
              _context21.next = 4;
              return _this3.getAmountOfJurorsForDispute(disputeId);

            case 4:
              numberOfJurors = _context21.sent;
              draws = [];
              draw = 1;

            case 7:
              if (!(draw <= numberOfJurors)) {
                _context21.next = 15;
                break;
              }

              _context21.next = 10;
              return _this3.isJurorDrawnForDispute(disputeId, draw, account);

            case 10:
              isJuror = _context21.sent;

              if (isJuror) {
                draws.push(draw);
              }

            case 12:
              draw++;
              _context21.next = 7;
              break;

            case 15:
              return _context21.abrupt('return', draws);

            case 16:
            case 'end':
              return _context21.stop();
          }
        }
      }, _callee21, _this3);
    }));

    return function (_x36, _x37) {
      return _ref23.apply(this, arguments);
    };
  }();

  this.getOpenDisputesForSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee22() {
    var currentSession, openDisputes, disputeId, dispute;
    return _regeneratorRuntime.wrap(function _callee22$(_context22) {
      while (1) {
        switch (_context22.prev = _context22.next) {
          case 0:
            _context22.next = 2;
            return _this3.loadContract();

          case 2:
            _context22.next = 4;
            return _this3.getSession();

          case 4:
            currentSession = _context22.sent;
            openDisputes = [];
            disputeId = 0;
            dispute = void 0;

          case 8:
            if (!1) {
              _context22.next = 27;
              break;
            }

            _context22.prev = 9;
            _context22.next = 12;
            return _this3.getDispute(disputeId);

          case 12:
            dispute = _context22.sent;
            _context22.next = 21;
            break;

          case 15:
            _context22.prev = 15;
            _context22.t0 = _context22['catch'](9);

            if (!(_context22.t0.message === errorConstants.UNABLE_TO_FETCH_DISPUTE)) {
              _context22.next = 19;
              break;
            }

            return _context22.abrupt('break', 27);

          case 19:
            console.error(_context22.t0);
            throw _context22.t0;

          case 21:
            if (!(dispute.arbitrableContractAddress === ethConstants.NULL_ADDRESS)) {
              _context22.next = 23;
              break;
            }

            return _context22.abrupt('break', 27);

          case 23:

            // If dispute is in the current session, add it to the result array
            if (dispute.firstSession + dispute.numberOfAppeals === currentSession) openDisputes.push(dispute);

            // Advance to the next dispute
            disputeId++;
            _context22.next = 8;
            break;

          case 27:
            return _context22.abrupt('return', openDisputes);

          case 28:
          case 'end':
            return _context22.stop();
        }
      }
    }, _callee22, _this3, [[9, 15]]);
  }));

  this.getDeadlineForOpenDispute = function () {
    var _ref25 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() {
      var period = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : arbitratorConstants.PERIOD.VOTE;
      var lastPeriodChange, result;
      return _regeneratorRuntime.wrap(function _callee23$(_context23) {
        while (1) {
          switch (_context23.prev = _context23.next) {
            case 0:
              _context23.next = 2;
              return _this3.loadContract();

            case 2:
              _context23.next = 4;
              return _this3.contractInstance.lastPeriodChange();

            case 4:
              lastPeriodChange = _context23.sent.toNumber();
              _context23.t0 = lastPeriodChange;
              _context23.next = 8;
              return _this3.getTimeForPeriod(period);

            case 8:
              _context23.t1 = _context23.sent;
              _context23.t2 = _context23.t0 + _context23.t1;
              result = 1000 * _context23.t2;
              return _context23.abrupt('return', result);

            case 12:
            case 'end':
              return _context23.stop();
          }
        }
      }, _callee23, _this3);
    }));

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

  this.getData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee24() {
    var _ref27, _ref28, pinakionContractAddress, rngContractAddress, period, session, lastPeriodChange;

    return _regeneratorRuntime.wrap(function _callee24$(_context24) {
      while (1) {
        switch (_context24.prev = _context24.next) {
          case 0:
            _context24.next = 2;
            return _this3.loadContract();

          case 2:
            _context24.next = 4;
            return _Promise.all([_this3.contractInstance.pinakion(), _this3.contractInstance.rng(), _this3.contractInstance.period(), _this3.contractInstance.session(), _this3.contractInstance.lastPeriodChange()]);

          case 4:
            _ref27 = _context24.sent;
            _ref28 = _slicedToArray(_ref27, 5);
            pinakionContractAddress = _ref28[0];
            rngContractAddress = _ref28[1];
            period = _ref28[2];
            session = _ref28[3];
            lastPeriodChange = _ref28[4];
            return _context24.abrupt('return', {
              pinakionContractAddress: pinakionContractAddress,
              rngContractAddress: rngContractAddress,
              period: period.toNumber(),
              session: session.toNumber(),
              lastPeriodChange: lastPeriodChange.toNumber()
            });

          case 12:
          case 'end':
            return _context24.stop();
        }
      }
    }, _callee24, _this3);
  }));
};

export default KlerosPOC;
//# sourceMappingURL=KlerosPOC.js.map