contract Referrals is Ownable, ReentrancyGuard {
  using SafeMath for uint;

  //1% - 100, 10% - 1000 50% - 5000
  uint256[] public affLevelReward;
  Affiliates public aff;

  constructor (address _aff) public {
    require(_aff != address(0));
    aff = Affiliates(_aff);

    // two upper levels for each: winner and loser
    // total sum of level's % must be 100%
    //1% - 100, 10% - 1000 50% - 5000
    affLevelReward.push(0); // level 0, 10% - player self - cacheback
    affLevelReward.push(8000); // level 1, 70% of affPool
    affLevelReward.push(2000); // level 2, 20% of affPool
  }


  //AFFILIATES
  function setAffiliateLevel(uint256 _level, uint256 _rewardPercent) external onlyOwner {
    require(_level < affLevelReward.length);
    affLevelReward[_level] = _rewardPercent;
  }

  function incAffiliateLevel(uint256 _rewardPercent) external onlyOwner {
    affLevelReward.push(_rewardPercent);
  }

  function decAffiliateLevel() external onlyOwner {
    delete affLevelReward[affLevelReward.length--];
  }

  function affLevelsCount() external view returns (uint) {
    return affLevelReward.length;
  }

  function _distributeAffiliateReward(uint256 _sum, uint256 _affCode, uint256 _level, bool _cacheBack) internal {
    uint upAffCode = aff.upAffCode(_affCode);

    if (affLevelReward[_level] > 0 && _affCode != 0 && (_level > 0 || (_cacheBack && upAffCode != 0))) {
      uint total = _getPercent(_sum, affLevelReward[_level]);
      aff.plusByCode.value(total)(address(0x0), _affCode, total);
    }

    if (affLevelReward.length > ++_level) {
      _distributeAffiliateReward(_sum, upAffCode, _level, false);
    }
  }

  function getAffReward() external nonReentrant {
    aff.sendAffReward(address(0x0), msg.sender);
  }

  //1% - 100, 10% - 1000 50% - 5000
  function _getPercent(uint256 _v, uint256 _p) internal pure returns (uint)    {
    return _v.mul(_p) / 10000;
  }
}
function setAffiliateLevel(uint256 _level, uint256 _rewardPercent) external onlyOwner {
    require(_level < affLevelReward.length);
    affLevelReward[_level] = _rewardPercent;
  }
//AFFILIATES