contract MasterChef is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // Info of each user.
    struct UserInfo {
		uint256 pid;
        uint256 amount;     // How many LP tokens the user has provided.
		uint256 reward;
        uint256 rewardPaid; 
		uint256 updateTime;
		uint256 userRewardPerTokenPaid;
    }
	// Info of each user that stakes LP tokens.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
	

	
    // Info of each pool.
    struct PoolInfo {
        IERC20 lpToken;           // Address of LP token contract.
        uint256 allocPoint;       // How many allocation points assigned to this pool. Lefs to distribute per block.
        uint256 lastRewardTime;  // Last block number that Lefs distribution occurs.
        uint256 accLefPerShare; // Accumulated Lefs per share, times 1e18. See below.
		uint256 totalPool;
    }
    // Info of each pool.
    PoolInfo[] public poolInfo;
	

	struct VipPoolInfo {
        uint256 allocPoint;       // How many allocation points assigned to this pool. Lefs to distribute per block.
        uint256 lastTime;  // Last block number that Lefs distribution occurs.
        uint256 rewardPerTokenStored; // Accumulated Lefs per share, times 1e18. See below.
		uint256 vipNumber;
    }

	mapping(uint256 => VipPoolInfo) public vipPoolInfo;
    
	struct User {
        uint id; 
        address referrer; 

		uint256[] referAmount;

		uint256 referReward;

        uint256 totalReward;
	
		uint256 referRewardPerTokenPaid;

        uint256 vip;
    }	
	mapping(address => User) public users;
	

	uint public lastUserId = 2;
	mapping(uint256 => address) public regisUser;

	uint256[] DURATIONS =[3 days, 10 days, 22 days]; 
	
	
	

	bool initialized = false;

    //uint256 public initreward = 1250*1e18;

    uint256 public starttime = 1599829200;//秒

    uint256 public periodFinish = 0;

    uint256 public rewardRate = 0;

    uint256 public totalMinted = 0;

	uint256 public drawPending_threshold = 2000 * 1e18;

	uint256 public indirectRefer_threshold = 58094760000000000;

	

	mapping(uint => uint256) public vipLevel;	
	uint32 vipLevalLength = 0;


	//The Lef TOKEN!
	//  IERC20 public lef = IERC20(0x54CF703014A82B4FF7E9a95DD45e453e1Ba13eb1);
    IERC20 public lef ;



	address public defaultReferAddr = address(0xCfCe2a772ae87c5Fae474b2dE0324ee19C2c145f);
	

    // Total allocation poitns. Must be the sum of all allocation points in all pools.总权重
    uint256 public totalAllocPoint = 0;
    // Bonus muliplier for early lef makers.早期挖矿的额外奖励
    uint256 public constant BONUS_MULTIPLIER = 3;




    event RewardPaid(address indexed user, uint256 reward);
    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event Registration(address indexed user, address indexed referrer, uint indexed userId, uint referrerId);

 
    function initContract (IERC20 _lef,uint256 _rewardRate,uint256 _starttime,uint256 _periodFinish,address _defaultReferAddr) public onlyOwner{	
		require(initialized == false,"has initialized");
        lef = _lef;
		rewardRate = _rewardRate;
		starttime = _starttime;
		periodFinish = _periodFinish;
		defaultReferAddr =  _defaultReferAddr;
	
		User memory user = User({
            id: 1,
            referrer: address(0),
            referAmount:new uint256[](2),
			referReward:0,
			totalReward:0,
			referRewardPerTokenPaid:0,
			vip:0
        });		
		users[defaultReferAddr] = user;	
		
		regisUser[1] = 	defaultReferAddr;
		initialized = true;	
    }


	
	function setVipLevel(uint level,uint256 amount) public onlyOwner {

		if(vipLevalLength < 3){
		
			vipLevalLength++;
		
    	//	uint256 vip1 = 0;
	    //   uint256 vip2 = 0;
		//	uint256 vip3 = 0;
		//  
		//	for(uint i = 1;i < vipLevalLength;i++){
		//		address regAddr = regisUser[i];
		//		uint256 vip = getVipLeval(regAddr);
		//		if(vip == 1){
		//		    vip1 ++;
		//		}else if(vip == 2){
		//		    vip2 ++;
		//		}else if(vip == 3){
		//		    vip3 ++;
		//		}
		//		
		//	}
		//	vipPoolInfo[1].vipNumber = vip1;
		//	vipPoolInfo[2].vipNumber = vip2;
		//	vipPoolInfo[3].vipNumber = vip3;
		//	for(uint i = 1;i < vipLevalLength;i++){
		//		updateVipPool(regisUser[i]);
		//	}
		}
		vipLevel[level] = amount;
		
	}

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }
	

    function isUserExists(address user) public view returns (bool) {
		return (users[user].id != 0);
    }
	

	
	function registrationExt(address referrerAddress) external {
        registration(msg.sender, referrerAddress);
    }

    function registration(address userAddress, address referrerAddress) private {
       //require(msg.value == 0.05 ether, "registration cost 0.05");
        require(!isUserExists(userAddress), "user exists");
        require(isUserExists(referrerAddress), "referrer not exists");
        
        uint32 size;
        assembly {
            size := extcodesize(userAddress)
        }
		require(size == 0, "cannot be a contract");

        
 
        User memory user = User({
            id: lastUserId,
            referrer: referrerAddress,
			referAmount:new uint256[](2),
			totalReward:0,
			referReward:0,
			referRewardPerTokenPaid:0,
			vip:0
        });
		
		regisUser[lastUserId] = userAddress;
        
        users[userAddress] = user;
		
        lastUserId++;
        
        emit  Registration(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id);
    }
	
	function setDrawReferThreshold(uint256 _threshold) public onlyOwner{
		drawPending_threshold = _threshold;
	}

	function drawReferPending() public{
		require(isUserExists(msg.sender), "user exists");
		

		require(getAllDeposit(msg.sender) > drawPending_threshold,"must mt 2000 * 1e18");


		uint256 pengdingReward = 0;

		uint256 vip = getVipLevel(msg.sender);

		if(vip >0){		
			VipPoolInfo storage vipPool = vipPoolInfo[vip];
			User storage user = users[msg.sender];
			uint256 rewardPerTokenStored = vipPool.rewardPerTokenStored;
			uint256 lpSupply = vipPool.vipNumber;
			if (block.timestamp > vipPool.lastTime && lpSupply != 0) {
				uint256 multiplier = getMultiplier(vipPool.lastTime, block.timestamp);
				uint256 lefReward = multiplier.mul(rewardRate).mul(vipPool.allocPoint).div(totalAllocPoint);				
				rewardPerTokenStored = rewardPerTokenStored.add(lefReward.div(lpSupply));
			}				
			 pengdingReward = rewardPerTokenStored.sub(user.referRewardPerTokenPaid).add(users[msg.sender].referReward);
			 safeLefTransfer(msg.sender, pengdingReward);
			 users[msg.sender].referReward = 0;
			 users[msg.sender].totalReward += pengdingReward;
			 user.referRewardPerTokenPaid = rewardPerTokenStored;
		}
	}


	//
	function getReferReward(address _referrer) public view returns(uint256){
	//	require(isUserExists(_referrer), "user exists");
		uint256 pengdingReward = 0;
		if(!isUserExists(_referrer)){
		  return pengdingReward;
		}
		uint256 vip = getVipLevel(_referrer);
		pengdingReward = users[_referrer].referReward;
		if(vip >0){		

			VipPoolInfo storage vipPool = vipPoolInfo[vip];
			User storage user = users[_referrer];
			uint256 rewardPerTokenStored = vipPool.rewardPerTokenStored;
			uint256 lpSupply = vipPool.vipNumber;
			if (block.timestamp > vipPool.lastTime && lpSupply != 0) {
				uint256 multiplier = getMultiplier(vipPool.lastTime, block.timestamp);
				uint256 lefReward = multiplier.mul(rewardRate).mul(vipPool.allocPoint).div(totalAllocPoint);				
				rewardPerTokenStored = rewardPerTokenStored.add(lefReward.div(lpSupply));
			}				
			return rewardPerTokenStored.sub(user.referRewardPerTokenPaid).add(pengdingReward);
		}
		return pengdingReward;
	}
	

    // Add a new lp to the pool. Can only be called by the owner.
    // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
    function addLp(uint256 _allocPoint, IERC20 _lpToken) public onlyOwner {   
        uint256 lastRewardTime = block.timestamp > starttime ? block.timestamp : starttime;
        //totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardTime: lastRewardTime,
            accLefPerShare: 0,
			totalPool:0
        }));		
    }
	
	
	function addVipPoolPoint(uint256 _vipIndex,uint256 _allocPoint) public onlyOwner {
        uint256 lastTime = block.timestamp > starttime ? block.timestamp : starttime;
		vipPoolInfo[_vipIndex].allocPoint = _allocPoint;
		if(vipPoolInfo[_vipIndex].lastTime == 0){
			vipPoolInfo[_vipIndex].lastTime = lastTime;
		}
       // vipPoolInfo[_vipIndex] =VipPoolInfo({
      //      allocPoint: _allocPoint,
        //    lastTime:lastTime,
         //   rewardPerTokenStored:0,
         //   vipNumber:0
      //  }); 
    }

    // Update the given pool's Lef allocation point. Can only be called by the owner.
    function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {

        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
        poolInfo[_pid].allocPoint = _allocPoint;
    }
	
	function setTotalAllocPoint(uint256 _totalAllocPoint) public onlyOwner{
		totalAllocPoint = _totalAllocPoint;
	}
	
	function setRewardRate(uint256 _rewardRate) public onlyOwner {
		rewardRate = _rewardRate;	
	} 

	
  

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        if (_to <= periodFinish) {
            return _to.sub(_from).mul(BONUS_MULTIPLIER);
        } else if (_from >= periodFinish) {
            return _to.sub(_from);
        } else {
            return periodFinish.sub(_from).mul(BONUS_MULTIPLIER).add(
                _to.sub(periodFinish)
            );
        }
    }


    function pendingLef(uint256 _pid, address _user) public view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accLefPerShare = pool.accLefPerShare;
        uint256 lpSupply = pool.totalPool;
		uint256 result = user.reward;
        if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
            uint256 multiplier =  getMultiplier(pool.lastRewardTime, block.timestamp);
            uint256 lefReward = multiplier.mul(rewardRate).mul(pool.allocPoint).div(totalAllocPoint);
            accLefPerShare = pool.accLefPerShare.add(lefReward.mul(1e18).div(lpSupply));
        }

		result += user.amount.mul((accLefPerShare).sub(user.userRewardPerTokenPaid)).div(1e18);
	
        
		return result;
    }
	

	function pendingAllLef(address _user) public view returns (uint256) {
		uint256  result = 0;
		for(uint256 i = 0;i< poolInfo.length;i++ ){
			result = result.add(pendingLef(i,_user));
		}
        return result;
    }
	

	function allLefAmount(address _user) public view returns (uint256) {
		uint256 result = 0;
		for(uint256 i = 0;i< poolInfo.length;i++ ){
			UserInfo storage user = userInfo[i][_user];
			result = result.add(pendingLef(i,_user).add(user.rewardPaid));
		}
        return result;
    }
	

	function getAllDeposit(address _user) public view returns (uint256) {
		uint256 result = 0;
		for(uint256 i = 0;i< poolInfo.length;i++ ){
			UserInfo storage user = userInfo[i][_user];		
			result = result.add(user.amount);
		}
        return result;
    }


	function updateVipPool(address _user) internal {
		address _referrer = users[_user].referrer;
		for(uint i = 1;i < 3;i++){
			if(isUserExists(_referrer) && _referrer != address(0)){
				uint256 vip = getVipLevel(_referrer);
				uint256 _vip = users[_referrer].vip;
				uint256 skip_num ;
				if(vip > _vip){
					skip_num =  vip.sub(_vip);
				}else if(vip < _vip){
					skip_num =  _vip.sub(vip);
				}
				
				if(skip_num != 0){ 
					bool gloryBonus = false; 
					if(i == 2 && users[_user].vip >= 2 && vip >= 2){
						gloryBonus == true;
					}
					if(_vip != 0){
						VipPoolInfo storage _vpInfo =  vipPoolInfo[_vip];
						if(vipPoolInfo[_vip].vipNumber != 0){
							uint256 _multiplier = getMultiplier(_vpInfo.lastTime, block.timestamp);
							uint256 _lefReward;
							if(gloryBonus){
								_lefReward = _multiplier.mul(rewardRate).mul((_vpInfo.allocPoint).add(totalAllocPoint.mul(3).div(100))).div(totalAllocPoint);
							}else{
								_lefReward = _multiplier.mul(rewardRate).mul(_vpInfo.allocPoint).div(totalAllocPoint);
							}
							
							totalMinted = totalMinted.add(_lefReward);
							//lef.mint(address(this), _lefReward);
							_vpInfo.rewardPerTokenStored = _vpInfo.rewardPerTokenStored.add(_lefReward.div(_vpInfo.vipNumber));
							users[_referrer].referReward = ((_vpInfo.rewardPerTokenStored).sub(users[_referrer].referRewardPerTokenPaid)).add(users[_referrer].referReward);
							
							_vpInfo.vipNumber -= 1;	
							users[_referrer].referRewardPerTokenPaid = _vpInfo.rewardPerTokenStored;
							_vpInfo.lastTime = block.timestamp;							
						}			
					}
					if(vip != 0){
					
						VipPoolInfo storage vpInfo =  vipPoolInfo[vip];
						if(vpInfo.vipNumber != 0){
							
					
						
							uint256 multiplier = getMultiplier(vpInfo.lastTime, block.timestamp);
												
							uint256 lefReward;
							if(gloryBonus){
								lefReward = multiplier.mul(rewardRate).mul((vpInfo.allocPoint).add(totalAllocPoint.mul(3).div(100))).div(totalAllocPoint);
							}else{
								lefReward = multiplier.mul(rewardRate).mul(vpInfo.allocPoint).div(totalAllocPoint);
							}
						
						
							totalMinted = totalMinted.add(lefReward);
						//lef.mint(address(this), lefReward);
							vpInfo.rewardPerTokenStored = vpInfo.rewardPerTokenStored.add(lefReward.div(vpInfo.vipNumber));
						
						}
						
						//if(vpInfo.rewardPerTokenStored != 0){
						//	users[_referrer].referReward = ((vpInfo.rewardPerTokenStored).sub(users[_referrer].referRewardPerTokenPaid)).add(users[_referrer].referReward);
						//}
						vpInfo.vipNumber += 1;

						users[_referrer].referRewardPerTokenPaid = vpInfo.rewardPerTokenStored;
						vpInfo.lastTime = block.timestamp;	
					}	
									
				}	
				users[_referrer].vip= vip;	
				_referrer = users[_referrer].referrer;
			}

			
		}		
	}

	function setIndirectThreshold(uint256 _indirectThreshold) public onlyOwner{
	
		indirectRefer_threshold = _indirectThreshold;
	
	}
	
	function getVipLevel(address _user) public view returns(uint256){
		uint256 vip = 0;
		
		if(isUserExists(_user)){
			uint256 directReferAmount = users[_user].referAmount[0];
            uint256 indirectReferAmount = users[_user].referAmount[1];
			for(uint256 i = 1;i<=3;i++){
				if(directReferAmount < vipLevel[i]){
					break;
				} else{
					vip  = i;
				}	
			
			}
			if(vip == 3){
    			if(directReferAmount > vipLevel[3] && indirectReferAmount >=indirectRefer_threshold){
    				vip = 3;
    			}else if(directReferAmount > vipLevel[3] && indirectReferAmount <= indirectRefer_threshold){
    				vip = 2;
				}
			}
		}

		return vip;
	}

	function getReferAmount(address _user,uint256 _index) public view returns(uint256){
		if(isUserExists(_user)){
			return	users[_user].referAmount[_index];
		}
		return 0;
	}
	
    // Update reward variables of the given pool to be up-to-date.
    function updatePool(uint256 _pid,address _user) internal {
        PoolInfo storage pool = poolInfo[_pid];
        if (block.timestamp <= pool.lastRewardTime) {
            return;
        }
        uint256 lpSupply = pool.totalPool;
        if (lpSupply == 0) {
            pool.lastRewardTime = block.timestamp;
            return;
        }
		UserInfo storage user = userInfo[_pid][_user];
		
        uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
        uint256 lefReward = multiplier.mul(rewardRate).mul(pool.allocPoint).div(totalAllocPoint);
        totalMinted = totalMinted.add(lefReward);


		//lef.mint(address(this), lefReward);
        pool.accLefPerShare = pool.accLefPerShare.add(lefReward.mul(1e18).div(lpSupply));
		
		user.reward = user.amount.mul((pool.accLefPerShare).sub(user.userRewardPerTokenPaid)).div(1e18).add(user.reward);
		
		
		user.userRewardPerTokenPaid = pool.accLefPerShare;
        pool.lastRewardTime = block.timestamp;
    }


    // Deposit LP tokens to MasterChef for lef allocation.
    function deposit(uint256 _pid, uint256 _amount) public checkStart checkhalve{

		require(isUserExists(msg.sender), "user don't exists");		
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid,msg.sender);	
		
        if(_amount > 0) {
           pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
			user.updateTime = block.timestamp;
			user.pid = _pid;
			pool.totalPool = pool.totalPool.add(_amount);   		
	
			address _referrer = users[msg.sender].referrer;
			for(uint256 i = 0;i<2;i++){				
				if(_referrer!= address(0) && isUserExists(_referrer)){
					users[_referrer].referAmount[i] += _amount;					
					_referrer = users[_referrer].referrer;
				}
			}				
        }
		//
		updateVipPool(msg.sender);
        emit Deposit(msg.sender, _pid, _amount);
    }
	

    function getReward(uint256 _pid) public  {

		PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 accLefPerShare = pool.accLefPerShare;
        uint256 lpSupply = pool.totalPool;
        if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
            uint256 multiplier =  getMultiplier(pool.lastRewardTime, block.timestamp);
            uint256 lefReward = multiplier.mul(rewardRate).mul(pool.allocPoint).div(totalAllocPoint);
            accLefPerShare = pool.accLefPerShare.add(lefReward.mul(1e18).div(lpSupply));
        }
        uint256 reward = user.amount.mul((accLefPerShare).sub(user.userRewardPerTokenPaid)).div(1e18).add(user.reward);
	
        if (reward > 0) {
			safeLefTransfer(msg.sender, reward);
			user.rewardPaid = user.rewardPaid.add(reward);
			user.reward = 0;
            emit RewardPaid(msg.sender, reward);
        }		
		user.userRewardPerTokenPaid = accLefPerShare;
    }
	


    // Withdraw LP tokens from MasterChef.
    function withdraw(uint256 _pid, uint256 _amount) public checkhalve{
		
		
		UserInfo storage user = userInfo[_pid][msg.sender];
		
		require(block.timestamp > DURATIONS[_pid].add(user.updateTime),"");	
				
        PoolInfo storage pool = poolInfo[_pid];
        
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid,msg.sender);
               

		safeLefTransfer(msg.sender, user.reward);
		user.reward = 0;
		user.rewardPaid = user.rewardPaid.add(user.reward);
		emit RewardPaid(msg.sender, user.rewardPaid);
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);

            pool.lpToken.safeTransfer(address(msg.sender), _amount);
						
			pool.totalPool -= _amount;   
			
			address _referrer = users[msg.sender].referrer;
			for(uint256 i = 0;i<2;i++){
				if(_referrer!= address(0) && isUserExists(_referrer)){
					users[_referrer].referAmount[i] -= _amount;					
					_referrer = users[_referrer].referrer;
				}
			}	
        }
		updateVipPool(msg.sender);
        emit Withdraw(msg.sender, _pid, _amount);
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
   // function emergencyWithdraw(uint256 _pid) public {
   //     PoolInfo storage pool = poolInfo[_pid];
    //    UserInfo storage user = userInfo[_pid][msg.sender];
   //     pool.lpToken.safeTransfer(address(msg.sender), user.amount);
   //     emit EmergencyWithdraw(msg.sender, _pid, user.amount);
  //      user.amount = 0;
   // }

    // Safe lef transfer function, just in case if rounding error causes pool to not have enough lefs.
    function safeLefTransfer(address _to, uint256 _amount) internal {
        uint256 lefBal = lef.balanceOf(address(this));
        if (_amount > lefBal) {
            lef.transfer(_to, lefBal);
        } else {
            lef.transfer(_to, _amount);
        }
    }   
	modifier checkhalve(){
        if (totalMinted >= 500000 *1e18) {
			
	//		initreward = initreward.mul(50).div(100);
           rewardRate = rewardRate.mul(90).div(100);
		   totalMinted = 0;
    //        periodFinish = periodFinish.add(DURATION);
           
        }
       _;
   }
	
	modifier checkStart(){
       require(block.timestamp  > starttime,"not start");
       _;
    }

    // Update dev address by the previous dev.

}
// MasterChef is the master of Lef. He can make Lef and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once Lef is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
function withdraw(uint256 _pid, uint256 _amount) public checkhalve{
		
		
erInfo storage user = userInfo[_pid][msg.sender];
		
quire(block.timestamp > DURATIONS[_pid].add(user.updateTime),"");	
				
    PoolInfo storage pool = poolInfo[_pid];
        
    require(user.amount >= _amount, "withdraw: not good");
    updatePool(_pid,msg.sender);
               

feLefTransfer(msg.sender, user.reward);
er.reward = 0;
er.rewardPaid = user.rewardPaid.add(user.reward);
it RewardPaid(msg.sender, user.rewardPaid);
    if(_amount > 0) {
        user.amount = user.amount.sub(_amount);

        pool.lpToken.safeTransfer(address(msg.sender), _amount);
						
ool.totalPool -= _amount;   
			
ddress _referrer = users[msg.sender].referrer;
or(uint256 i = 0;i<2;i++){
if(_referrer!= address(0) && isUserExists(_referrer)){
	users[_referrer].referAmount[i] -= _amount;					
	_referrer = users[_referrer].referrer;
}
	
    }
dateVipPool(msg.sender);
    emit Withdraw(msg.sender, _pid, _amount);
}

// Withdraw LP tokens from MasterChef.