contract DopeDealer 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.
        uint256 pendingRewards; // Pending rewards for user.
        uint256 lastHarvestBlock; //Block of last harvest, used for vesting
    }

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

    // DOPE token
    DopeSwap public dope;
    // DOPE tokens created per block.
    uint256 public dopePerBlock;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigrationMaster public migrator;
    //Has the minting rate halved?
    bool isMintingHalved;
    //Maximum DOPE supply
    uint256 public maxDopeSupply;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // 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 totalAllocPoint = 0;
    // The block number when DOPE mining starts.
    uint256 public startBlock;

    // Events
    event Recovered(address token, uint256 amount);
    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event Claim(address indexed user, uint256 indexed pid, uint256 amount);
    event ClaimAndStake(address indexed user, uint256 indexed pid, uint256 amount);
    event EmergencyWithdraw(
        address indexed user,
        uint256 indexed pid,
        uint256 amount
    );

    constructor(
        DopeSwap _dope,
        uint256 _dopePerBlock,
        uint256 _startBlock,
        uint256 _maxDopeSupply
    ) public {
        dope = _dope;
        dopePerBlock = _dopePerBlock;
        startBlock = _startBlock;
        isMintingHalved = false;
        maxDopeSupply = _maxDopeSupply*(10**dope.decimals());

        // staking pool
        poolInfo.push(PoolInfo({
            lpToken: _dope,
            allocPoint: 1000,
            lastRewardBlock: startBlock,
            accDopePerShare: 0,
            harvestVestingBlocks: 0
        }));

        totalAllocPoint = 1000;
    }

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }
    
    // Return reward multiplier over the given _from to _to block.
    // maybe add bonus
    function getMultiplier(uint256 _from, uint256 _to)
        public
        pure
        returns (uint256)
    {
        return _to.sub(_from);
        //Maybe add bonuses based on block?
    }

    // 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,
        uint _harvestVestingBlocks
    ) 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,
                accDopePerShare: 0,
                harvestVestingBlocks: _harvestVestingBlocks
            })
        );
        updateStakingPool();
    }

    // Update the given pool's DOPE 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
        );
        uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
        poolInfo[_pid].allocPoint = _allocPoint;
        if (prevAllocPoint != _allocPoint) {
            updateStakingPool();
        }
    }

    function updateStakingPool() internal {
        uint256 length = poolInfo.length;
        uint256 points = 0;
        for (uint256 pid = 1; pid < length; ++pid) {
            points = points.add(poolInfo[pid].allocPoint);
        }
        if (points != 0) {
            points = points.div(3);
            totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
            poolInfo[0].allocPoint = points;
        }
    }

    // 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 DOPEs on frontend.
    function pendingDOPEs(uint256 _pid, address _user)
        external
        view
        returns (uint256)
    {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accDopePerShare = pool.accDopePerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(
                pool.lastRewardBlock,
                block.number
            );
            uint256 dopeReward = multiplier
                .mul(dopePerBlock)
                .mul(pool.allocPoint)
                .div(totalAllocPoint);
            accDopePerShare = accDopePerShare.add(
                dopeReward.mul(1e12).div(lpSupply)
            );
        }
        return
            user.amount.mul(accDopePerShare).div(1e12).sub(user.rewardDebt).add(user.pendingRewards);
    }

    // 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 dopeReward = multiplier
            .mul(dopePerBlock)
            .mul(pool.allocPoint)
            .div(totalAllocPoint);
        uint256 currentSupply = dope.totalSupply();
        if(currentSupply.add(dopeReward) <= maxDopeSupply) {
            dope.mint(address(this), dopeReward);
        }
        pool.accDopePerShare = pool.accDopePerShare.add(
            dopeReward.mul(1e12).div(lpSupply)
        );
        pool.lastRewardBlock = block.number;
        //Should we halve the minting?
        if(block.number >= startBlock.add(100000) && !isMintingHalved) {
            dopePerBlock = dopePerBlock.div(2);
            isMintingHalved = true;
        }
    }

    // Deposit LP tokens to DopeDealer for DOPE allocation.
    function deposit(uint256 _pid, uint256 _amount, bool _withdrawRewards) public {
        require (_pid != 0, 'please deposit DOPE by staking');
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user
                .amount
                .mul(pool.accDopePerShare)
                .div(1e12)
                .sub(user.rewardDebt);
            
            if (pending > 0) {
                user.pendingRewards = user.pendingRewards.add(pending);

                if (_withdrawRewards) {
                    safeDopeTransfer(msg.sender, user.pendingRewards);
                    emit Claim(msg.sender, _pid, user.pendingRewards);
                    user.pendingRewards = 0;
                }
            }
        }
        if (_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);
        user.lastHarvestBlock = block.number;
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from DopeDealer.
    function withdraw(uint256 _pid, uint256 _amount, bool _withdrawRewards) public {
        require (_pid != 0, 'please withdraw DOPE by unstaking');
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        require (block.number >= user.lastHarvestBlock.add(pool.harvestVestingBlocks), 'withdraw: you cant harvest yet');
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
        if (pending > 0) {
            user.pendingRewards = user.pendingRewards.add(pending);

            if (_withdrawRewards) {
                safeDopeTransfer(msg.sender, user.pendingRewards);
                emit Claim(msg.sender, _pid, user.pendingRewards);
                user.pendingRewards = 0;
            }
        }
        if (_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);
        user.lastHarvestBlock = block.number;
        emit Withdraw(msg.sender, _pid, _amount);
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _pid) public {
        require (_pid != 0, 'please withdraw DOPE by unstaking');
        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;
        user.pendingRewards = 0;
        user.lastHarvestBlock = block.number;
    }

    // Claim rewards from DopeDealer.
    function claim(uint256 _pid) public {
        require (_pid != 0, 'please claim staking rewards on stake page');
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require (block.number >= user.lastHarvestBlock.add(pool.harvestVestingBlocks), 'withdraw: you cant harvest yet');
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
        if (pending > 0 || user.pendingRewards > 0) {
            user.pendingRewards = user.pendingRewards.add(pending);
            safeDopeTransfer(msg.sender, user.pendingRewards);
            emit Claim(msg.sender, _pid, user.pendingRewards);
            user.pendingRewards = 0;
            user.lastHarvestBlock = block.number;
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);
    }

    // Claim rewards from DopeDealer and deposit them directly to staking pool.
    function claimAndStake(uint256 _pid) public {
        require (_pid != 0, 'please claim and stake staking rewards on stake page');
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
        if (pending > 0 || user.pendingRewards > 0) {
            user.pendingRewards = user.pendingRewards.add(pending);
            transferToStake(user.pendingRewards);
            emit ClaimAndStake(msg.sender, _pid, user.pendingRewards);
            user.pendingRewards = 0;
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);
    }

    // Transfer rewards from LP pools to staking pool.
    function transferToStake(uint256 _amount) internal {
        PoolInfo storage pool = poolInfo[0];
        UserInfo storage user = userInfo[0][msg.sender];
        updatePool(0);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
            if (pending > 0) {
                user.pendingRewards = user.pendingRewards.add(pending);
            }
        }
        if (_amount > 0) {
            user.amount = user.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);

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

    // Stake DOPE tokens to DopeDealer.
    function enterStaking(uint256 _amount, bool _withdrawRewards) public {
        PoolInfo storage pool = poolInfo[0];
        UserInfo storage user = userInfo[0][msg.sender];
        updatePool(0);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
            if (pending > 0) {
                user.pendingRewards = user.pendingRewards.add(pending);

                if (_withdrawRewards) {
                    safeDopeTransfer(msg.sender, user.pendingRewards);
                    user.pendingRewards = 0;
                }
            }
        }
        if (_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);

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

    // Withdraw DOPE tokens from staking.
    function leaveStaking(uint256 _amount, bool _withdrawRewards) public {
        PoolInfo storage pool = poolInfo[0];
        UserInfo storage user = userInfo[0][msg.sender];
        require(user.amount >= _amount, "unstake: not good");
        updatePool(0);
        uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
        if (pending > 0) {
                user.pendingRewards = user.pendingRewards.add(pending);

                if (_withdrawRewards) {
                    safeDopeTransfer(msg.sender, user.pendingRewards);
                    user.pendingRewards = 0;
                }
            }
        if (_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);

        emit Withdraw(msg.sender, 0, _amount);
    }

    // Claim staking rewards from DopeDealer.
    function claimStaking() public {
        PoolInfo storage pool = poolInfo[0];
        UserInfo storage user = userInfo[0][msg.sender];
        updatePool(0);
        uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
        if (pending > 0 || user.pendingRewards > 0) {
            user.pendingRewards = user.pendingRewards.add(pending);
            safeDopeTransfer(msg.sender, user.pendingRewards);
            emit Claim(msg.sender, 0, user.pendingRewards);
            user.pendingRewards = 0;
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);
    }

    // Transfer staking rewards to staking pool.
    function stakeRewardsStaking() public {
        PoolInfo storage pool = poolInfo[0];
        UserInfo storage user = userInfo[0][msg.sender];
        uint256 rewardsToStake;
        updatePool(0);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
            if (pending > 0) {
                user.pendingRewards = user.pendingRewards.add(pending);
            }
        }
        if (user.pendingRewards > 0) {
            rewardsToStake = user.pendingRewards;
            user.pendingRewards = 0;
            user.amount = user.amount.add(rewardsToStake);
        }
        user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);

        emit Deposit(msg.sender, 0, rewardsToStake);
    }

    // Safe DOPE transfer function, just in case if rounding error causes pool to not have enough DOPEs.
    function safeDopeTransfer(address _to, uint256 _amount) internal {
        uint256 dopeBal = dope.balanceOf(address(this));
        if (_amount > dopeBal) {
            dope.transfer(_to, dopeBal);
        } else {
            dope.transfer(_to, _amount);
        }
    }

    // **** Additional functions to edit master attributes ****

    function setDopePerBlock(uint256 _dopePerBlock) public onlyOwner {
        require(_dopePerBlock > 0, "!dopePerBlock-0");
        dopePerBlock = _dopePerBlock;
    }

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigrationMaster _migrator) public onlyOwner {
        migrator = _migrator;
    }
}
function withdraw(uint256 _pid, uint256 _amount, bool _withdrawRewards) public {
    require (_pid != 0, 'please withdraw DOPE by unstaking');
    PoolInfo storage pool = poolInfo[_pid];
    UserInfo storage user = userInfo[_pid][msg.sender];
    require(user.amount >= _amount, "withdraw: not good");
    require (block.number >= user.lastHarvestBlock.add(pool.harvestVestingBlocks), 'withdraw: you cant harvest yet');
    updatePool(_pid);
    uint256 pending = user.amount.mul(pool.accDopePerShare).div(1e12).sub(user.rewardDebt);
    if (pending > 0) {
        user.pendingRewards = user.pendingRewards.add(pending);

        if (_withdrawRewards) {
            safeDopeTransfer(msg.sender, user.pendingRewards);
            emit Claim(msg.sender, _pid, user.pendingRewards);
            user.pendingRewards = 0;
        }
    }
    if (_amount > 0) {
        user.amount = user.amount.sub(_amount);
        pool.lpToken.safeTransfer(address(msg.sender), _amount);
    }
    user.rewardDebt = user.amount.mul(pool.accDopePerShare).div(1e12);
    user.lastHarvestBlock = block.number;
    emit Withdraw(msg.sender, _pid, _amount);
}

// Withdraw LP tokens from DopeDealer.