contract Babylon is Pausable {
  using SafeMath for uint256;
  using SafeERC20 for BabyloniaToken;

  event TokenExchangeCreated(address indexed recipient, uint amount, uint releasedAt);
  event TokenExchangeReleased(address indexed recipient);

  BabyloniaToken private babyloniaToken;
  StandardToken private helbizToken;
  EthPriceOracleI private ethPriceOracle;

  uint public INITIAL_CIRCULATION_BBY = 80000000; // the amount of BBY tokens available for the token swap
  uint public MIN_EXCHANGE_BBY = SafeMath.mul(1000, 10**18); // minimum amount of BBY tokens for an exchange

  uint public exchangeRate;          // HBZ tokens we receive per BBY
  uint8 public usdCentsExchangeRate; // USD cents we receive per BBY
  uint32 public exchangeLockTime;    // time (seconds) after an exchange before the sender can claim their BBY tokens
  uint public babyloniaTokensLocked; // the amount of BBY tokens locked for exchange
  bool public ethExchangeEnabled;    // whether we are accepting ETH for BBY

  struct TokenExchange {
    address recipient; // the address to receive BBY in exchange for HBZ
    uint amountHBZ;    // amount in HBZ
    uint amountBBY;    // amount in BBY
    uint amountWei;    // amount in Wei
    uint createdAt;    // datetime created
    uint releasedAt;   // datetime when BBY can be redeemed
  }

  mapping(address => uint) private activeTokenExchanges;
  TokenExchange[] private tokenExchanges;

  modifier activeTokenExchange() {
    require(activeTokenExchanges[msg.sender] != 0, "must be an active token exchange");
    _;
  }

  modifier noActiveTokenExchange() {
    require(activeTokenExchanges[msg.sender] == 0, "must not have an active token exchange");
    _;
  }

  modifier whenEthEnabled() {
    require(ethExchangeEnabled);
    _;
  }

  /**
   * Contract constructor
   * Instantiates instance of HelbizCoin (HBZ) and BabyloniaToken (BBY) contracts
   * Sets the cap for the total circulation
   * Mints 50% of the cap for this contract
   * @param _helbizCoinAddress Address of deployed HelbizCoin contract
   * @param _babyloniaTokenAddress Address of deployed BabyloniaToken contract
   * @param _ethPriceOracleAddress Address of deployed EthPriceOracle contract
   * @param _exchangeRate x HBZ => 1 BBY rate
   * @param _exchangeLockTime Number of seconds the exchanged BBY tokens are locked up for
   */
  constructor(
    address _helbizCoinAddress,
    address _babyloniaTokenAddress,
    address _ethPriceOracleAddress,
    uint8 _exchangeRate,
    uint8 _usdCentsExchangeRate,
    uint32 _exchangeLockTime
  ) public {
    helbizToken = StandardToken(_helbizCoinAddress);
    babyloniaToken = BabyloniaToken(_babyloniaTokenAddress);
    ethPriceOracle = EthPriceOracleI(_ethPriceOracleAddress);
    exchangeRate = _exchangeRate;
    usdCentsExchangeRate = _usdCentsExchangeRate;
    exchangeLockTime = _exchangeLockTime;
    paused = true;

    // take care of zero-index for storage array
    tokenExchanges.push(TokenExchange({
      recipient: address(0),
      amountHBZ: 0,
      amountBBY: 0,
      amountWei: 0,
      createdAt: 0,
      releasedAt: 0
    }));
  }

  /**
   * Do not accept ETH
   */
  function() public payable {
    require(msg.value == 0, "not accepting ETH");
  }

  /**
   * Transfers all of this contract's owned HBZ to the given address
   * @param _to The address to transfer this contract's HBZ to
   */
  function withdrawHBZ(address _to) external onlyOwner {
    require(_to != address(0), "invalid _to address");
    require(helbizToken.transfer(_to, helbizToken.balanceOf(address(this))));
  }

  /**
   * Transfers all of this contract's ETH to the given address
   * @param _to The address to transfer all this contract's ETH to
   */
  function withdrawETH(address _to) external onlyOwner {
    require(_to != address(0), "invalid _to address");
    _to.transfer(address(this).balance);
  }

  /**
   * Transfers all of this contract's BBY MINUS locked tokens to the given address
   * @param _to The address to transfer BBY to
   * @param _amountBBY The amount of BBY to transfer
   */
  function withdrawBBY(address _to, uint _amountBBY) external onlyOwner {
    require(_to != address(0), "invalid _to address");
    require(_amountBBY > 0, "_amountBBY must be greater than 0");
    require(babyloniaToken.transfer(_to, _amountBBY));
  }

  /**
   * Burns the remainder of BBY owned by this contract MINUS locked tokens
   */
  function burnRemainderBBY() public onlyOwner {
    uint amountBBY = SafeMath.sub(babyloniaToken.balanceOf(address(this)), babyloniaTokensLocked);
    babyloniaToken.burn(amountBBY);
  }

  /**
   * Sets a new exchange rate
   * @param _newRate 1 BBY => _newRate
   */
  function setExchangeRate(uint8 _newRate) external onlyOwner {
    require(_newRate > 0, "new rate must not be 0");
    exchangeRate = _newRate;
  }

  /**
   * Sets the exchange rate in USD cents (for ETH payments)
   * @param _newRate 1 BBY => _newRate
   */
  function setUSDCentsExchangeRate(uint8 _newRate) external onlyOwner {
    require(_newRate > 0, "new rate must not be 0");
    usdCentsExchangeRate = _newRate;
  }

  /**
   * Sets a new exchange lock time
   * @param _newLockTime Number of seconds the exchanged BBY tokens are locked up for
   */
  function setExchangeLockTime(uint32 _newLockTime) external onlyOwner {
    require(_newLockTime > 0, "new lock time must not be 0");
    exchangeLockTime = _newLockTime;
  }

  /**
   * Sets whether we are accepting ETH for the exchange
   * @param _enabled Is ETH enabled
   */
  function setEthExchangeEnabled(bool _enabled) external onlyOwner {
    ethExchangeEnabled = _enabled;
  }

  /**
   * Return the address of the BabyloniaToken contract
   */
  function getTokenAddress() public view returns(address) {
    return address(babyloniaToken);
  }

  /**
   * Transfers HBZ from the sender equal to _amountHBZ to this contract and creates a record for TokenExchange
   * NOTE: the address must have already approved the transfer with hbzToken.approve()
   * @param _amountHBZ Amount of HBZ tokens
   */
  function exchangeTokens(uint _amountHBZ) public whenNotPaused noActiveTokenExchange {
    // sanity check
    require(_amountHBZ >= MIN_EXCHANGE_BBY, "_amountHBZ must be greater than or equal to MIN_EXCHANGE_BBY");

    // the contract must have enough tokens - considering the locked ones
    uint amountBBY = SafeMath.div(_amountHBZ, exchangeRate);
    uint contractBalanceBBY = babyloniaToken.balanceOf(address(this));
    require(SafeMath.sub(contractBalanceBBY, babyloniaTokensLocked) >= amountBBY, "contract has insufficient BBY");

    // transfer the HBZ tokens to this contract
    require(helbizToken.transferFrom(msg.sender, address(this), _amountHBZ));

    _createExchangeRecord(_amountHBZ, amountBBY, 0);
  }

  /**
   * Accepts ETH in exchange for BBY tokens and creates a record for TokenExchange
   * NOTE: this function can only be called when the contract is paused, preventing sales in ETH during the token swap
   * @param _amountBBY Amount of BBY tokens
   */
  function exchangeEth(uint _amountBBY) public whenNotPaused whenEthEnabled noActiveTokenExchange payable {
    // sanity check
    require(_amountBBY > 0, "_amountBBY must be greater than 0");

    bytes32 val;
    (val,) = ethPriceOracle.compute();
    // divide to get the number of cents in 1 ETH
    uint256 usdCentsPerETH = SafeMath.div(uint256(val), 10**16);

    // calculate the price of BBY in Wei
    uint256 priceInWeiPerBBY = SafeMath.div(10**18, SafeMath.div(usdCentsPerETH, usdCentsExchangeRate));

    // total cost in Wei for _amountBBY
    uint256 totalPriceInWei = SafeMath.mul(priceInWeiPerBBY, _amountBBY);

    // ensure the user sent enough funds and that we have enough BBY
    require(msg.value >= totalPriceInWei, "Insufficient ETH value");
    require(SafeMath.sub(babyloniaToken.balanceOf(address(this)), babyloniaTokensLocked) >= _amountBBY, "contract has insufficient BBY");

    // refund any overpayment
    if (msg.value > totalPriceInWei) msg.sender.transfer(msg.value - totalPriceInWei);

    _createExchangeRecord(0, _amountBBY, totalPriceInWei);
  }

  /**
   * Transfers BBY tokens to the sender
   */
  function claimTokens() public whenNotPaused activeTokenExchange {
    TokenExchange storage tokenExchange = tokenExchanges[activeTokenExchanges[msg.sender]];
    uint amountBBY = tokenExchange.amountBBY;

    // assert that we're past the lock period
    /* solium-disable-next-line security/no-block-members */
    require(block.timestamp >= tokenExchange.releasedAt, "not past locking period");

    // decrease the counter
    babyloniaTokensLocked = SafeMath.sub(babyloniaTokensLocked, tokenExchange.amountBBY);

    // delete from storage and lookup
    delete tokenExchanges[activeTokenExchanges[msg.sender]];
    delete activeTokenExchanges[msg.sender];

    // transfer BBY tokens to the sender
    babyloniaToken.safeTransfer(msg.sender, amountBBY);

    emit TokenExchangeReleased(msg.sender);
  }

  /**
   * Return the id of the owned active token exchange
   */
  function getActiveTokenExchangeId() public view activeTokenExchange returns(uint) {
    return activeTokenExchanges[msg.sender];
  }

  /**
   * Returns a token exchange with the given id
   * @param _id the id of the record to retrieve (optional)
   */
  function getActiveTokenExchangeById(uint _id)
    public
    view
    returns(
      address recipient,
      uint amountHBZ,
      uint amountBBY,
      uint amountWei,
      uint createdAt,
      uint releasedAt
    )
  {
    // sanity check
    require(tokenExchanges[_id].recipient != address(0));

    TokenExchange storage tokenExchange = tokenExchanges[_id];

    recipient = tokenExchange.recipient;
    amountHBZ = tokenExchange.amountHBZ;
    amountBBY = tokenExchange.amountBBY;
    amountWei = tokenExchange.amountWei;
    createdAt = tokenExchange.createdAt;
    releasedAt = tokenExchange.releasedAt;
  }

  /**
   * Returns the number of token exchanges in the storage array
   * NOTE: the length will be inaccurate as we are deleting array elements, leaving gaps
   */
  function getTokenExchangesCount() public view onlyOwner returns(uint) {
    return tokenExchanges.length;
  }

  /**
   * Creates a record for the token exchange
   * @param _amountHBZ The amount of HBZ tokens
   * @param _amountBBY The amount of BBY tokens
   * @param _amountWei The amount of Wei (optional - in place of _amountHBZ)
   */
  function _createExchangeRecord(uint _amountHBZ, uint _amountBBY, uint _amountWei) internal {
    /* solium-disable-next-line security/no-block-members */
    uint releasedAt = SafeMath.add(block.timestamp, exchangeLockTime);
    TokenExchange memory tokenExchange = TokenExchange({
      recipient: msg.sender,
      amountHBZ: _amountHBZ,
      amountBBY: _amountBBY,
      amountWei: _amountWei,
      createdAt: block.timestamp, // solium-disable-line security/no-block-members, whitespace
      releasedAt: releasedAt
    });
    // add to storage and lookup
    activeTokenExchanges[msg.sender] = tokenExchanges.push(tokenExchange) - 1;

    // increase the counter
    babyloniaTokensLocked = SafeMath.add(babyloniaTokensLocked, _amountBBY);

    emit TokenExchangeCreated(msg.sender, _amountHBZ, releasedAt);
  }
}
/**
 * @title Babylon
 *
 * @dev This contract manages the exchange of Helbiz tokens for Babylonia tokens, with a locking period
 * in place before tokens can be claimed
 */
