contract BonzaiFarm 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.
        //
        // We do some fancy math here. Basically, any point in time, the amount of 
        // claimable BONZAI by a user is:
        //
        //   pending reward = (user.amount * pool.accBonzaiPerLPShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accBonzaiPerLPShare` (and `lastRewardedBlock`) 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 lpTokenContract;     // Address of LP token contract.
        string name;                // Name of the pool/pair.
        uint256 allocPoints;        // Allocation points from the pool.
        uint256 lastRewardedBlock;  // Last block number where CHARGW distribution occured.
        uint256 accBonzaiPerLPShare; // Accumulated Bonzai per share.
        uint256 lpTokenHolding;     // Amount of LP token hold by this pool
    }

    // Info of Bonzai minting
    struct MintInfo {
        uint256 BonzaiPerBlock;  // Amount of minted Bonzai each block.
        uint256 mintStartBlock; // Minting of this amount starts here.
    }

    // The Bonzai token contract
    Token public Bonzai;
    
    // Dev address
    address public devaddr;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of Bonzai minting block span.
    MintInfo[] public mintInfo;
    
    // Info of each user that stakes LP tokens.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
    // Total allocation points. Must be the sum of all allocation points in all pools.
    uint256 public totalAllocPoints = 0;

    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(
        Token _Bonzai,
        address _devaddr,
        uint256 _BonzaiPerBlock,
        uint256 _mintStartBlock
    ) public {
        Bonzai = _Bonzai;
        devaddr = _devaddr;
        mintInfo.push(MintInfo({
            BonzaiPerBlock: _BonzaiPerBlock,
            mintStartBlock: _mintStartBlock
        }));
    }
    
    // Get current mint per block
    function currentMint() external view returns (uint256){
        for(uint256 i = 0; i < mintInfo.length-1; i++){
            if(mintInfo[i].mintStartBlock <= block.number && mintInfo[i+1].mintStartBlock > block.number){
                return i;
            }
        }
        if(block.number < mintInfo[0].mintStartBlock) {
            return 99999;
        }
        return mintInfo.length-1;
    }

    // Amount of block spans for minting different amounts of Bonzai
    function mintLength() external view returns (uint256) {
        return mintInfo.length;
    }
    
    // Return if farming already started or not 
    function farmingActive() external view returns (bool){
        return block.number >= mintInfo[0].mintStartBlock;
    }
    
    // Add a new block and mint amount to the mintInfo list. Can only be called by the owner.
    // Only possible to change for blocks not already mined.
    function addMint(uint256 _block, uint256 _amount) public onlyOwner {
        require(_block > block.number + 10, "_block is already mined or too close on getting mined.");
        mintInfo.push(MintInfo({
            BonzaiPerBlock: _amount,
            mintStartBlock: _block
        }));
    }
    
    // Update the fiven blockspans startblock and mint amount. Can only be called by the owner.
    // Only possible to change for blocks not already mined.
    function setMint(uint256 _mid, uint256 _block, uint256 _amount) public onlyOwner {
        require(_block > block.number + 10, "_block is already mined or too close on getting mined.");
        require(mintInfo[_mid].mintStartBlock > block.number + 10, "mintStartBlock is already mined or too close on getting mined.");
        mintInfo[_mid].BonzaiPerBlock = _amount;
        mintInfo[_mid].mintStartBlock = _block;
    }
    
    // Deletes a given blockspan for minting. You can't delete first one. Can only be called by the owner.
    // Only possible to change for blocks not already mined.
    function deleteMint(uint256 _mid) public onlyOwner {
        require(_mid != 0, "You can't delete the first blockspan!");
        require(_mid < mintInfo.length, "_mid is invalid!");
        require(mintInfo[_mid].mintStartBlock > block.number + 10, "_block is already mined or too close on getting mined.");
        for(uint256 i = _mid; i < mintInfo.length - 1; i++){
            mintInfo[i] = mintInfo[i+1];
        }
        mintInfo.pop();
    }

    // Amount of pairs available for farming
    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }
    
    // Withdraw LP tokens from Farm.
    // Also used to claim the users pending Bonzai tokens
    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");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accBonzaiPerLPShare).div(1e18).sub(user.rewardDebt);
        safeBonzaiTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accBonzaiPerLPShare).div(1e18);
        pool.lpTokenContract.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }
    
    // Add a new LP contract to the pool. Can only be called by the owner.
    // !!! DO NOT add the same LP token more than once. Rewards will be messed up if you do !!!
    function addLP(string memory _name, uint256 _allocPoints, IERC20 _lpTokenContract, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardedBlock = block.number > mintInfo[0].mintStartBlock ? block.number : mintInfo[0].mintStartBlock;
        totalAllocPoints = totalAllocPoints.add(_allocPoints);
        poolInfo.push(PoolInfo({
            lpTokenContract: _lpTokenContract,
            name: _name,
            allocPoints: _allocPoints,
            lastRewardedBlock: lastRewardedBlock,
            accBonzaiPerLPShare: 0,
            lpTokenHolding: 0
        }));
    }

    // Update the given pools allocation points. Can only be called by the owner.
    function setLP(uint256 _pid, string memory _name, uint256 _allocPoints, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoints = totalAllocPoints.sub(poolInfo[_pid].allocPoints).add(_allocPoints);
        poolInfo[_pid].name = _name;
        poolInfo[_pid].allocPoints = _allocPoints;
    }

    // Return rewards over the given span from _from block to _to block.
    function getBonzaiAmountInRange(uint256 _from, uint256 _to) public view returns (uint256) {
        if(_from >= _to){
            return 0;
        }
        uint256 reward = 0;
        uint256 blocksleft = _to.sub(_from);
        for( uint256 cblock = _from+1; cblock <= _to; cblock++){
            if(cblock < mintInfo[0].mintStartBlock){
                blocksleft--;
            }
        }
        for( uint256 i = 0; i < mintInfo.length-1; i++){
            for( uint256 cblock = _from+1; cblock <= _to; cblock++){
                if(cblock >= mintInfo[i].mintStartBlock && cblock < mintInfo[i+1].mintStartBlock){
                    reward += mintInfo[i].BonzaiPerBlock;
                    blocksleft--;
                }
            }
        }
        reward += blocksleft.mul(mintInfo[mintInfo.length-1].BonzaiPerBlock);
        return reward;
    }

    // View function to see pending Bonzai on frontend.
    function pendingBonzai(uint256 _pid, address _user) public returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accBonzaiPerLPShare = pool.accBonzaiPerLPShare;
        // Users LP tokens who is connected to the site
        uint256 lpSupply = pool.lpTokenContract.balanceOf(address(this));
        pool.lpTokenHolding = lpSupply;
        if (block.number > pool.lastRewardedBlock && lpSupply > 0) {
            uint256 BonzaiReward = getBonzaiAmountInRange(pool.lastRewardedBlock, block.number).mul(pool.allocPoints).div(totalAllocPoints);
            BonzaiReward = BonzaiReward.mul(1e18);
            accBonzaiPerLPShare = accBonzaiPerLPShare.add(BonzaiReward.div(lpSupply));
        }
        return user.amount.mul(accBonzaiPerLPShare).div(1e18).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.lastRewardedBlock) {
            return;
        }
        uint256 lpSupply = pool.lpTokenContract.balanceOf(address(this));
        pool.lpTokenHolding = lpSupply;
        if (lpSupply == 0) {
            pool.lastRewardedBlock = block.number;
            return;
        }
        uint256 BonzaiReward = getBonzaiAmountInRange(pool.lastRewardedBlock, block.number).mul(pool.allocPoints).div(totalAllocPoints);
        Bonzai.mint(devaddr, BonzaiReward.div(5)); 
        Bonzai.mint(address(this), BonzaiReward);
        BonzaiReward = BonzaiReward.mul(1e18);
        pool.accBonzaiPerLPShare = pool.accBonzaiPerLPShare.add(BonzaiReward.div(lpSupply));
        pool.lastRewardedBlock = block.number;
    }

    // Deposit LP tokens to Farm for Bonzai allocation.
    // Also used to claim the users pending Bonzai tokens (_amount = 0)
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accBonzaiPerLPShare).div(1e18).sub(user.rewardDebt);
            safeBonzaiTransfer(msg.sender, pending);
        }
        pool.lpTokenContract.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accBonzaiPerLPShare).div(1e18);
        emit Deposit(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.lpTokenContract.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }

    // Safe Bonzai transfer function, just in case if rounding error causes pool to not have enough bonzai.
    function safeBonzaiTransfer(address _to, uint256 _amount) internal {
        uint256 BonzaiBal = Bonzai.balanceOf(address(this));
        if (_amount > BonzaiBal) {
            Bonzai.transfer(_to, BonzaiBal);
        } else {
            Bonzai.transfer(_to, _amount);
        }
    }
    
    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
    require(msg.sender == devaddr, "dev: nonono?");
    devaddr = _devaddr;
    }
}
function pendingBonzai(uint256 _pid, address _user) public returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accBonzaiPerLPShare = pool.accBonzaiPerLPShare;
        // Users LP tokens who is connected to the site
        uint256 lpSupply = pool.lpTokenContract.balanceOf(address(this));
        pool.lpTokenHolding = lpSupply;
        if (block.number > pool.lastRewardedBlock && lpSupply > 0) {
            uint256 BonzaiReward = getBonzaiAmountInRange(pool.lastRewardedBlock, block.number).mul(pool.allocPoints).div(totalAllocPoints);
            BonzaiReward = BonzaiReward.mul(1e18);
            accBonzaiPerLPShare = accBonzaiPerLPShare.add(BonzaiReward.div(lpSupply));
        }
        return user.amount.mul(accBonzaiPerLPShare).div(1e18).sub(user.rewardDebt);
    }
// View function to see pending Bonzai on frontend.