contract Hype_BetStake is Owned {
    using SafeMath for uint256;
    
    address public Hype_Bet = 0xc9Dfcd0A1dD2D7BB6Fd2EF91A16a6a1c4E9846Dd;
    
    uint256 public totalStakes = 0;
    uint256 public totalDividends = 0;
    uint256 private scaledRemainder = 0;
    uint256 private scaling = uint256(10) ** 12;
    uint public round = 1;
    uint256 public maxAllowed = 200000000000000000000000; //200000 tokens total allowed to be staked
    
    /* Fees breaker, to protect withdraws if anything ever goes wrong */
    bool public breaker = false; // withdraw can be lock,, default unlocked
    mapping(address => uint) public farmLock; // period that your sake it locked to keep it for farming
    //uint public lock = 0; // farm lock in blocks ~ 0 days for 15s/block
    //address public admin;
    
    struct USER{
        uint256 stakedTokens;
        uint256 lastDividends;
        uint256 fromTotalDividend;
        uint round;
        uint256 remainder;
    }
    
        address[] internal stakeholders;
    mapping(address => USER) stakers;
    mapping (uint => uint256) public payouts;                   // keeps record of each payout
    
    event STAKED(address staker, uint256 tokens);
    event EARNED(address staker, uint256 tokens);
    event UNSTAKED(address staker, uint256 tokens);
    event PAYOUT(uint256 round, uint256 tokens, address sender);
    event CLAIMEDREWARD(address staker, uint256 reward);
    event WithdrawalLockDurationSet(uint256 value, address sender);
    
    function setBreaker(bool _breaker) external onlyOwner {
        breaker = _breaker;
    }
    
    
    function isStakeholder(address _address)
       public
       view
       returns(bool)
   {
       for (uint256 s = 0; s < stakeholders.length; s += 1){
           if (_address == stakeholders[s]) return (true);
       }
       return (false);
   }
   
   function addStakeholder(address _stakeholder)
       public
   {
       (bool _isStakeholder) = isStakeholder(_stakeholder);
       if(!_isStakeholder) stakeholders.push(_stakeholder);
   }
   


    // ------------------------------------------------------------------------
    // Token holders can stake their tokens using this function
    // @param tokens number of tokens to stake
    // ------------------------------------------------------------------------
    function STAKE(uint256 tokens) external {
        require(totalStakes <= maxAllowed, "Max Stake amount exceed");
        require(IERC20(Hype_Bet).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user account");
        
        (uint256 transferToAmount,,) = IERC20(Hype_Bet).calculateAmountsAfterFee(msg.sender, address(this), tokens);
        
            
            // add pending rewards to remainder to be claimed by user later, if there is any existing stake
            uint256 owing = pendingReward(msg.sender);
            stakers[msg.sender].remainder += owing;
            
            stakers[msg.sender].stakedTokens = transferToAmount.add(stakers[msg.sender].stakedTokens);
            stakers[msg.sender].lastDividends = owing;
            stakers[msg.sender].fromTotalDividend= totalDividends;
            stakers[msg.sender].round =  round;
            
            (bool _isStakeholder) = isStakeholder(msg.sender);
             if(!_isStakeholder) farmLock[msg.sender] =  block.timestamp;
            
            
            totalStakes = totalStakes.add(transferToAmount);
            
            addStakeholder(msg.sender);
            
            emit STAKED(msg.sender, transferToAmount);
        
    }
    
    // ------------------------------------------------------------------------
    // Owners can send the funds to be distributed to stakers using this function
    // @param tokens number of tokens to distribute
    // ------------------------------------------------------------------------
    function ADDFUNDS(uint256 tokens) external {
        
        require(IERC20(Hype_Bet).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account");
        (uint256 transferToAmount,,) = IERC20(Hype_Bet).calculateAmountsAfterFee(msg.sender, address(this), tokens);
        _addPayout(transferToAmount);
    }
    
    // ------------------------------------------------------------------------
    // Private function to register payouts
    // ------------------------------------------------------------------------
    function _addPayout(uint256 tokens) private{
        // divide the funds among the currently staked tokens
        // scale the deposit and add the previous remainder
        uint256 available = (tokens.mul(scaling)).add(scaledRemainder); 
        uint256 dividendPerToken = available.div(totalStakes);
        scaledRemainder = available.mod(totalStakes);
        
        totalDividends = totalDividends.add(dividendPerToken);
        payouts[round] = payouts[round - 1].add(dividendPerToken);
        
        emit PAYOUT(round, tokens, msg.sender);
        round++;
    }
    
    // ------------------------------------------------------------------------
    // Stakers can claim their pending rewards using this function
    // ------------------------------------------------------------------------
    function CLAIMREWARD() public {
        
        if(totalDividends > stakers[msg.sender].fromTotalDividend){
            uint256 owing = pendingReward(msg.sender);
        
            owing = owing.add(stakers[msg.sender].remainder);
            stakers[msg.sender].remainder = 0;
        
            require(IERC20(Hype_Bet).transfer(msg.sender,owing), "ERROR: error in sending reward from contract");
        
            emit CLAIMEDREWARD(msg.sender, owing);
        
            stakers[msg.sender].lastDividends = owing; // unscaled
            stakers[msg.sender].round = round; // update the round
            stakers[msg.sender].fromTotalDividend = totalDividends; // scaled
        }
    }
    
    // ------------------------------------------------------------------------
    // Get the pending rewards of the staker
    // @param _staker the address of the staker
    // ------------------------------------------------------------------------    
    function pendingReward(address staker) private returns (uint256) {
        require(staker != address(0), "ERC20: sending to the zero address");
        
        uint stakersRound = stakers[staker].round;
        uint256 amount =  ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling);
        stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ;
        return amount;
    }
    
    function getPendingReward(address staker) public view returns(uint256 _pendingReward) {
        require(staker != address(0), "ERC20: sending to the zero address");
         uint stakersRound = stakers[staker].round;
         
        uint256 amount =  ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling);
        amount += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ;
        return (amount.add(stakers[staker].remainder));
    }
    
    // ------------------------------------------------------------------------
    // Stakers can un stake the staked tokens using this function
    // @param tokens the number of tokens to withdraw
    // ------------------------------------------------------------------------
    function WITHDRAW(uint256 tokens) external {
        require(breaker == false, "Admin Restricted WITHDRAW");
        require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
        
        require(farmLock[msg.sender]+10 days <= block.timestamp, "Withdraw can only be done after 10 days");
        
        totalStakes = totalStakes.sub(tokens);
        
        // add pending rewards to remainder to be claimed by user later, if there is any existing stake
        uint256 owing = pendingReward(msg.sender);
        stakers[msg.sender].remainder += owing;
                
        stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
        stakers[msg.sender].lastDividends = owing;
        stakers[msg.sender].fromTotalDividend= totalDividends;
        stakers[msg.sender].round =  round;
        
        
        require(IERC20(Hype_Bet).transfer(msg.sender, tokens), "Error in un-staking tokens");
        emit UNSTAKED(msg.sender, tokens);
    }
    
    // ------------------------------------------------------------------------
    // Private function to calculate 1% percentage
    // ------------------------------------------------------------------------
    function onePercent(uint256 _tokens) private pure returns (uint256){
        uint256 roundValue = _tokens.ceil(100);
        uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2));
        return onePercentofTokens;
    }
    
    // ------------------------------------------------------------------------
    // Get the number of tokens staked by a staker
    // @param _staker the address of the staker
    // ------------------------------------------------------------------------
    function yourStakedHype_Bet(address staker) public view returns(uint256 stakedHype_Bet){
        require(staker != address(0), "ERC20: sending to the zero address");
        
        return stakers[staker].stakedTokens;
    }
    
    // ------------------------------------------------------------------------
    // Get the Hype_Bet balance of the token holder
    // @param user the address of the token holder
    // ------------------------------------------------------------------------
    function yourHype_BetBalance(address user) external view returns(uint256 Hype_BetBalance){
        require(user != address(0), "ERC20: sending to the zero address");
        return IERC20(Hype_Bet).balanceOf(user);
    }
    
   
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
function yourStakedHype_Bet(address staker) public view returns(uint256 stakedHype_Bet){
        require(staker != address(0), "ERC20: sending to the zero address");
        
        return stakers[staker].stakedTokens;
    }
// ------------------------------------------------------------------------
// Get the number of tokens staked by a staker
// @param _staker the address of the staker
// ------------------------------------------------------------------------