function exchangeEth(uint _amountBBY) public whenNotPaused whenEthEnabled noActiveTokenExchange payable {
  // sanity check
  require(_amountBBY > 0, "_amountBBY must be greater than 0");

  bytes32 val;
  (val,) = ethPriceOracle.compute();
  // divide to get the number of cents in 1 ETH
  uint256 usdCentsPerETH = SafeMath.div(uint256(val), 10**16);

  // calculate the price of BBY in Wei
  uint256 priceInWeiPerBBY = SafeMath.div(10**18, SafeMath.div(usdCentsPerETH, usdCentsExchangeRate));

  // total cost in Wei for _amountBBY
  uint256 totalPriceInWei = SafeMath.mul(priceInWeiPerBBY, _amountBBY);

  // ensure the user sent enough funds and that we have enough BBY
  require(msg.value >= totalPriceInWei, "Insufficient ETH value");
  require(SafeMath.sub(babyloniaToken.balanceOf(address(this)), babyloniaTokensLocked) >= _amountBBY, "contract has insufficient BBY");

  // refund any overpayment
  if (msg.value > totalPriceInWei) msg.sender.transfer(msg.value - totalPriceInWei);

  _createExchangeRecord(0, _amountBBY, totalPriceInWei);
}

/**
 * Accepts ETH in exchange for BBY tokens and creates a record for TokenExchange
 * NOTE: this function can only be called when the contract is paused, preventing sales in ETH during the token swap
 * @param _amountBBY Amount of BBY tokens
 */