// Contract: MasterChef
// Target function: function updatePool(uint256 _pid,address _user) internal
 // 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 * 10e18;



	

	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;
        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));
        }
        return user.amount.mul((accLefPerShare).sub(user.userRewardPerTokenPaid)).div(1e18).add(user.reward);
    }
	

	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 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]){
					return vip;
				} else {
					vip = i;
				}				
			}
		}
		return vip;
	}

	function getReferAmount(address _user,uint256 _index) public view returns(uint256){
		if(isUserExists(_user)){
			return	users[_user].referAmount[_index];
		}
		return 0;
	}