contract DimSumMasterChef 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 Tokens
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accTokenPerShare) - user.rewardDebt
    }

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

    modifier onlyPoolAdder() {
        require(
            msg.sender == poolAdderAddr,
            "MasterChef: Sender not pool adder"
        );
        _;
    }

    IERC20 public Token;
    // Dev address.
    address public devaddr;
    // Pool Adder address.
    address public poolAdderAddr;
    // Token tokens created per block.
    uint256 public TokenPerBlock;

    // Token token hardcap
    uint256 public TokenHardCap;
    IMigratorChef public migrator;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    mapping(address => bool) public lpTokenExistsInPool;
    // 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 Token mining starts.
    uint256 public startBlock;

    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(
        IERC20 _tokenAddr,
        address _devaddr,
        address _poolAdderAddr,
        uint256 _startBlock
    ) public {
        Token = _tokenAddr;
        poolAdderAddr = _poolAdderAddr;
        devaddr = _devaddr;
        TokenPerBlock = 20 ether;
        TokenHardCap = 400000 ether;
        startBlock = _startBlock;
    }

    function setPoolAdderAddr(address _newAddr) external onlyPoolAdder {
        poolAdderAddr = _newAddr;
    }

    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 onlyPoolAdder {
        require(
            !lpTokenExistsInPool[address(_lpToken)],
            "MasterChef: LP Token Address already exists in pool"
        );
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock
            ? block.number
            : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(
            PoolInfo({
                lpToken: _lpToken,
                allocPoint: _allocPoint,
                lastRewardBlock: lastRewardBlock,
                accTokenPerShare: 0
            })
        );
        lpTokenExistsInPool[address(_lpToken)] = true;
    }

    function updateLpTokenExists(address _lpTokenAddr, bool _isExists)
        external
        onlyPoolAdder
    {
        lpTokenExistsInPool[_lpTokenAddr] = _isExists;
    }

    // Update the given pool's Token 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;
    }

    function setMigrator(IMigratorChef _migrator) public onlyOwner {
        migrator = _migrator;
    }

    function migrate(uint256 _pid) public onlyOwner {
        require(
            address(migrator) != address(0),
            "MasterChef: Address of migrator is null"
        );
        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(
            !lpTokenExistsInPool[address(newLpToken)],
            "MasterChef: New LP Token Address already exists in pool"
        );
        require(
            bal == newLpToken.balanceOf(address(this)),
            "MasterChef: New LP Token balance incorrect"
        );
        pool.lpToken = newLpToken;
        lpTokenExistsInPool[address(newLpToken)] = true;
    }

    // View function to see pending Tokens on frontend.
    function pendingToken(uint256 _pid, address _user)
        external
        view
        returns (uint256)
    {
        if (Token.totalSupply() >= TokenHardCap) {
            return 0;
        }
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accTokenPerShare = pool.accTokenPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 blockPassed = block.number.sub(pool.lastRewardBlock);
            uint256 TokenReward = blockPassed
                .mul(TokenPerBlock)
                .mul(pool.allocPoint)
                .div(totalAllocPoint);
            accTokenPerShare = accTokenPerShare.add(
                TokenReward.mul(1e12).div(lpSupply)
            );
        }
        uint256 pendingAmt = user.amount.mul(accTokenPerShare).div(1e12).sub(
            user.rewardDebt
        );

        return
            pendingAmt > TokenHardCap ||
                pendingAmt.add(Token.totalSupply()) > TokenHardCap
                ? TokenHardCap.sub(Token.totalSupply())
                : user.amount.mul(accTokenPerShare).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;
        }
        if (Token.totalSupply() >= TokenHardCap) {
            TokenPerBlock = 0;
            return;
        }
        uint256 blockPassed = block.number.sub(pool.lastRewardBlock);
        uint256 TokenReward = blockPassed
            .mul(TokenPerBlock)
            .mul(pool.allocPoint)
            .div(totalAllocPoint);

        if (
            TokenReward > TokenHardCap ||
            TokenReward.add(Token.totalSupply()) > TokenHardCap
        ) {
            // No dev reward
            TokenReward = TokenHardCap.sub(Token.totalSupply());
        } else if (
            TokenReward != TokenHardCap &&
            TokenReward.add(Token.totalSupply()) != TokenHardCap
        ) {
            Token.mint(devaddr, TokenReward.div(100)); // 1%
        }

        Token.mint(address(this), TokenReward);

        pool.accTokenPerShare = pool.accTokenPerShare.add(
            TokenReward.mul(1e12).div(lpSupply)
        );
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterChef for Token allocation.
    function deposit(uint256 _pid, uint256 _amount) public {
        if (Token.totalSupply() >= TokenHardCap) {
            TokenPerBlock = 0;
            return;
        }
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user
                .amount
                .mul(pool.accTokenPerShare)
                .div(1e12)
                .sub(user.rewardDebt);
            safeTokenTransfer(msg.sender, pending);
        }
        pool.lpToken.safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from MasterChef.
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(
            user.amount >= _amount,
            "MasterChef: Insufficient Amount to withdraw"
        );
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(
            user.rewardDebt
        );
        safeTokenTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
        pool.lpToken.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(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.lpToken.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }

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

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(
            msg.sender == devaddr,
            "MasterChef: Sender is not the developer"
        );
        devaddr = _devaddr;
    }
}
function safeTokenTransfer(address _to, uint256 _amount) internal {
    uint256 TokenBal = Token.balanceOf(address(this));
    if (_amount > TokenBal) {
        Token.transfer(_to, TokenBal);
    } else {
        Token.transfer(_to, _amount);
    }
}

// Safe Token transfer function, just in case if rounding error causes pool to not have enough Tokens.