contract Gravity 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.
    }

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


    // The MILKYWAY_Token!
    MilkyWayToken public milk;

    // Dev address.
    address public devAddr;

    // Distribution address.
    address public distributor;

    // The block number when MILK2 mining starts.
    uint256 public startFirstPhaseBlock;

    // The block number when MILK2 mining starts.
    uint256 public startSecondPhaseBlock;

    // The block number when MILK2 mining starts.
    uint256 public startThirdPhaseBlock;

    // Block number when bonus MILK2 period ends.
    uint256 public bonusEndBlock;

    // Bonus multiplier for early milk2 makers.
    uint256[4] private milkPerBlocks = [20, 10, 5, 2];

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


    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(
        MilkyWayToken _milk,
        address _devAddr,
        address _distributor,
        uint256 _startFirstPhaseBlock
    ) public {
        milk = _milk;
        devAddr = _devAddr;
        distributor = _distributor;
        startFirstPhaseBlock = _startFirstPhaseBlock;
        startSecondPhaseBlock = startFirstPhaseBlock.add(10000);
        startThirdPhaseBlock = startSecondPhaseBlock.add(30000);
        bonusEndBlock = startThirdPhaseBlock.add(60000);
    }

    // view length of liquidity pools
    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 onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startFirstPhaseBlock ? block.number : startFirstPhaseBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
        lpToken: _lpToken,
        allocPoint: _allocPoint,
        lastRewardBlock: lastRewardBlock,
        accMilkPerShare: 0
        }));
    }


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


    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        if (_to <= startFirstPhaseBlock) { // 0
            return  _to.sub(_from).mul(milkPerBlocks[3]);
        }
        else if (_to <= startSecondPhaseBlock) { // + 10,000 blocks
            return _to.sub(_from).mul(milkPerBlocks[0]);
        }
        else if (_to <= startThirdPhaseBlock) { // + 40,000 blocks
            return _to.sub(_from).mul(milkPerBlocks[1]);
        }
        else if (_to <= bonusEndBlock) { // + 40,000 blocks
            return _to.sub(_from).mul(milkPerBlocks[2]);
        }
        else  { // + 100,000 blocks
            return _to.sub(_from).mul(milkPerBlocks[3]);
        }
    }


    // View current block reward in MILK2s
    function getCurrentBlockReward(uint256 _currentBlock) public view returns (uint256) {
        if (_currentBlock <= startFirstPhaseBlock) {
            return 0;
        }
        else if (_currentBlock <= startSecondPhaseBlock) {
            return milkPerBlocks[0];
        }
        else if (_currentBlock <= startThirdPhaseBlock) {
            return milkPerBlocks[1];
        }
        else if (_currentBlock <= bonusEndBlock) {
            return milkPerBlocks[2];
        }
        else {
            return milkPerBlocks[3];
        }
    }


    // View function to see pending MILK2s on frontend.
    function pendingMilk(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accMilkPerShare = pool.accMilkPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));

        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 milkReward = (multiplier.mul(1e18)).mul(pool.allocPoint).div(totalAllocPoint);
            accMilkPerShare = accMilkPerShare.add(milkReward.mul(1e12).div(lpSupply));
        }

        return user.amount.mul(accMilkPerShare).div(1e12).sub(user.rewardDebt);
    }


    // 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 milkReward = multiplier.mul(1e18).mul(pool.allocPoint).div(totalAllocPoint);
        milk.mint(devAddr, milkReward.mul(3).div(100)); // 3% developers
        milk.mint(distributor, milkReward.div(100)); // 1% shakeHolders
        milk.mint(address(this), milkReward);
        pool.accMilkPerShare = pool.accMilkPerShare.add(milkReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }


    // Deposit LP tokens to Interstellar for MILK allocation.
    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.accMilkPerShare).div(1e12).sub(user.rewardDebt);
            safeMilkTransfer(msg.sender, pending);
        }

        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }


    // Withdraw LP tokens from Interstellar.
    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.accMilkPerShare).div(1e12).sub(user.rewardDebt);
        safeMilkTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accMilkPerShare).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 milk2 transfer function, just in case if rounding error causes pool to not have enough MILK2s.
    function safeMilkTransfer(address _to, uint256 _amount) internal {
        uint256 milkBal = milk.balanceOf(address(this));
        if (_amount > milkBal) {
            milk.transfer(_to, milkBal);
        } else {
            milk.transfer(_to, _amount);
        }
    }


    // Update dev address by the previous dev.
    function dev(address _devAddr) public {
        require(msg.sender == devAddr, "dev: wut?");
        devAddr = _devAddr;
    }


    // Update distributor address by the previous dev.
    function updateDistributor(address _distributor) public {
        require(msg.sender == devAddr, "dev: wut?");
        distributor = _distributor;
    }

}
/**
 // Note that it's ownable and the owner wields tremendous power. The ownership
 // will be transferred to a governance smart contract once MILKYWAY is sufficiently
 // distributed and the community can show to govern itself.
 //
 // Have fun reading it. Hopefully it's bug-free. God bless.
 */
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.accMilkPerShare).div(1e12).sub(user.rewardDebt);
    safeMilkTransfer(msg.sender, pending);
    user.amount = user.amount.sub(_amount);
    user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e12);
    pool.lpToken.safeTransfer(address(msg.sender), _amount);
    emit Withdraw(msg.sender, _pid, _amount);
}

// Withdraw LP tokens from Interstellar.