contract TKNVFarm 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 TKNV
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (userInfo.amount * pool.accTKNVPerShare) - userInfo.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's accTKNVPerShare (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.
    }
    // Info of each pool.
    struct PoolInfo {
        IERC20 token; // Address of token or LP contract
        uint256 allocPoint; // How many allocation points assigned to this pool. TKNV to distribute per block.
        uint256 lastRewardBlock; // Last block number that TKNV distribution occurs.
        uint256 accTKNVPerShare; // Accumulated TKNV per share, times 1e12. See below.
    }
    
    // Total allocation points. Must be the sum of all allocation points in all pools.
    uint256 public totalAllocPoint = 0;
    // The block number when TKNV mining starts ->
        
    // max reward block
    uint256 public maxRewardBlockNumber;

    // rewad per block in wei
    uint256 public rewardPerBlock;
    
    // Accumulated TKNV per share, times 1e12.
    uint256 public accTKNVPerShareMultiple = 1E12;
    // The TKNV token!
    IERC20 public tknv;

    // Info on each pool added
    PoolInfo[] public poolInfo;
    // Info of each user that stakes tokens.
    mapping(uint256 => mapping(address => UserInfo)) public userInfo;
    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 _tknv,
        uint256 _rewardPerBlock,
        uint256 _maxRewardBlockNumber
    ) public {
        tknv = _tknv;
        rewardPerBlock = _rewardPerBlock;
        maxRewardBlockNumber = _maxRewardBlockNumber;
    }
    // Pool Length
    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    // Update maxRewardBlockNumber
    function updateMaxRewardBlockNumber(
        uint256 _newMaxRewardBlockNumber
    ) public onlyOwner {
        maxRewardBlockNumber = _newMaxRewardBlockNumber;
    }

    // Update rewardPerBlock
    function updateRewardPerBlock(
        uint256 _rewardPerBlock
    ) public onlyOwner {
        rewardPerBlock = _rewardPerBlock;
    }

    // Add a new token or 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 _token, // lp token address
        bool _withUpdate
    ) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(
            PoolInfo({
                token: _token,
                allocPoint: _allocPoint,
                lastRewardBlock: lastRewardBlock,
                accTKNVPerShare: 0
            })
        );
    }
    // Update the given pool's TKNV 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;
    }

    // View function to see pending TKNV on frontend.
    // function pendingTKNV(uint256 _pid, address _user)
    //     external
    //     view
    //     returns (uint256)
    // {
    //     PoolInfo storage pool = poolInfo[_pid];
    //     UserInfo storage user = userInfo[_pid][_user];
    //     uint256 accTKNVPerShare = pool.accTKNVPerShare;
    //     uint256 lpSupply = pool.token.balanceOf(address(this));
    //     if (
    //         block.number > pool.lastRewardBlock &&
    //         lpSupply != 0 &&
    //         pool.lastRewardBlock < maxRewardBlockNumber
    //     ) {
    //         uint256 totalReward =
    //             getTotalRewardInfo(pool.lastRewardBlock, block.number);
    //         uint256 tknvReward =
    //             totalReward.mul(pool.allocPoint).div(totalAllocPoint);
    //         accTKNVPerShare = accTKNVPerShare.add(
    //             tknvReward.mul(accTKNVPerShareMultiple).div(lpSupply)
    //         );
    //     }
    //     return
    //         user.amount.mul(accTKNVPerShare).div(accTKNVPerShareMultiple).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.token.balanceOf(address(this));
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        if (pool.lastRewardBlock >= maxRewardBlockNumber) {
            return;
        }

        uint256 totalReward = (block.number.sub(pool.lastRewardBlock)).mul(rewardPerBlock);
            
        uint256 tknvReward =
            totalReward.mul(pool.allocPoint).div(totalAllocPoint);
        // tknv.mintTo(address(this), tknvReward);
        pool.accTKNVPerShare = pool.accTKNVPerShare.add(
            tknvReward.mul(accTKNVPerShareMultiple).div(lpSupply)
        );
        pool.lastRewardBlock = block.number;
    }
    // Deposit tokens to TKNVFarmTest for TKNV 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.accTKNVPerShare)
                    .div(accTKNVPerShareMultiple)
                    .sub(user.rewardDebt);
            if (pending > 0) {
                safeTKNVTransfer(msg.sender, pending);
            }
        }
        pool.token.safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accTKNVPerShare).div(
            accTKNVPerShareMultiple
        );
        emit Deposit(msg.sender, _pid, _amount);
    }
    // Withdraw tokens from TKNVFarmTest
    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.accTKNVPerShare)
                .div(accTKNVPerShareMultiple)
                .sub(user.rewardDebt);
        if (pending > 0) {
            safeTKNVTransfer(msg.sender, pending);
        }
        if (_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.token.safeTransfer(address(msg.sender), _amount);
        }
        user.rewardDebt = user.amount.mul(pool.accTKNVPerShare).div(
            accTKNVPerShareMultiple
        );
        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.token.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }
    // Safe tknv transfer function, just in case if rounding error causes pool to not have enough $TKNV
    function safeTKNVTransfer(address _to, uint256 _amount) internal {
        uint256 tknvBal = tknv.balanceOf(address(this));
        if (_amount > tknvBal) {
            tknv.transfer(_to, tknvBal);
        } else {
            tknv.transfer(_to, _amount);
        }
    }

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

// Pool Length