contract HeadFarmer 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 YieldXs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accYieldXPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accYieldXPerShare` (and `lastRewardBlock`) 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.
        uint256 userRewardPerTokenPaid;
    }

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

    // The YieldX TOKEN!
    YieldXToken public yieldx;
    // Dev address.
    address public devaddr;
    // Bar address.
    address public baraddr;
    // YieldX tokens created per block.
    uint256 public constant YIELDX_PER_BLOCK = 1e18;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigratorHead public migrator;
    StakingRewardsFactory public stakingRewardsFactory;

    // Referral
    mapping (address => string) public addressToReferralCode;
    mapping (string => address) public referralCodeToAddress;
    mapping (address => address) public addressToRefereeAddress;
    mapping (address => uint256) public addressToNumReferrals;
    mapping (address => uint256) public addressToNumYieldXViaReferral;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // 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 YieldX mining starts.
    //The block range for calculating YieldX Bonus
    uint256[7] public BLOCK_BOUNDRY = [uint256(11050000), 11320000, 13660000, 16000000, 18340000, 20680000, 23020000];
    // Bonus muliplier for each block range.
    uint256[6] public BONUS_MULTIPLIERS = [uint256(150),13,7,4,2,1];
    // Initial Dev Fund
    uint256 public initialDevFund;
    uint256 public constant INITIAL_DEV_VESTING_NUM_INSTALMENTS = 36;
    uint256 public constant INITIAL_DEV_VESTING_START_BLOCK = 11905000;
    uint256 public constant INITIAL_DEV_VESTING_PERIOD_LENGTH = 195000;
    mapping (uint256 => uint256) public claimedDevFund;

    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(
        YieldXToken _yieldx,
        address _devaddr,
        address _baraddr,
        StakingRewardsFactory _stakingRewardsFactory
    ) public {
        yieldx = _yieldx;
        devaddr = _devaddr;
        baraddr = _baraddr;
        stakingRewardsFactory = _stakingRewardsFactory;
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256) {
        return x < y ? x : y;
    }

    function max(uint256 x, uint256 y) internal pure returns (uint256) {
        return x > y ? x : y;
    }

    function sub(uint256 x, uint256 y) internal pure returns (uint256) {
        return x > y ? x - y : 0;
    }

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    // Set the migrator contract. Can only be called by the owner.
    function setYear5BlockBoundary(uint256 _year5BlockBoundary) public onlyOwner {
        BLOCK_BOUNDRY[6] = _year5BlockBoundary;
    }

    // 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 = max(block.number, BLOCK_BOUNDRY[0]);
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accYieldXPerShare: 0,
            lastUpdateTime: 0,
            rewardPerTokenStored: 0
        }));
    }

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

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigratorHead _migrator) public onlyOwner {
        migrator = _migrator;
    }

    // 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];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        updatePool(_pid);
        if (stakingRewardsAddress != address(0)) {
            StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
            uint256 tokensStaked = stakingRewards.balanceOf(address(this));
            if (tokensStaked > 0) {
                stakingRewards.withdraw(tokensStaked);
            }
        }
        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;
    }

    // Return reward multiplier over the given _from to _to block after initial period.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        uint256 multiplier = 0;
        for (uint256 x = 2; x < BLOCK_BOUNDRY.length; ++x) {
            multiplier = multiplier.add(sub(min(_to, BLOCK_BOUNDRY[x]), max(_from, BLOCK_BOUNDRY[x-1])).mul(BONUS_MULTIPLIERS[x-1]));
        }
        return multiplier;
    }

    // Return reward multiplier over the given _from to _to block in the initial period.
    function getMultiplierForInitialPeriod(uint256 _from, uint256 _to) public view returns (uint256) {
        return sub(min(_to, BLOCK_BOUNDRY[1]), max(_from, BLOCK_BOUNDRY[0])).mul(BONUS_MULTIPLIERS[0]);
    }

     // View function to see pending YieldXs on frontend.
    function pendingYieldX(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accYieldXPerShare = pool.accYieldXPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (stakingRewardsAddress != address(0)) {
            StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
            lpSupply = lpSupply.add(stakingRewards.balanceOf(address(this)));
        }
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplierForInitialPeriod = getMultiplierForInitialPeriod(pool.lastRewardBlock, block.number);
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            multiplier = multiplier.add(multiplierForInitialPeriod);
            uint256 yieldxReward = multiplier.mul(YIELDX_PER_BLOCK).mul(pool.allocPoint).div(totalAllocPoint);
            accYieldXPerShare = accYieldXPerShare.add(yieldxReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accYieldXPerShare).div(1e12).sub(user.rewardDebt);
    }

     // View function to see if extra reward is there for this pool.
    function hasExtraReward(uint256 _pid) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        if (stakingRewardsAddress != address(0)) {
            return 1;
        }
        return 0;
    }

     // View function to see pending reward on frontend.
    function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        UserInfo storage user = userInfo[_pid][_user];
        if (stakingRewardsAddress != address(0)) {
            StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
            uint256 rewardPerTokenStored = pool.rewardPerTokenStored;
            uint256 tokensStaked = stakingRewards.balanceOf(address(this));
            if (tokensStaked > 0) {
                uint256 reward = stakingRewards.earned(address(this));
                uint256 rewardPerToken = reward.mul(1e12).div(tokensStaked);
                rewardPerTokenStored = rewardPerTokenStored.add(rewardPerToken);
            }
            uint256 userRewardPerToken = rewardPerTokenStored.sub(user.userRewardPerTokenPaid);
            uint256 userReward = userRewardPerToken.mul(user.amount).div(1e12);
            return userReward;
        }
        return 0;
    }

    // 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];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (stakingRewardsAddress != address(0)) {
            StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
            lpSupply = lpSupply.add(stakingRewards.balanceOf(address(this)));
        }
        if (lpSupply > 0) {
            uint256 multiplierForInitialPeriod = getMultiplierForInitialPeriod(pool.lastRewardBlock, block.number);
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            if (multiplierForInitialPeriod > 0) {
                uint256 yieldxReward;
                yieldxReward = multiplierForInitialPeriod.mul(YIELDX_PER_BLOCK).mul(pool.allocPoint).div(totalAllocPoint);
                yieldx.mint(address(this), yieldxReward);
                yieldx.mint(baraddr, yieldxReward.div(10));
                initialDevFund += yieldxReward.div(10);
                pool.accYieldXPerShare = pool.accYieldXPerShare.add(yieldxReward.mul(1e12).div(lpSupply));
            }
            if (multiplier > 0) {
                uint256 yieldxReward;
                yieldxReward = multiplier.mul(YIELDX_PER_BLOCK).mul(pool.allocPoint).div(totalAllocPoint);
                yieldx.mint(address(this), yieldxReward);
                yieldx.mint(baraddr, yieldxReward.div(10));
                yieldx.mint(devaddr, yieldxReward.div(10));
                pool.accYieldXPerShare = pool.accYieldXPerShare.add(yieldxReward.mul(1e12).div(lpSupply));
            }
        }
        if (stakingRewardsAddress != address(0)) {
            StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
            uint256 tokensStaked = stakingRewards.balanceOf(address(this));
            if (tokensStaked > 0) {
                uint256 rewardsTokenBalanceBefore = stakingRewards.rewardsToken().balanceOf(address(this));
                stakingRewards.getReward();
                uint256 rewardsTokenBalanceAfter = stakingRewards.rewardsToken().balanceOf(address(this));
                uint256 reward = rewardsTokenBalanceAfter.sub(rewardsTokenBalanceBefore);
                uint256 rewardPerToken = reward.mul(1e12).div(tokensStaked);
                pool.rewardPerTokenStored = pool.rewardPerTokenStored.add(rewardPerToken);
            }
            uint256 userRewardPerToken = pool.rewardPerTokenStored.sub(user.userRewardPerTokenPaid);
            uint256 userReward = userRewardPerToken.mul(user.amount).div(1e12);
            if (userReward > 0) {
                stakingRewards.rewardsToken().safeTransfer(msg.sender, userReward);
            }
            user.userRewardPerTokenPaid = pool.rewardPerTokenStored;
        }
        pool.lastRewardBlock = block.number;
    }

    function claimDevFund(uint256 period) public {
        require(period < INITIAL_DEV_VESTING_NUM_INSTALMENTS, "period out of range");
        uint256 periodEndBlock = INITIAL_DEV_VESTING_START_BLOCK + INITIAL_DEV_VESTING_PERIOD_LENGTH * (period + 1);
        require(periodEndBlock <= block.number, "cannot claim for this period right now");
        uint256 initialDevFundPerPeriod = initialDevFund.div(INITIAL_DEV_VESTING_NUM_INSTALMENTS);
        require(claimedDevFund[period] < initialDevFundPerPeriod, "already claimed for this period");
        uint256 claimableDevFund = initialDevFundPerPeriod.sub(claimedDevFund[period]);
        claimedDevFund[period] = initialDevFundPerPeriod;
        yieldx.mint(devaddr, claimableDevFund);
    }

    // Deposit with referral code.
    function depositWithReferralCode(uint256 _pid, uint256 _amount, string calldata _referralCode, string calldata _refereeCode) external {
        if (bytes(_refereeCode).length != 0) {
            address refereeAddress = referralCodeToAddress[_refereeCode];
            require (refereeAddress != address(0), "invalid referral code");
            addressToRefereeAddress[msg.sender] = refereeAddress;
            addressToNumReferrals[refereeAddress] = addressToNumReferrals[refereeAddress].add(1);
        }
        require (bytes(_referralCode).length != 0, "referral code cannot be blank");
        require (bytes(addressToReferralCode[msg.sender]).length == 0, "referral code already generated");
        require (referralCodeToAddress[_referralCode] == address(0), "referral code already used");
        referralCodeToAddress[_referralCode] = msg.sender;
        addressToReferralCode[msg.sender] = _referralCode;
        deposit(_pid, _amount);
    }

    // Deposit LP tokens to HeadFarmer for YieldX allocation.
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accYieldXPerShare).div(1e12).sub(user.rewardDebt);
            if(pending > 0) {
                safeYieldXTransfer(msg.sender, pending);
            }
        }
        if(_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
            if (stakingRewardsAddress != address(0)) {
                StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
                pool.lpToken.safeApprove(stakingRewardsAddress, _amount);
                stakingRewards.stake(_amount);
            }
        }
        user.rewardDebt = user.amount.mul(pool.accYieldXPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from HeadFarmer.
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        (address stakingRewardsAddress, ) = stakingRewardsFactory.stakingRewardsInfoByStakingToken(address(pool.lpToken));
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accYieldXPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeYieldXTransfer(msg.sender, pending);
        }
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            if (stakingRewardsAddress != address(0)) {
                StakingRewards stakingRewards = StakingRewards(stakingRewardsAddress);
                stakingRewards.withdraw(_amount);
            }
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        user.rewardDebt = user.amount.mul(pool.accYieldXPerShare).div(1e12);
        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 yieldx transfer function, just in case if rounding error causes pool to not have enough YieldXs.
    function safeYieldXTransfer(address _to, uint256 _amount) internal {
        _amount = min(_amount, yieldx.balanceOf(address(this)));
        yieldx.transfer(_to, _amount);
        address refereeAddress = addressToRefereeAddress[_to];
        if (refereeAddress != address(0)) {
            uint256 refereeReward = _amount.div(10);
            yieldx.mint(refereeAddress, refereeReward);
            addressToNumYieldXViaReferral[refereeAddress] = addressToNumYieldXViaReferral[refereeAddress].add(refereeReward);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
}
// HeadFarmer is the head of YieldX. He can make YieldX and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once YieldX is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
function setYear5BlockBoundary(uint256 _year5BlockBoundary) public onlyOwner {
    BLOCK_BOUNDRY[6] = _year5BlockBoundary;
}

// Set the migrator contract. Can only be called by the owner.