contract MOOchef is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;
    struct UserInfo {
        uint256 amount;     // How many LP tokens the user has provided.
        uint256 rewardDebt; // Reward debt. Same as sushiswap
        uint256 lastDepositTime; // Last LP deposit time 
        uint256 timelock; // Does the user has LP timelock 0: no, certain number: timelock period
    }

    struct PoolInfo {
        IERC20 lpToken;           // Address of LP token contract.
        uint256 allocPoint;       // How many allocation points assigned to this pool.
        uint256 lastRewardBlock;  // Last block number that Burn distribution occurs.
        uint256 accMooPerShare; // Accumulated token per share, times 1e12. See below.
        uint256 isFreezone; // LP without Burn =  1, LP with Burn = 0
    }

    // MOOswapToken
    MOOswapToken public moo;
    // Dev, burn, and Buyback address.
    address public devaddr;
    address public burnaddr;
    address public buybackaddr;
    // Block number when bonus period ends.
    uint256 public bonusEndBlock;
    // Tokens created per block.
    uint256 public mooPerBlock;
    uint256 public BONUS_MULTIPLIER = 2;
    // Defining diminish and vault fee.
    uint256 public diminish = 10 days;
    uint256 public vaultfee = 200;
    uint256 public locktime = 2 days;

    // 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 mining starts.
    uint256 public startBlock;

    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event DepositWithLPlock(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(
        MOOswapToken _moo,
        address _devaddr,
        address _buybackaddr,
        address _burnaddr,
        uint256 _startBlock,
        uint256 _bonusEndBlock
    ) public {
        moo = _moo;
        devaddr = _devaddr;
        buybackaddr = _buybackaddr;
        burnaddr = _burnaddr;
        mooPerBlock = 100000000000000000; // 0.1 /Block
        bonusEndBlock = _bonusEndBlock;
        startBlock = _startBlock;
    }

    function changeReward(uint256 _mooPerBlock) public onlyOwner {
        mooPerBlock = _mooPerBlock;
    }

    function changeStartBlock(uint256 _startBlock) public onlyOwner {
        startBlock = _startBlock;
    }
    function changeBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
        bonusEndBlock = _bonusEndBlock;
    }
    function changeBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
        BONUS_MULTIPLIER = _bonusMultiplier;
    }
    function changeDiminishRate(uint256 _diminish) public onlyOwner {
        diminish = _diminish;
    }
    function changeVaultfee(uint256 _vaultfee) public onlyOwner {
        vaultfee = _vaultfee;
    }
    
    // Affective to the timelock after this change occurs
    function changeLocktime(uint256 _locktime) public onlyOwner {
        locktime = _locktime;
    }

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

    function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _isFreezone, 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,
            accMooPerShare: 0,
            isFreezone: _isFreezone
        }));
    }

    function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
        poolInfo[_pid].allocPoint = _allocPoint;
        poolInfo[_pid].lpToken = _lpToken;
    }

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

    // View function to see pending Burn on frontend.
    function pendingMOO(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accMooPerShare = pool.accMooPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 mooReward = multiplier.mul(mooPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accMooPerShare = accMooPerShare.add(mooReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accMooPerShare).div(1e12).sub(user.rewardDebt);
    }
    
    // View function to see estimated harvest after burnt MOO on frontend.
    function estimatedMOO(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 depositduration = 0;
        uint256 subrate = 1;
        uint256 pending = 0;
        if(now < (user.lastDepositTime + diminish) ){
                 subrate = depositduration.div(diminish);
        }
        uint256 accMooPerShare = pool.accMooPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 mooReward = multiplier.mul(mooPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accMooPerShare = accMooPerShare.add(mooReward.mul(1e12).div(lpSupply));
        }
        pending = user.amount.mul(accMooPerShare).div(1e12).sub(user.rewardDebt);
        return pending.mul(subrate);
    }
    
    // Update reward variables 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 mooReward = multiplier.mul(mooPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        moo.distribute(devaddr, mooReward.div(20));
        moo.distribute(address(this), mooReward);
        pool.accMooPerShare = pool.accMooPerShare.add(mooReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 vaultamount = 0;
        uint256 depositduration = 0;
        uint256 subrate = 1;
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
            uint256 moopending = 0;
            depositduration = now.sub(user.lastDepositTime);
            if(now < (user.lastDepositTime + diminish) ){
                 subrate = depositduration.div(diminish);
             }
        
            if(pending > 0) {
                moopending = pending.sub(pending.mul(subrate));
                safeMooTransfer(msg.sender, pending.mul(subrate));
                safeMooTransfer(burnaddr, moopending);
            }
        }
        if(_amount > 0) {
            if(pool.isFreezone > 0) {
                vaultamount = _amount.div(vaultfee);
                pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount));
                pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount);
            }
            if(pool.isFreezone < 1) {
                pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            }
            user.amount = user.amount.add(_amount.sub(vaultamount));
            user.lastDepositTime = now;
            user.timelock = 0;
        }
        user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }
    
    /** Locks lpToken for certain period. Locked LP depotied through this method only can be withdrawed after timelock period
     * 
     */
    function depositWithLPlock(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 vaultamount = 0;
        uint256 depositduration = 0;
        uint256 subrate = 1;
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
            uint256 moopending = 0;
            depositduration = now.sub(user.lastDepositTime);
            if(now < (user.lastDepositTime + diminish) ){
                 subrate = depositduration.div(diminish);
             }
        
            if(pending > 0) {
                moopending = pending.sub(pending.mul(subrate));
                safeMooTransfer(msg.sender, pending.mul(subrate));
                safeMooTransfer(burnaddr, moopending);
            }
        }
        if(_amount > 0) {
            if(pool.isFreezone > 0) {
                vaultamount = _amount.div(vaultfee);
                pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount));
                pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount);
            }
            if(pool.isFreezone < 1) {
                pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            }
            user.amount = user.amount.add(_amount.sub(vaultamount));
            user.lastDepositTime = now;
            user.timelock = locktime;
        }
        user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
        emit DepositWithLPlock(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens.
    // Only non-locked LP and Locked LP after lock period can be withdrawed
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        require(now > user.lastDepositTime + user.timelock, "Your LP is LOCKed for the moment");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
        uint256 depositduration = 0;
        uint256 subrate = 1;
        depositduration = now.sub(user.lastDepositTime);
        if(now < (user.lastDepositTime + diminish) ){
            subrate = depositduration.div(diminish);
        }
        
        if(pending > 0) {
            safeMooTransfer(msg.sender, pending.mul(subrate));
            safeMooTransfer(burnaddr, pending.sub(pending.mul(subrate)));
        }
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        user.lastDepositTime = now.sub(depositduration.div(2));
        user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
        emit Withdraw(msg.sender, _pid, _amount);
    }
    
    // Update buyback address.
    function bbto(address _buybackaddr) public {
        require(msg.sender == buybackaddr, "ERROR");
        buybackaddr = _buybackaddr;
    }

    // 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 MOO transfer function, just in case if rounding error causes pool to not have enough MOO.
    function safeMooTransfer(address _to, uint256 _amount) internal {
        uint256 mooBal = moo.balanceOf(address(this));
        if (_amount > mooBal) {
            moo.transfer(_to, mooBal);
        } else {
            moo.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "ERROR");
        devaddr = _devaddr;
    }

    // Update burn-event address.
    function burnto(address _burnaddr) public {
        require(msg.sender == devaddr, "ERROR");
        burnaddr = _burnaddr;
    }
}
function depositWithLPlock(uint256 _pid, uint256 _amount) public {
    PoolInfo storage pool = poolInfo[_pid];
    UserInfo storage user = userInfo[_pid][msg.sender];
    uint256 vaultamount = 0;
    uint256 depositduration = 0;
    uint256 subrate = 1;
    updatePool(_pid);
    if (user.amount > 0) {
        uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
        uint256 moopending = 0;
        depositduration = now.sub(user.lastDepositTime);
        if(now < (user.lastDepositTime + diminish) ){
             subrate = depositduration.div(diminish);
         }
        
        if(pending > 0) {
            moopending = pending.sub(pending.mul(subrate));
            safeMooTransfer(msg.sender, pending.mul(subrate));
            safeMooTransfer(burnaddr, moopending);
        }
    }
    if(_amount > 0) {
        if(pool.isFreezone > 0) {
            vaultamount = _amount.div(vaultfee);
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount));
            pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount);
        }
        if(pool.isFreezone < 1) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        }
        user.amount = user.amount.add(_amount.sub(vaultamount));
        user.lastDepositTime = now;
        user.timelock = locktime;
    }
    user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
    emit DepositWithLPlock(msg.sender, _pid, _amount);
}

/** Locks lpToken for certain period. Locked LP depotied through this method only can be withdrawed after timelock period
 * 
 */