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

    // Info of each user.
    struct UserInfo {
        uint256 amount;     // How many LP tokens the user has provided.
        uint256 rewardDebt; // Reward debt. See explanation below.
        uint256 lastLockRewardBlock;
        uint256 haveReceivedReward;
        uint256 totalLockReward;
        //
        // We do some fancy math here. Basically, any point in time, the amount of MGs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accMGPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accMGPerShare` (and `lastRewardBlock`) gets updated.
        //   2. User receives the pending reward sent to his/her address.
        //   3. User's `amount` gets updated.
        //   4. User's `rewardDebt` gets updated.
    }

    // Info of each pool.
    struct PoolInfo {
        IERC20 lpToken;           // Address of LP token contract.
        uint256 allocPoint;       // How many allocation points assigned to this pool. MGs to distribute per block.
        uint256 lastRewardBlock;  // Last block number that MGs distribution occurs.
        uint256 accMGPerShare; // Accumulated MGs per share, times 1e12. See below.
    }

    // The MG TOKEN!
    MGToken public mg;

    // Block number when bonus MG period ends.
    uint256 public bonusEndBlock;
    // MG tokens created per block.
    uint256 public mgPerBlock;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigratorChef public migrator;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of each user that stakes LP tokens.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
    // Total allocation poitns. Must be the sum of all allocation points in all pools.
    uint256 public totalAllocPoint = 0;
    // The block number when MG mining starts.
    uint256 public startBlock;
    uint256 public weekBlock = 40320;
    uint256 public oneYearBlock = 2102400;
    uint256 public weeksBlock16 = 645120;
    uint256 public molecular = 7500;
    uint256 public rate = 9000;
    uint256 public denominator = 10000;

    uint256 public oneTwoBlock; // 1,2 end
    uint256 public threeBlock;  // 3 end
    uint256 public fourBlock;   // 4 end 
    uint256 public fiveBlock;   // 5 end
    uint256 public sixBlock;    // 6 end
    uint256 public sevenBlock;  // 7 end

    IPlayerBook public playerBook;
    
    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);

    constructor(
        MGToken _mg,
        uint256 _mgPerBlock,
        uint256 _startBlock,
        uint256 _bonusEndBlock,
        address _playerBook
    ) public {
        require(_bonusEndBlock >= _startBlock.add(weekBlock.mul(9)), "_bonusEndBlock err");
        mg = _mg;
        mgPerBlock = _mgPerBlock;
        bonusEndBlock = _bonusEndBlock;
        startBlock = _startBlock;
        playerBook = IPlayerBook(_playerBook);

        oneTwoBlock = startBlock + 2*weekBlock;
        threeBlock = startBlock + 3*weekBlock; 
        fourBlock = startBlock + 4*weekBlock;  
        fiveBlock = startBlock + 5*weekBlock;  
        sixBlock = startBlock + 6*weekBlock;   
        sevenBlock = startBlock + 7*weekBlock; 
    }

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

    // 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 add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accMGPerShare: 0
        }));
    }

    // Update the given pool's MG allocation point. Can only be called by the owner.
    function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
        poolInfo[_pid].allocPoint = _allocPoint;
    }

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigratorChef _migrator) public onlyOwner {
        migrator = _migrator;
    }

    // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
    function migrate(uint256 _pid) public {
        require(address(migrator) != address(0), "migrate: no migrator");
        PoolInfo storage pool = poolInfo[_pid];
        IERC20 lpToken = pool.lpToken;
        uint256 bal = lpToken.balanceOf(address(this));
        lpToken.safeApprove(address(migrator), bal);
        IERC20 newLpToken = migrator.migrate(lpToken);
        require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
        pool.lpToken = newLpToken;
    }

    // View function to see pending MGs on frontend.
    function pendingMG(uint256 _pid, address _user) public view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accMGPerShare = pool.accMGPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 mgReward = multiplier.mul(mgPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accMGPerShare = accMGPerShare.add(mgReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accMGPerShare).div(1e12).sub(user.rewardDebt);
    }

    // Update reward vairables for all pools. Be careful of gas spending!
    function massUpdatePools() public {
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            updatePool(pid);
        }
    }

    // Update reward variables of the given pool to be up-to-date.
    function updatePool(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        if (block.number <= pool.lastRewardBlock) {
            return;
        }
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 mgReward = multiplier.mul(mgPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        mg.mint(address(this), mgReward);
        pool.accMGPerShare = pool.accMGPerShare.add(mgReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterChef for MG allocation.
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];

        if (user.amount > 0) {
            _withdraw(_pid, 0);
        } else {
            updatePool(_pid);
        }
        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accMGPerShare).div(1e12);
        if(user.lastLockRewardBlock == 0  && block.number <= sevenBlock) {
            user.lastLockRewardBlock = block.number;
        }

        emit Deposit(msg.sender, _pid, _amount);
    }


    // Withdraw LP tokens from MasterChef.
    function withdraw(uint256 _pid, uint256 _amount) public {
        _withdraw(_pid, _amount);
        userInfo[_pid][msg.sender].amount = userInfo[_pid][msg.sender].amount.sub(_amount);
        userInfo[_pid][msg.sender].rewardDebt = userInfo[_pid][msg.sender].amount.mul(poolInfo[_pid].accMGPerShare).div(1e12);
        poolInfo[_pid].lpToken.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }


    function _withdraw(uint256 _pid, uint256 _amount) internal {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accMGPerShare).div(1e12).sub(user.rewardDebt);
        ///add
        address laffAddress = playerBook.getPlayerLaffAddress(msg.sender); // laff address
        address devAddress = playerBook._teamWallet(); //dev address
        uint256 laffRewardRate = playerBook._referLaffRewardRate(); //laff rate
        uint256 devRewardRate = playerBook._referDevRewardRate();
        uint256 baseRate = playerBook._baseRate();
        uint256 toLaff = pending.mul(laffRewardRate).div(baseRate);
        uint256 toDev = pending.mul(devRewardRate).div(baseRate);

        // 0 ~ 7 weeks
        if(block.number >= startBlock && block.number <= sevenBlock) {
            uint256 remain = pending.sub(toLaff).sub(toDev);
            uint256 lockAmount = remain.mul(molecular).div(denominator);

            safeMGTransfer(msg.sender, remain.sub(lockAmount));
            if(devAddress == laffAddress){
                safeMGTransfer(devAddress, toLaff.add(toDev));
            } else {
                safeMGTransfer(devAddress, toDev);
                safeMGTransfer(laffAddress, toLaff);
            }
            user.totalLockReward = user.totalLockReward.add(lockAmount);
            user.lastLockRewardBlock = block.number;
        } else if (block.number > sevenBlock && user.lastLockRewardBlock <= sevenBlock)  {
            uint256 comBlock = block.number.sub(user.lastLockRewardBlock);
            uint256 needBlock = sevenBlock.sub(user.lastLockRewardBlock);
            uint256 remain = pending.sub(toLaff).sub(toDev);
            uint256 lockAmount = remain.mul(molecular).mul(needBlock).div(comBlock).div(denominator);

            safeMGTransfer(msg.sender, remain.sub(lockAmount));
            if(devAddress == laffAddress){
                safeMGTransfer(devAddress, toLaff.add(toDev));
            } else {
                safeMGTransfer(devAddress, toDev);
                safeMGTransfer(laffAddress, toLaff);
            }
            user.totalLockReward = user.totalLockReward.add(lockAmount);
            user.lastLockRewardBlock = block.number;
        } else {
            /// send mg
            if(devAddress == laffAddress){
                safeMGTransfer(msg.sender, pending.sub(toLaff).sub(toDev));
                safeMGTransfer(devAddress, toLaff.add(toDev));
            } else {
                safeMGTransfer(msg.sender, pending.sub(toLaff).sub(toDev));
                safeMGTransfer(devAddress, toDev);
                safeMGTransfer(laffAddress, toLaff);
            }
        } 
    }

    function receiveLockedRewards(uint256 _pid) public {
        require(block.number >= startBlock.add(weeksBlock16), "not receive time");

        // after one year + 16 weeks
        if(block.number >= startBlock.add(oneYearBlock).add(weeksBlock16)) {
            safeMGTransfer(msg.sender, (userInfo[_pid][msg.sender].totalLockReward).sub(userInfo[_pid][msg.sender].haveReceivedReward));
            userInfo[_pid][msg.sender].haveReceivedReward = userInfo[_pid][msg.sender].totalLockReward;
            userInfo[_pid][msg.sender].lastLockRewardBlock = block.number;
        } else {
            if(userInfo[_pid][msg.sender].lastLockRewardBlock < startBlock.add(weeksBlock16)) {
                uint256 reward = userInfo[_pid][msg.sender].totalLockReward.mul(block.number.sub(startBlock.add(weeksBlock16))).div(oneYearBlock);
                safeMGTransfer(msg.sender, reward);
                userInfo[_pid][msg.sender].haveReceivedReward = userInfo[_pid][msg.sender].haveReceivedReward.add(reward);
                userInfo[_pid][msg.sender].lastLockRewardBlock = block.number;
            } else {
                uint256 reward = userInfo[_pid][msg.sender].totalLockReward.mul(block.number.sub(userInfo[_pid][msg.sender].lastLockRewardBlock)).div(oneYearBlock);
                safeMGTransfer(msg.sender, reward);
                userInfo[_pid][msg.sender].haveReceivedReward = userInfo[_pid][msg.sender].haveReceivedReward.add(reward);
                userInfo[_pid][msg.sender].lastLockRewardBlock = block.number;
            }
        }
    }

    // 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;
        user.rewardDebt = 0;
    }

    // Safe mg transfer function, just in case if rounding error causes pool to not have enough MGs.
    function safeMGTransfer(address _to, uint256 _amount) internal {
            uint256 mgBal = mg.balanceOf(address(this));
        if (_amount > mgBal) {
            mg.transfer(_to, mgBal);
        } else {
            mg.transfer(_to, _amount);
        }
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        uint8 fromPeriod = getTimeInPeriod(_from);
        uint8 toPeriod = getTimeInPeriod(_to);

        uint256 _oneTwo;
        uint256 _three;
        uint256 _four;
        uint256 _five;
        uint256 _six;
        uint256 _seven;
        uint256 _eight;

        // 1,2 period, 1,2 period
        if(fromPeriod == 1 && toPeriod == 1) {
            return _to.sub(_from).mul(64);

        // 3 period, 3 period 
        } else if(fromPeriod == 2 && toPeriod == 2) {
            return _to.sub(_from).mul(32);

        // 4 period, 4 period 
        } else if(fromPeriod == 3 && toPeriod == 3) {
            return _to.sub(_from).mul(16);

        // 5 period, 5 period             
        } else if(fromPeriod == 4 && toPeriod == 4) {
            return _to.sub(_from).mul(8);

        // 6 period, 6 period            
        } else if(fromPeriod == 5 && toPeriod == 5) {
            return _to.sub(_from).mul(4);

        // 7 period, 7 period 
        } else if(fromPeriod == 6 && toPeriod == 6) {
            return _to.sub(_from).mul(2);

        // 8 period, 8 period             
        } else if(fromPeriod == 7 && toPeriod == 7) {
            return _to.sub(_from);

        // 8 period, out end period 
        } else if(fromPeriod == 7 && toPeriod == 8) {
            return bonusEndBlock.sub(_from);
            
        // 1,2 period, 3 period            
        } else if(fromPeriod == 1 && toPeriod == 2) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three = _to.sub(oneTwoBlock).mul(32);
            return _oneTwo.add(_three);

        // 1,2 period, 4 period  
        } else if(fromPeriod == 1 && toPeriod == 3) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three =  weekBlock.mul(32);
            _four = _to.sub(threeBlock).mul(16);
            return _oneTwo.add(_three).add(_four);

        // 1,2 period, 5 period  
        } else if(fromPeriod == 1 && toPeriod == 4) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three =  weekBlock.mul(32);
            _four = weekBlock.mul(16);
            _five = _to.sub(fourBlock).mul(8);
            return _oneTwo.add(_three).add(_four).add(_five);

        // 1,2 period, 6 period
        } else if(fromPeriod == 1 && toPeriod == 5) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three =  weekBlock.mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = _to.sub(fiveBlock).mul(4);
            return _oneTwo.add(_three).add(_four).add(_five).add(_six);

         // 1,2 period, 7 period           
        } else if(fromPeriod == 1 && toPeriod == 6) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three =  weekBlock.mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = _to.sub(sixBlock).mul(2);
            uint256 a = _oneTwo.add(_three).add(_four).add(_five);
            return a.add(_six).add(_seven);

        // 1,2 period, 8 ~ end period   
        }  else if(fromPeriod == 1 && toPeriod == 7) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three =  weekBlock.mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = _to.sub(sevenBlock);
            uint256 a = _oneTwo.add(_three).add(_four).add(_five).add(_six);
            return a.add(_seven).add(_eight);

        //1,2 period, out end period   
        } else if(fromPeriod == 1 && toPeriod == 8) {
            _oneTwo = oneTwoBlock.sub(_from).mul(64);
            _three =  weekBlock.mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = bonusEndBlock.sub(sevenBlock);
            uint256 a = _oneTwo.add(_three).add(_four).add(_five).add(_six);
            return a.add(_seven).add(_eight);

        // 3 period, 4 period           
        } else if(fromPeriod == 2 && toPeriod == 3) {
            _three = threeBlock.sub(_from).mul(32);
            _four = _to.sub(threeBlock).mul(16); 
            return _three.add(_four);

        // 3 period, 5 period             
        } else if(fromPeriod == 2 && toPeriod == 4) {
            _three = threeBlock.sub(_from).mul(32);
            _four = weekBlock.mul(16);
            _five = _to.sub(fourBlock).mul(8);
            return _three.add(_four).add(_five);

        // 3 period, 6 period    
        } else if(fromPeriod == 2 && toPeriod == 5) {
            _three = threeBlock.sub(_from).mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = _to.sub(fiveBlock).mul(4);
            return _three.add(_four).add(_five).add(_six);

        // 3 period, 7 period  
        } else if(fromPeriod == 2 && toPeriod == 6) {
            _three = threeBlock.sub(_from).mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = _to.sub(sixBlock).mul(2);
            return _three.add(_four).add(_five).add(_six).add(_seven);

        // 3 period, 8 ~ end period                
        } else if(fromPeriod == 2 && toPeriod == 7) {
            _three = threeBlock.sub(_from).mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = _to.sub(sevenBlock);
            return _three.add(_four).add(_five).add(_six).add(_seven).add(_eight);

        // 3 period,, out end period  
        } else if(fromPeriod == 2 && toPeriod == 8) {
            _three = threeBlock.sub(_from).mul(32);
            _four = weekBlock.mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = bonusEndBlock.sub(sevenBlock);
            return _three.add(_four).add(_five).add(_six).add(_seven).add(_eight);

         // 4 period, 5 period            
        } else if(fromPeriod == 3 && toPeriod == 4) {
            _four = fourBlock.sub(_from).mul(16);
            _five = _to.sub(fourBlock).mul(8);
            return _four.add(_five);

         // 4 period, 6 period              
        } else if(fromPeriod == 3 && toPeriod == 5) {
            _four = fourBlock.sub(_from).mul(16);
            _five = weekBlock.mul(8);
            _six = _to.sub(fiveBlock).mul(4);
            return _four.add(_five).add(_six);

         // 4 period, 7 period                
        } else if(fromPeriod == 3 && toPeriod == 6) {
            _four = fourBlock.sub(_from).mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = _to.sub(sixBlock).mul(2);
            return _four.add(_five).add(_six).add(_seven);

         // 4 period, 8 period              
        } else if(fromPeriod == 3 && toPeriod == 7) {
            _four = fourBlock.sub(_from).mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = _to.sub(sevenBlock);
            return _four.add(_five).add(_six).add(_seven).add(_eight);

         // 4 period, out end period           
        } else if(fromPeriod == 3 && toPeriod == 8) {
            _four = fourBlock.sub(_from).mul(16);
            _five = weekBlock.mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = bonusEndBlock.sub(sevenBlock);
            return _four.add(_five).add(_six).add(_seven).add(_eight);

        // 5 period, 6 period                 
        } else if(fromPeriod == 4 && toPeriod == 5) {
            _five = fiveBlock.sub(_from).mul(8);
            _six = _to.sub(fiveBlock).mul(4);
            return _five.add(_six);

        // 5 period, 7 period               
        } else if(fromPeriod == 4 && toPeriod == 6) {
            _five = fiveBlock.sub(_from).mul(8);
            _six = weekBlock.mul(4);
            _seven = _to.sub(sixBlock).mul(2);
            return _five.add(_six).add(_seven);

        // 5 period, 8 ~ end period                  
        } else if(fromPeriod == 4 && toPeriod == 7) {
            _five = fiveBlock.sub(_from).mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = _to.sub(sevenBlock);
            return _five.add(_six).add(_seven).add(_eight);

        //5 period, out end period       
        }  else if(fromPeriod == 4 && toPeriod == 8) {
            _five = fiveBlock.sub(_from).mul(8);
            _six = weekBlock.mul(4);
            _seven = weekBlock.mul(2);
            _eight = bonusEndBlock.sub(sevenBlock);
            return _five.add(_six).add(_seven).add(_eight);

        // 6 period, 7 period  
        } else if(fromPeriod == 5 && toPeriod == 6) {
            _six = sixBlock.sub(_from).mul(4);
            _seven = _to.sub(sixBlock).mul(2);
            return _six.add(_seven);

        // 6 period, 8 ~ end period               
        } else if(fromPeriod == 5 && toPeriod == 7) {
            _six = sixBlock.sub(_from).mul(4);
            _seven = weekBlock.mul(2);
            _eight = _to.sub(sevenBlock);
            return _six.add(_seven).add(_eight);

        //6 period, out end period  
        } else if(fromPeriod == 5 && toPeriod == 8) {
            _six = sixBlock.sub(_from).mul(4);
            _seven = weekBlock.mul(2);
            _eight = bonusEndBlock.sub(sevenBlock);
            return _six.add(_seven).add(_eight);

        // 7 period, 8 ~ end period                 
        } else if(fromPeriod == 6 && toPeriod == 7) {
            _seven = sevenBlock.sub(_from).mul(2);
            _eight = _to.sub(sevenBlock);
            return _seven.add(_eight);

        // 7 period, out end period   
        } else if(fromPeriod == 6 && toPeriod == 8) {
            _seven = sevenBlock.sub(_from).mul(2);
            _eight = bonusEndBlock.sub(sevenBlock);
            return _seven.add(_eight);

        } else {
            return 0;
        }

    }

    // Get period through block
    function getTimeInPeriod(uint256 _time) public view returns(uint8 _period) {
        // 1,2 period
        if(startBlock <= _time && _time < startBlock.add(weekBlock.mul(2))) {
            _period = 1; 
        // 3
        } else if(_time >= startBlock.add(weekBlock.mul(2)) &&  _time < startBlock.add(weekBlock.mul(3))) {
            _period = 2; 
        // 4
        } else if(_time >= startBlock.add(weekBlock.mul(3)) &&  _time < startBlock.add(weekBlock.mul(4))) {
            _period = 3;  
        // 5
        } else if(_time >= startBlock.add(weekBlock.mul(4)) &&  _time < startBlock.add(weekBlock.mul(5))) {
            _period = 4;  
        // 6 
        } else if(_time >= startBlock.add(weekBlock.mul(5)) &&  _time < startBlock.add(weekBlock.mul(6))) {
            _period = 5; 
        // 7 
        } else if(_time >= startBlock.add(weekBlock.mul(6)) &&  _time < startBlock.add(weekBlock.mul(7))) {
            _period = 6; 
        // 8 ~ end
        } else if(_time >= startBlock.add(weekBlock.mul(7)) &&  _time < bonusEndBlock) {
            _period = 7; 
        // > out end
        } else if(_time >= bonusEndBlock) {
            _period = 8; 
        } else {
            _period = 0; 
        }
    }

    function getCurrentPerBlock() public view returns(uint256) {
        uint8 period = getTimeInPeriod(block.number);
        if(period == 1) {
            return mgPerBlock.mul(64);
        }
        if(period == 2) {
            return mgPerBlock.mul(32);
        }
        if(period == 3) {
            return mgPerBlock.mul(16);
        }
        if(period == 4) {
            return mgPerBlock.mul(8);
        }
        if(period == 5) {
            return mgPerBlock.mul(4);
        }
        if(period == 6) {
            return mgPerBlock.mul(2);
        }
        if(period == 7) {
            return mgPerBlock;
        }

        return 0;
    }

    function getLockAmount(uint256 _pid, address _user) public view returns(uint256) {
        uint256 earn = pendingMG(_pid, _user);
        UserInfo storage user = userInfo[_pid][_user];
    
        // 0 ~ 7 weeks
        if(block.number >= startBlock && block.number <= sevenBlock) {
            uint256 lockAmount = earn.mul(rate).mul(molecular).div(denominator).div(denominator); 
            return lockAmount.add(user.totalLockReward);
        }

        if(block.number > sevenBlock && user.lastLockRewardBlock <= sevenBlock) {
            uint256 comBlock = block.number.sub(user.lastLockRewardBlock);
            uint256 needBlock = sevenBlock.sub(user.lastLockRewardBlock);
            uint256 amount = earn.mul(needBlock).div(comBlock);
            uint256 lockAmount = amount.mul(rate).mul(molecular).div(denominator).div(denominator);
            return lockAmount.add(user.totalLockReward);
        }

        return user.totalLockReward.sub(user.haveReceivedReward);
    }
    
    function getCurrBlockNumber() public view returns(uint256) {
        return block.number;
    }
}
// MasterChef is the master of MG. He can make MG 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 MG is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
    if (_withUpdate) {
        massUpdatePools();
    }
    uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
    totalAllocPoint = totalAllocPoint.add(_allocPoint);
    poolInfo.push(PoolInfo({
        lpToken: _lpToken,
        allocPoint: _allocPoint,
        lastRewardBlock: lastRewardBlock,
        accMGPerShare: 0
    }));
}

// 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.