contract TokenSwap is
  Pausable,
  Destructible
{
  using SafeMath for uint;

  address public baseTokenAddress;
  address public quoteTokenAddress;

  address public wallet;

  uint public buyRate;
  uint public buyRateDecimals;
  uint public sellRate;
  uint public sellRateDecimals;

  event LogWithdrawToken(
    address indexed _from,
    address indexed _token,
    uint amount
  );
  event LogSetWallet(address indexed _wallet);
  event LogSetBaseTokenAddress(address indexed _token);
  event LogSetQuoteTokenAddress(address indexed _token);
  event LogSetRateAndRateDecimals(
    uint _buyRate,
    uint _buyRateDecimals,
    uint _sellRate,
    uint _sellRateDecimals
  );
  event LogSetNumberOfZeroesFromLastDigit(
    uint _numberOfZeroesFromLastDigit
  );
  event LogTokenSwap(
    address indexed _userAddress,
    address indexed _userSentTokenAddress,
    uint _userSentTokenAmount,
    address indexed _userReceivedTokenAddress,
    uint _userReceivedTokenAmount
  );

  /**
   * @dev Contract constructor.
   * @param _baseTokenAddress  The base of the swap pair.
   * @param _quoteTokenAddress The quote of the swap pair.
   * @param _buyRate Purchase rate, how many baseToken for the given quoteToken.
   * @param _buyRateDecimals Define the decimals precision for the given asset.
   * @param _sellRate Purchase rate, how many quoteToken for the given baseToken.
   * @param _sellRateDecimals Define the decimals precision for the given asset.
   */
  constructor(
    address _baseTokenAddress,
    address _quoteTokenAddress,
    address _wallet,
    uint _buyRate,
    uint _buyRateDecimals,
    uint _sellRate,
    uint _sellRateDecimals
  )
    public
  {
    require(_wallet != address(0), "_wallet == address(0)");
    baseTokenAddress = _baseTokenAddress;
    quoteTokenAddress = _quoteTokenAddress;
    wallet = _wallet;
    buyRate = _buyRate;
    buyRateDecimals = _buyRateDecimals;
    sellRate = _sellRate;
    sellRateDecimals = _sellRateDecimals;
  }

  function()
    external
    whenNotPaused
    payable
  {
    require(isETH(quoteTokenAddress), 'Cannot use fallback, the quote set is not ETH');

    require(swapToken(quoteTokenAddress, msg.value), 'Swap failed');
  }

  /**
   * @dev Set base token address.
   * @param _baseTokenAddress The pair base token address.
   * @return bool.
   */
  function setBaseTokenAddress(address _baseTokenAddress)
    public
    onlyOwner
    returns (bool)
  {
    baseTokenAddress = _baseTokenAddress;
    emit LogSetBaseTokenAddress(_baseTokenAddress);
    return true;
  }

  /**
   * @dev Set quote token address.
   * @param _quoteTokenAddress The quote token address.
   * @return bool.
   */
  function setQuoteTokenAddress(address _quoteTokenAddress)
    public
    onlyOwner
    returns (bool)
  {
    quoteTokenAddress = _quoteTokenAddress;
    emit LogSetQuoteTokenAddress(_quoteTokenAddress);
    return true;
  }

  /**
   * @dev Set wallet sc address.
   * @param _wallet The wallet sc address.
   * @return bool.
   */
  function setWallet(address _wallet)
    public
    onlyOwner
    returns (bool)
  {
    require(_wallet != address(0), "_wallet == address(0)");
    wallet = _wallet;
    emit LogSetWallet(_wallet);
    return true;
  }

  /**
   * @dev Set rate.
   * @param _buyRate Multiplier, how many base token for the quote token.
   * @param _buyRateDecimals Number of significan digits of the rate.
   * @param _sellRate Multiplier, how many quote token for the base token.
   * @param _sellRateDecimals Number of significan digits of the rate.
   * @return bool.
   */
  function setRateAndRateDecimals(
    uint _buyRate,
    uint _buyRateDecimals,
    uint _sellRate,
    uint _sellRateDecimals
  )
    public
    onlyOwner
    returns (bool)
  {
    require(_buyRate != buyRate, "_buyRate == buyRate");
    require(_buyRate != 0, "_buyRate == 0");
    require(_sellRate != sellRate, "_sellRate == sellRate");
    require(_sellRate != 0, "_sellRate == 0");
    buyRate = _buyRate;
    sellRate = _sellRate;
    buyRateDecimals = _buyRateDecimals;
    sellRateDecimals = _sellRateDecimals;
    emit LogSetRateAndRateDecimals(
      _buyRate,
      _buyRateDecimals,
      _sellRate,
      _sellRateDecimals
    );
    return true;
  }

  /**
   * @dev Withdraw asset.
   * @param _tokenAddress Asset to be withdrawed.
   * @return bool.
   */
  function withdrawToken(address _tokenAddress)
    public
    onlyOwner
    returns(bool)
  {
    uint tokenBalance;
    if (isETH(_tokenAddress)) {
      tokenBalance = address(this).balance;
      msg.sender.transfer(tokenBalance);
    } else {
      tokenBalance = ERC20(_tokenAddress).balanceOf(address(this));
      require(
        SafeTransfer._safeTransfer(_tokenAddress, msg.sender, tokenBalance),
        "withdraw transfer failed"
      );
    }
    emit LogWithdrawToken(msg.sender, _tokenAddress, tokenBalance);
    return true;
  }

  /**
   * @dev Understand if the user swap request is a BUY or a SELL.
   * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base).
   * @return bool.
   */

  function isBuy(address _offerTokenAddress)
    public
    view
    returns (bool)
  {
    return _offerTokenAddress == quoteTokenAddress;
  }

  /**
   * @dev Understand if the token is ETH or not.
   * @param _tokenAddress The token address the purchaser is offering (It may be the quote or the base).
   * @return bool.
   */

  function isETH(address _tokenAddress)
    public
    pure
    returns (bool)
  {
    return _tokenAddress == address(0);
  }

  /**
   * @dev Understand if the user swap request is for the available pair.
   * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base).
   * @return bool.
   */

  function isOfferInPair(address _offerTokenAddress)
    public
    view
    returns (bool)
  {
    return _offerTokenAddress == quoteTokenAddress ||
      _offerTokenAddress == baseTokenAddress;
  }

  /**
   * @dev Function to calculate the number of tokens the user is going to receive.
   * @param _offerTokenAmount The amount of tokne number of WEI to convert in ERC20.
   * @return uint.
   */
  function getAmount(
    uint _offerTokenAmount,
    bool _isBuy
  )
    public
    view
    returns(uint)
  {
    uint amount;
    if (_isBuy) {
      amount = _offerTokenAmount.mul(buyRate).div(10 ** buyRateDecimals);
    } else {
      amount = _offerTokenAmount.mul(sellRate).div(10 ** sellRateDecimals);
    }
    return amount;
  }

  /**
   * @dev Release purchased asset to the buyer based on pair rate.
   * @param _userOfferTokenAddress The token address the purchaser is offering (It may be the quote or the base).
   * @param _userOfferTokenAmount The amount of token the user want to swap.
   * @return bool.
   */
  function swapToken (
    address _userOfferTokenAddress,
    uint _userOfferTokenAmount
  )
    public
    whenNotPaused
    payable
    returns (bool)
  {
    require(_userOfferTokenAmount != 0, "_userOfferTokenAmount == 0");
    // check if offered token address is the base or the quote token address
    require(
      isOfferInPair(_userOfferTokenAddress),
      "_userOfferTokenAddress not in pair"
    );
    // check if the msg.value is consistent when offered token address is eth
    if (isETH(_userOfferTokenAddress)) {
      require(_userOfferTokenAmount == msg.value, "msg.value != _userOfferTokenAmount");
    } else {
      require(msg.value == 0, "msg.value != 0");
    }
    bool isUserBuy = isBuy(_userOfferTokenAddress);
    uint toWalletAmount = _userOfferTokenAmount;
    uint toUserAmount = getAmount(
      _userOfferTokenAmount,
      isUserBuy
    );
    require(toUserAmount > 0, "toUserAmount must be greater than 0");
    if (isUserBuy) {
      // send the quote to wallet
      require(
        _transferAmounts(
          msg.sender,
          wallet,
          quoteTokenAddress,
          toWalletAmount
        ),
        "the transfer from of the quote the user to the TokenSwap SC failed"
      );
      // send the base to user
      require(
        _transferAmounts(
          wallet,
          msg.sender,
          baseTokenAddress,
          toUserAmount
        ),
        "the transfer of the base from the TokenSwap SC to the user failed"
      );
      emit LogTokenSwap(
        msg.sender,
        quoteTokenAddress,
        toWalletAmount,
        baseTokenAddress,
        toUserAmount
      );
    } else {
      // send the base to wallet
      require(
        _transferAmounts(
          msg.sender,
          wallet,
          baseTokenAddress,
          toWalletAmount
        ),
        "the transfer of the base from the user to the TokenSwap SC failed"
      );
      // send the quote to user
      require(
        _transferAmounts(
          wallet,
          msg.sender,
          quoteTokenAddress,
          toUserAmount
        ),
        "the transfer of the quote from the TokenSwap SC to the user failed"
      );
      emit LogTokenSwap(
        msg.sender,
        baseTokenAddress,
        toWalletAmount,
        quoteTokenAddress,
        toUserAmount
      );
    }
    return true;
  }

  /**
   * @dev Transfer amounts from user to this contract and vice versa.
   * @param _from The 'from' address.
   * @param _to The 'to' address.
   * @param _tokenAddress The asset to be transfer.
   * @param _amount The amount to be transfer.
   * @return bool.
   */
  function _transferAmounts(
    address _from,
    address _to,
    address _tokenAddress,
    uint _amount
  )
    private
    returns (bool)
  {
    if (isETH(_tokenAddress)) {
      if (_from == wallet) {
        require(
          IWallet(_from).transferAssetTo(
            _tokenAddress,
            _to,
            _amount
          ),
          "trasnsferAssetTo failed"
        );
      } else {
        _to.transfer(_amount);
      }
    } else {
      if (_from == wallet) {
        require(
          IWallet(_from).transferAssetTo(
            _tokenAddress,
            _to,
            _amount
          ),
          "trasnsferAssetTo failed"
        );
      } else {
        require(
          SafeTransfer._safeTransferFrom(
            _tokenAddress,
            _from,
            _to,
            _amount
        ),
          "transferFrom reserve to _receiver failed"
        );
      }
    }
    return true;
  }
}
/**
 * @title TokenSwap.
 * @author Eidoo SAGL.
 * @dev A swap asset contract. The offerAmount and wantAmount are collected and sent into the contract itself.
 */
function isETH(address _tokenAddress)
  public
  pure
  returns (bool)
{
  return _tokenAddress == address(0);
}

/**
 * @dev Understand if the token is ETH or not.
 * @param _tokenAddress The token address the purchaser is offering (It may be the quote or the base).
 * @return bool.
 */