contract VoltsChef 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 CHARGED by a user is:
        //
        //   pending reward = (user.amount * pool.accVoltsPerLPShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accVoltsPerLPShare` (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 accVoltsPerLPShare; // Accumulated Volts per share.
        uint256 lpTokenHolding;     // Amount of LP token hold by this pool
    }

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

    // The Volts token contract
    VoltsToken public Volts;
    
    address public devaddr;
    // devmint cant be changed!
    uint256 public devmint;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of Volts 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(
        VoltsToken _Volts,
        address _devaddr,
        uint256 _devmint,
        uint256 _VoltsPerBlock,
        uint256 _mintStartBlock
    ) public {
        Volts = _Volts;
        devaddr = _devaddr;
        devmint = _devmint;
        mintInfo.push(MintInfo({
            VoltsPerBlock: _VoltsPerBlock,
            mintStartBlock: _mintStartBlock
        }));
    }
    
    // Get current mint per block
    function currentMint() public 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 Volts
    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) external onlyOwner {
        require(_block > block.number + 10, "_block is already mined or too close on getting mined.");
        mintInfo.push(MintInfo({
            VoltsPerBlock: _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) external 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].VoltsPerBlock = _amount;
        mintInfo[_mid].mintStartBlock = _block;
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            // Only true if first span isn't reached yet
            if(poolInfo[pid].lastRewardedBlock > mintInfo[_mid].mintStartBlock){
                poolInfo[pid].lastRewardedBlock = _block-1;
            }
        }
    }
    
    // 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) external 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;
    }
    
    // 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) external onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardedBlock = block.number > mintInfo[0].mintStartBlock ? block.number : mintInfo[0].mintStartBlock-1;
        totalAllocPoints = totalAllocPoints.add(_allocPoints);
        poolInfo.push(PoolInfo({
            lpTokenContract: _lpTokenContract,
            name: _name,
            allocPoints: _allocPoints,
            lastRewardedBlock: lastRewardedBlock,
            accVoltsPerLPShare: 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) external onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoints = totalAllocPoints.sub(poolInfo[_pid].allocPoints).add(_allocPoints);
        poolInfo[_pid].name = _name;
        poolInfo[_pid].allocPoints = _allocPoints;
    }

    // Return reward over the given span from _from block to _to block.
    function getVoltsAmountInRange(uint256 _from, uint256 _to) public view returns (uint256) {
        if(_from < mintInfo[0].mintStartBlock){
            _from = mintInfo[0].mintStartBlock-1;
        }
        if(_from >= _to) {
            return 0;
        }
        uint256 reward = 0;
        uint256 startIsIn = 0;
        bool startSet = false;
        uint256 endIsIn = 0;
        bool endSet = false;
        // If mintInfo.length-1 = 0 (as only one blockspan exists) startIsIn=endIsIn=0 by init.
        for( uint256 span = 0; span < mintInfo.length-1; span++) {
            if(_from+1 >= mintInfo[span].mintStartBlock && _from+1 < mintInfo[span+1].mintStartBlock) {
                startIsIn = span;
                startSet = true;
            }else if(!startSet){
                startIsIn = mintInfo.length-1;
            }
            if(_to >= mintInfo[span].mintStartBlock && _to < mintInfo[span+1].mintStartBlock) {
                endIsIn = span;
                endSet = true;
            }else if(!endSet){
                endIsIn = mintInfo.length-1;
            }
        }
        if(startIsIn == endIsIn) {
            return (_to.sub(_from)).mul(mintInfo[startIsIn].VoltsPerBlock);
        }else {
            // If mintInfo.length-1 = 0 (as only one blockspan exists) 'else' will never get used
            for(uint256 span = 0; span < mintInfo.length-1; span++) {
                if(startIsIn == endIsIn) {
                    reward += (_to.sub(_from)).mul(mintInfo[startIsIn].VoltsPerBlock);
                    return reward;
                }else {
                    reward += (mintInfo[startIsIn+1].mintStartBlock-1).sub(_from).mul(mintInfo[startIsIn].VoltsPerBlock);
                    _from = mintInfo[startIsIn+1].mintStartBlock-1;
                    startIsIn ++;
                }
            }
            if(startIsIn == endIsIn) {
                reward += (_to.sub(_from)).mul(mintInfo[startIsIn].VoltsPerBlock);
                return reward;
            }
        }
        return reward;
    }

    // View function to see pending Volts on frontend.
    function pendingVolts(uint256 _pid, address _user) external returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accVoltsPerLPShare = pool.accVoltsPerLPShare;
        // 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 VoltsReward = getVoltsAmountInRange(pool.lastRewardedBlock, block.number).mul(pool.allocPoints).mul(1e18).div(totalAllocPoints);
            accVoltsPerLPShare = accVoltsPerLPShare.add(VoltsReward.div(lpSupply));
        }
        return user.amount.mul(accVoltsPerLPShare).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 VoltsReward = getVoltsAmountInRange(pool.lastRewardedBlock, block.number).mul(pool.allocPoints).mul(1e18).div(totalAllocPoints);
        Volts.mint(devaddr, VoltsReward.mul(devmint).div(1e18).div(100));
        Volts.mint(address(this), VoltsReward.div(1e18));
        pool.accVoltsPerLPShare = pool.accVoltsPerLPShare.add(VoltsReward.div(lpSupply));
        pool.lastRewardedBlock = block.number;
    }

    // Deposit LP tokens to Chef for Volts allocation.
    // Also used to claim the users pending Volts tokens (_amount = 0)
    function deposit(uint256 _pid, uint256 _amount) external {
        require(!Address.isContract(address(msg.sender)), "Please use your individual account.");
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accVoltsPerLPShare).div(1e18).sub(user.rewardDebt);
            safeVoltsTransfer(msg.sender, pending);
        }
        pool.lpTokenContract.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accVoltsPerLPShare).div(1e18);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from Chef.
    // Also used to claim the users pending Volts tokens
    function withdraw(uint256 _pid, uint256 _amount) external {
        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.accVoltsPerLPShare).div(1e18).sub(user.rewardDebt);
        safeVoltsTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accVoltsPerLPShare).div(1e18);
        pool.lpTokenContract.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _pid) external {
        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 Volts transfer function, just in case if rounding error causes pool to not have enough tokens.
    function safeVoltsTransfer(address _to, uint256 _amount) internal returns (bool) {
        uint256 VoltsBal = Volts.balanceOf(address(this));
        if (_amount > VoltsBal) {
            return Volts.transfer(_to, VoltsBal);
        } else {
            return Volts.transfer(_to, _amount);
        }
    }
    
    // Update dev address by the previous dev.
    function changeDevaddr(address _devaddr) external {
        require(msg.sender == devaddr, "Sender isnt dev!");
        devaddr = _devaddr;
    }
}
function addLP(string memory _name, uint256 _allocPoints, IERC20 _lpTokenContract, bool _withUpdate) external onlyOwner {
    if (_withUpdate) {
        massUpdatePools();
    }
    uint256 lastRewardedBlock = block.number > mintInfo[0].mintStartBlock ? block.number : mintInfo[0].mintStartBlock-1;
    totalAllocPoints = totalAllocPoints.add(_allocPoints);
    poolInfo.push(PoolInfo({
        lpTokenContract: _lpTokenContract,
        name: _name,
        allocPoints: _allocPoints,
        lastRewardedBlock: lastRewardedBlock,
        accVoltsPerLPShare: 0,
        lpTokenHolding: 0
    }));
}

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