contract LPTokenWrapper is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // -- yam things
    IERC20 public slp = IERC20(0x0F82E57804D0B1F6FAb2370A43dcFAd3c7cB239c);
    IERC20 public yam = IERC20(0x0AaCfbeC6a24756c20D41914F2caba817C0d8521);
    address public reserves = address(0x97990B693835da58A281636296D2Bf02787DEa17);

    // -- Sushi things
    IERC20 public sushi = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
    SushiBar public sushibar = SushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272);
    MasterChef public masterchef = MasterChef(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd);
    uint256 public pid = 44; // YAM/ETH pool id
    bool public chefEmergency;

    // approve masterchef on initiation
    constructor () internal {
        slp.approve(address(masterchef), uint256(-1));
    }

    uint256 public minBlockBeforeVoting;
    bool public minBlockSet;

    uint256 private _totalSupply;

    uint256 public constant BASE = 10**18;

    mapping(address => uint256) private _balances;


    mapping(address => address) public delegates;

    /// @notice A checkpoint for marking number of lp tokens staked from a given block
    struct Checkpoint {
        uint32 fromBlock;
        uint256 lpStake;
    }

    /// @notice A record of votes checkpoints for each account, by index
    mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;

    /// @notice The number of checkpoints for each account
    mapping (address => uint32) public numCheckpoints;

    /// @notice The number of checkpoints for total supply
    mapping (uint32 => Checkpoint) public totalSupplyCheckpoints;

    uint32 public numSupplyCheckpoints;

    function totalSupply() public view returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view returns (uint256) {
        return _balances[account];
    }

    function delegate(address delegatee) public {
        _delegate(msg.sender, delegatee);
    }

    function _delegate(address delegator, address delegatee)
        internal
    {
        address currentDelegate = delegates[msg.sender];
        uint256 delegatorBalance = _balances[msg.sender];
        delegates[msg.sender] = delegatee;

        _moveDelegates(currentDelegate, delegatee, delegatorBalance);
    }

    function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
        if (srcRep != dstRep && amount > 0) {
            if (srcRep != address(0)) {
                // decrease old representative
                uint32 srcRepNum = numCheckpoints[srcRep];
                uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].lpStake : 0;
                uint256 srcRepNew = srcRepOld.sub(amount);
                _writeCheckpoint(srcRep, srcRepNum, srcRepNew);
            }

            if (dstRep != address(0)) {
                // increase new representative
                uint32 dstRepNum = numCheckpoints[dstRep];
                uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].lpStake : 0;
                uint256 dstRepNew = dstRepOld.add(amount);
                _writeCheckpoint(dstRep, dstRepNum, dstRepNew);
            }
        }
    }


    function stake(uint256 amount) public {
        _totalSupply = _totalSupply.add(amount);
        uint256 new_bal = _balances[msg.sender].add(amount);
        _balances[msg.sender] = new_bal;
        address delegate = delegates[msg.sender];
        if (delegate == address(0)) {
          delegates[msg.sender] = msg.sender;
          delegate = msg.sender;
        }
        _moveDelegates(address(0), delegate, amount);
        _writeSupplyCheckpoint();
        // deposit here
        slp.safeTransferFrom(msg.sender, address(this), amount);
        // deposit to masterchef
        depositToMasterChef(amount);
    }

    function withdraw(uint256 amount) public {
        _totalSupply = _totalSupply.sub(amount);
        uint256 new_bal = _balances[msg.sender].sub(amount);
        _balances[msg.sender] = new_bal;
        _moveDelegates(delegates[msg.sender], address(0), amount);
        _writeSupplyCheckpoint();
        // withdraw from masterchef
        withdrawFromMasterChef(amount);
        // send to user
        slp.safeTransfer(msg.sender, amount);
    }

    function depositToMasterChef(uint256 amount) internal {
        // LP token allowance does not decrease when set to -1
        if (!chefEmergency) {
            masterchef.deposit(pid, amount);
        }
    }

    function withdrawFromMasterChef(uint256 amount) internal {
        if (!chefEmergency) {
            masterchef.withdraw(pid, amount);
        }
    }

    // callable by anyone, this function sweeps earned rewards into sushibar
    function sweepToXSushi() public {
        masterchef.withdraw(pid, 0);
        uint256 sushi_bal = sushi.balanceOf(address(this));
        if (sushi.allowance(address(this), address(sushibar)) < sushi_bal) {
            sushi.approve(address(sushibar), uint256(-1));
        }
        sushibar.enter(sushi_bal);
    }

    function sushiToReserves(uint256 xsushi_amt) public {
        require(owner() == msg.sender, "!owner");

        // if -1, sweep all
        if (xsushi_amt == uint256(-1)) {
          xsushi_amt = IERC20(address(sushibar)).balanceOf(address(this));
        }

        sushibar.leave(xsushi_amt);
        sushi.transfer(reserves, sushi.balanceOf(address(this)));
    }

    function setReserves(address newReserves) public {
        require(owner() == msg.sender, "!owner");
        reserves = newReserves;
    }

    function emergencyMasterChefWithdraw() public {
        require(owner() == msg.sender, "!owner");
        masterchef.emergencyWithdraw(pid);
        chefEmergency = true;
    }

    function reenableChef() public {
        require(owner() == msg.sender, "!owner");
        require(chefEmergency, "!emergency");
        masterchef.deposit(pid, slp.balanceOf(address(this)));
        chefEmergency = false;
    }

    /**
     * @notice Gets the current votes balance for `account`
     * @param account The address to get votes balance
     * @return The number of current votes for `account`
     */
    function getCurrentVotes(address account)
        external
        view
        returns (uint256)
    {
        if (!minBlockSet || block.number < minBlockBeforeVoting) {
            return 0;
        }
        uint256 poolVotes = YAM(address(yam)).getCurrentVotes(address(slp));
        uint32 nCheckpoints = numCheckpoints[account];
        uint256 lpStake = nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].lpStake : 0;
        uint256 percOfVotes = lpStake.mul(BASE).div(_totalSupply);
        return poolVotes.mul(percOfVotes).div(BASE);
    }

    function getPriorVotes(address account, uint256 blockNumber)
        public
        view
        returns (uint256)
    {
        require(blockNumber < block.number, "Incentivizer::getPriorVotes: not yet determined");
        if (!minBlockSet || blockNumber < minBlockBeforeVoting) {
            return 0;
        }
        // get incentivizer's uniswap pool yam votes
        uint256 poolVotes = YAM(address(yam)).getPriorVotes(address(slp), blockNumber);

        if (poolVotes == 0) {
            return 0;
        }

        // get prior stake
        uint256 priorStake = _getPriorLPStake(account, blockNumber);

        if (priorStake == 0) {
            return 0;
        }

        // get prior LP stake
        uint256 lpTotalSupply = getPriorSupply(blockNumber);

        if (lpTotalSupply == 0) {
            return 0;
        }

        // get percent ownership of staked LPs
        uint256 percentOfVote = priorStake.mul(BASE).div(lpTotalSupply);

        // votes * percentage / percentage max
        // note: this will overestimate the number of votes based on
        //       % of LP pool tokens staked here
        return poolVotes.mul(percentOfVote).div(BASE);
    }

    function getPriorLPStake(address account, uint256 blockNumber)
        public
        view
        returns (uint256)
    {
        require(blockNumber < block.number, "Incentivizer::_getPriorLPStake: not yet determined");
        return _getPriorLPStake(account, blockNumber);
    }

    function _getPriorLPStake(address account, uint256 blockNumber)
        internal
        view
        returns (uint256)
    {
        uint32 nCheckpoints = numCheckpoints[account];
        if (nCheckpoints == 0) {
            return 0;
        }

        // First check most recent balance
        if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
            return checkpoints[account][nCheckpoints - 1].lpStake;
        }

        // Next check implicit zero balance
        if (checkpoints[account][0].fromBlock > blockNumber) {
            return 0;
        }

        uint32 lower = 0;
        uint32 upper = nCheckpoints - 1;
        while (upper > lower) {
            uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            Checkpoint memory cp = checkpoints[account][center];
            if (cp.fromBlock == blockNumber) {
                return cp.lpStake;
            } else if (cp.fromBlock < blockNumber) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return checkpoints[account][lower].lpStake;
    }

    function _writeCheckpoint(
        address delegatee,
        uint32 nCheckpoints,
        uint256 newStake
    )
        internal
    {
        // this means this contract can lock funds in approximately 1766 years from now.
        uint32 blockNumber = safe32(block.number, "Incentivizer::_writeCheckpoint: block number exceeds 32 bits");

        if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
            checkpoints[delegatee][nCheckpoints - 1].lpStake = newStake;
        } else {
            checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newStake);
            numCheckpoints[delegatee] = nCheckpoints + 1;
        }
    }

    function _writeSupplyCheckpoint()
        internal
    {
        uint32 blockNumber = safe32(block.number, "Incentivizer::_writeSupplyCheckpoint: block number exceeds 32 bits");

        // overwrite totalSupplyCheckpoint for block, increment counter if needed
        if (numSupplyCheckpoints > 0 && totalSupplyCheckpoints[numSupplyCheckpoints - 1].fromBlock == blockNumber) {
            totalSupplyCheckpoints[numSupplyCheckpoints - 1].lpStake = _totalSupply;
        } else {
            totalSupplyCheckpoints[numSupplyCheckpoints] = Checkpoint(blockNumber, _totalSupply);
            numSupplyCheckpoints += 1;
        }
    }

    function getPriorSupply(uint256 blockNumber)
        public
        view
        returns (uint256)
    {
        if (numSupplyCheckpoints == 0) {
            return 0;
        }

        // First check most recent balance
        if (totalSupplyCheckpoints[numSupplyCheckpoints - 1].fromBlock <= blockNumber) {
            return totalSupplyCheckpoints[numSupplyCheckpoints - 1].lpStake;
        }

        // Next check implicit zero balance
        if (totalSupplyCheckpoints[0].fromBlock > blockNumber) {
            return 0;
        }

        uint32 lower = 0;
        uint32 upper = numSupplyCheckpoints - 1;
        while (upper > lower) {
            uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            Checkpoint memory cp = totalSupplyCheckpoints[center];
            if (cp.fromBlock == blockNumber) {
                return cp.lpStake;
            } else if (cp.fromBlock < blockNumber) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return totalSupplyCheckpoints[lower].lpStake;
    }

    function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
        require(n < 2**32, errorMessage);
        return uint32(n);
    }

    function setMinBlockBeforeVoting(uint256 blockNum)
        external
    {
        // only gov
        require(msg.sender == owner(), "!governance");
        require(!minBlockSet, "minBlockSet");
        minBlockBeforeVoting = blockNum;
        minBlockSet = true;
    }
}
function getCurrentVotes(address account)
    external
    view
    returns (uint256)
{
    if (!minBlockSet || block.number < minBlockBeforeVoting) {
        return 0;
    }
    uint256 poolVotes = YAM(address(yam)).getCurrentVotes(address(slp));
    uint32 nCheckpoints = numCheckpoints[account];
    uint256 lpStake = nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].lpStake : 0;
    uint256 percOfVotes = lpStake.mul(BASE).div(_totalSupply);
    return poolVotes.mul(percOfVotes).div(BASE);
}

/**
 * @notice Gets the current votes balance for `account`
 * @param account The address to get votes balance
 * @return The number of current votes for `account`
 */