contract USDTETHPool is StakeTokenWrapper, IRewardDistributionRecipient {
    IERC20 public defi = IERC20(0x77c329b7C9E2632A77Aca45074d92AB027898c0e);
    
    address payable public projectAddress;
    uint256 public constant DURATION = 7 days;
    uint256 public constant RewardDuration = 1 days;
    uint256 public constant startTime = 1607000400;
    uint256 public periodFinish = 0;
    uint256 public rewardRate = 0;
    uint256 public lastUpdateTime; 
    uint256 public rewardPerTokenStored = 0;
    uint256 public totalBurnReward = 0;
    uint256[] public stakePool = new uint256[](1); 
    uint256[] public burnPool = new uint256[](1);
    bool private open = true;
    uint256 private constant _gunit = 1e18;
    
    struct Deposit {
      uint256 amount;
      uint256 stakeTime;
      uint256 stakeRewardPerTokenStored;
      uint256 round;
   }
   
   struct User {
      Deposit[] deposits;
   }
    
    mapping(address => uint256) public userRewardPerTokenPaid; 
    mapping(address => uint256) public rewards; // Unclaimed rewards
    mapping (address => User) internal users;

    event RewardAdded(uint256 reward);
    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(address indexed user, uint256 reward);
    event SetOpen(bool _open);

    constructor(address payable projectAddr) public {
        projectAddress = projectAddr;
    }
    
    function _autoExendArray(uint256[] storage arr, uint256 index) internal{
        if(index >= arr.length){
            arr.length = index.add(1);
        }
    }
    
    function getRound(uint256 beginTime) public view returns (uint256) {
        if(block.timestamp <= beginTime) return 0;
        return block.timestamp.sub(beginTime).div(RewardDuration);
    }
    
    function getUser(address adrr,uint256 index) public view returns (uint256,uint256,uint256,uint256) {
        return (users[adrr].deposits[index].amount,users[adrr].deposits[index].stakeTime,users[adrr].deposits[index].stakeRewardPerTokenStored,users[adrr].deposits[index].round);
    }
    
    function getBurnPoolReward(uint256 index) public view returns (uint256) {
        if(index >= burnPool.length) return 0;
        return burnPool[index];
    }

    function getTotalBurnPoolReward() public view returns (uint256) {
        uint256 totalBurnPoolReward = 0;
        for(uint256 i = 0; i < burnPool.length; i++){
            totalBurnPoolReward = totalBurnPoolReward.add(burnPool[i]);
        }
        return totalBurnPoolReward;
    }

    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = lastTimeRewardApplicable();
        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = rewardPerTokenStored;
        }
        _;
    }

    function lastTimeRewardApplicable() public view returns (uint256) {
        return Math.min(block.timestamp, periodFinish);
    }

    /**
     * Calculate the rewards for each token
     */
    function rewardPerToken() public view returns (uint256) {
        if (totalSupply() == 0) {
            return rewardPerTokenStored;
        }
        return
            rewardPerTokenStored.add(
                lastTimeRewardApplicable()
                    .sub(lastUpdateTime)
                    .mul(rewardRate)
                    .mul(_gunit)
                    .div(totalSupply())
            );
    }

    function earned(address account) public view returns (uint256) {
        return
            balanceOf(account)
                .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                .div(_gunit)
                .add(rewards[account]);
    }

    function stake(uint256 amount) public checkOpen checkStart updateReward(msg.sender){ 
        require(amount > 0, "Cannot stake 0");
        super.stake(amount);
        uint256 round = getRound(startTime);
        _autoExendArray(stakePool,round);
        _autoExendArray(burnPool,round);
        stakePool[round] = stakePool[round].add(amount);
        uint256 updateTime = lastTimeRewardApplicable();
        users[msg.sender].deposits.push(Deposit(amount, updateTime, rewardPerTokenStored,round));
        emit Staked(msg.sender, amount);
    }

    function withdraw(uint256 amount) public checkStart updateReward(msg.sender){
        require(amount > 0, "Cannot withdraw 0");
        getReward();
        super.withdraw(amount);
        uint256 totalAmount = amount;
        for (uint256 i = 0; i < users[msg.sender].deposits.length; i++) {
            uint256 userAmount = users[msg.sender].deposits[i].amount;
            uint256 userRound = users[msg.sender].deposits[i].round;
            if(totalAmount == 0 ) break;
            if(userAmount >= totalAmount){
                users[msg.sender].deposits[i].amount = users[msg.sender].deposits[i].amount.sub(totalAmount);
                stakePool[userRound] = stakePool[userRound].sub(totalAmount);
                totalAmount = 0;
            }else{
                stakePool[userRound] = stakePool[userRound].sub(users[msg.sender].deposits[i].amount);
                users[msg.sender].deposits[i].amount = 0;
                totalAmount = totalAmount.sub(userAmount);
            }
        }
        emit Withdrawn(msg.sender, amount);
    }

    function getReward() public checkStart updateReward(msg.sender){
        uint256 reward = earned(msg.sender);
        if (reward > 0) {
            rewards[msg.sender] = 0;
            uint256 taxAmount = tax(msg.sender);
            uint256 burnReward = _updateBurnReward(msg.sender);
            uint256 round = getRound(startTime);
            _autoExendArray(burnPool,round);
            _autoExendArray(stakePool,round.add(1));
            totalBurnReward = totalBurnReward.add(taxAmount);
            burnPool[round] = burnPool[round].add(taxAmount);
            defi.safeTransfer(projectAddress, reward.div(10));
            defi.safeTransfer(msg.sender, reward.mul(9).div(10).sub(taxAmount).add(burnReward));
            uint256 updateTime = lastTimeRewardApplicable();
            for (uint256 i = 0; i < users[msg.sender].deposits.length; i++) {
                if(users[msg.sender].deposits[i].amount != 0){
                    uint256 userRound = users[msg.sender].deposits[i].round;
                    stakePool[userRound] = stakePool[userRound].sub(users[msg.sender].deposits[i].amount);
                    users[msg.sender].deposits[i].stakeTime = updateTime;
                    users[msg.sender].deposits[i].stakeRewardPerTokenStored = userRewardPerTokenPaid[msg.sender];
                    users[msg.sender].deposits[i].round = round.add(1);
                    stakePool[round.add(1)] = stakePool[round.add(1)].add(users[msg.sender].deposits[i].amount);
                }
            }
            emit RewardPaid(msg.sender, reward);
        }
    }
    
    function getTaxRate(uint256 stakeTime) public view returns(uint256) {
        uint256 taxRate = lastTimeRewardApplicable()
                                .sub(stakeTime)
                                .mul(100)
                                .div(RewardDuration)
                                .div(3);
        return taxRate;
    }

    function tax(address account) public view returns(uint256) {
        uint256 taxAmount = 0;
        uint256 taxRewardPerToken = rewardPerToken();
        for(uint256 i = 0; i < users[account].deposits.length; i++) {
            if(users[account].deposits[i].amount != 0){
                uint256 taxRate = getTaxRate(users[account].deposits[i].stakeTime);
                if(taxRate < 100) {
                    taxRate = uint256(100).sub(taxRate);
                    uint256 userRewardPerToken = taxRewardPerToken.sub(users[account].deposits[i].stakeRewardPerTokenStored);
                    uint256 amount =  users[account].deposits[i].amount;
                    taxAmount = taxAmount.add(
                        amount
                            .mul(userRewardPerToken)
                            .mul(9)
                            .div(10)
                            .mul(36)
                            .div(100)
                            .mul(taxRate)
                        );
                }
            }
        }
        return taxAmount.div(_gunit).div(100);
    }
    
     function getBurnReward(address account) public view returns(uint256) {
        uint256 endIndex =  getRound(startTime);
        if(endIndex < 3 || users[account].deposits.length == 0){
            return 0;
        }
        uint256 burnRewardAmount = 0;
        uint256[] memory tempBurnPool = burnPool;
        
        for (uint256 i = 0; i < users[account].deposits.length; i++) {
            if(users[account].deposits[i].amount != 0){
                if(users[account].deposits[i].round == 0){
                    uint256 reward = 0;
                    for(uint256 j = 0; j < 3; j++){
                        reward = reward.add(tempBurnPool[j]);
                    }
                    burnRewardAmount = burnRewardAmount.add(
                                            reward.mul(users[account].deposits[i].amount)
                                            .div(stakePool[0])
                                        );
                }
                uint256 userRound = users[account].deposits[i].round == 0 ? 1 : users[account].deposits[i].round;
                if(endIndex >= userRound.add(3)){
                    uint256 stakeRealAmount = 0;
                    for(uint256 j = 0; j < userRound; j++){
                        stakeRealAmount = stakeRealAmount.add(stakePool[j]);
                    }
                    for(uint256 j = userRound; j < tempBurnPool.length - 3; j++ ){
                        stakeRealAmount = stakeRealAmount.add(stakePool[j]);
                        uint reward = tempBurnPool[j.add(2)].mul(users[account].deposits[i].amount).div(stakeRealAmount);
                        burnRewardAmount = burnRewardAmount.add(reward); 
                    }
                }
            }
        }
        
        return burnRewardAmount;
    }
    
    function _updateBurnReward(address account) internal returns(uint256) {
        uint256 endIndex =  getRound(startTime);
        if(endIndex < 3 || users[account].deposits.length == 0){
            return 0;
        }
        uint256 burnRewardAmount = 0;
        uint256[] memory tempBurnPool = burnPool;
        
        for (uint256 i = 0; i < users[account].deposits.length; i++) {
            if(users[account].deposits[i].amount != 0){
                if(users[account].deposits[i].round == 0){
                    uint256 reward = 0;
                    for(uint256 j = 0; j < 3; j++){
                        reward = reward.add(tempBurnPool[j]);
                    }
                    burnRewardAmount = burnRewardAmount.add(reward.mul(users[account].deposits[i].amount).div(stakePool[0]));
                    uint256 totalBurnRewardAmount = burnRewardAmount;
                    for (uint256 j = 0; j < 3; j++) {
                        if(totalBurnRewardAmount == 0 ) break;
                        if(burnPool[j] >= totalBurnRewardAmount){
                            burnPool[j] = burnPool[j].sub(totalBurnRewardAmount);
                            totalBurnRewardAmount = 0;
                        }else{
                            totalBurnRewardAmount = totalBurnRewardAmount.sub(burnPool[j]);
                            burnPool[j] = 0;
                        }
                    }
                }
                uint256 userRound = users[account].deposits[i].round == 0 ? 1 : users[account].deposits[i].round;
                if(endIndex >= userRound.add(3)){
                    uint256 stakeRealAmount = 0;
                    for(uint256 j = 0; j < userRound; j++){
                        stakeRealAmount = stakeRealAmount.add(stakePool[j]);
                    }
                    for(uint256 j = userRound; j < tempBurnPool.length - 3; j++ ){
                        stakeRealAmount = stakeRealAmount.add(stakePool[j]);
                        uint reward = tempBurnPool[j.add(2)].mul(users[account].deposits[i].amount).div(stakeRealAmount);
                        burnRewardAmount = burnRewardAmount.add(reward);
                        burnPool[j.add(2)] = burnPool[j.add(2)].add(reward);
                    }
                }
            }
        }
        
        return burnRewardAmount;
    }

    modifier checkStart(){
        require(block.timestamp > startTime,"Not start");
        _;
    }

    modifier checkOpen() {
        require(open, "Pool is closed");
        _;
    }

    function getPeriodFinish() external view returns (uint256) {
        return periodFinish;
    }

    function isOpen() external view returns (bool) {
        return open;
    }

    function setOpen(bool _open) external onlyOwner {
        open = _open;
        emit SetOpen(_open);
    }

    function notifyRewardAmount(uint256 reward)
        external
        onlyRewardDistribution
        checkOpen
        updateReward(address(0)){
        if (block.timestamp > startTime){
            if (block.timestamp >= periodFinish) {
                uint256 period = block.timestamp.sub(startTime).div(DURATION).add(1);
                periodFinish = startTime.add(period.mul(DURATION));
                rewardRate = reward.div(periodFinish.sub(block.timestamp));
            } else {
                uint256 remaining = periodFinish.sub(block.timestamp);
                uint256 leftover = remaining.mul(rewardRate);
                rewardRate = reward.add(leftover).div(remaining);
            }
            lastUpdateTime = block.timestamp;
        }else {
          rewardRate = reward.div(DURATION);
          periodFinish = startTime.add(DURATION);
          lastUpdateTime = startTime;
        }

        defi.mint(address(this),reward);
        emit RewardAdded(reward);

        // avoid overflow to lock assets
        _checkRewardRate();
    }
    
    function _checkRewardRate() internal view returns (uint256) {
        return DURATION.mul(rewardRate).mul(_gunit);
    }
}
function rewardPerToken() public view returns (uint256) {
        if (totalSupply() == 0) {
            return rewardPerTokenStored;
        }
        return
            rewardPerTokenStored.add(
                lastTimeRewardApplicable()
                    .sub(lastUpdateTime)
                    .mul(rewardRate)
                    .mul(_gunit)
                    .div(totalSupply())
            );
    }
/**
 * Calculate the rewards for each token
 */