// File: contracts/tokenomics/Vote.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.20;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

import "../../interfaces/tokenomics/ITORUSLockerV2.sol";

contract Vote is Ownable, ReentrancyGuard {
    address public voteLocker;

    uint256 internal constant DURATION = 7 days;
    uint256 public constant MAX_VOTE_DELAY = 7 days;
    uint256 internal constant WEEK = 86400 * 7; // allows minting once per week (reset every Thursday 00:00 UTC)
    uint256 public active_period;
    uint256 public VOTE_DELAY; // delay between votes in seconds

    mapping(address => mapping(address => uint256)) public votes; // user => pool => votes
    mapping(address => address[]) public poolVote; // user => pool
    mapping(uint256 => mapping(address => uint256)) internal weightsPerEpoch; // timestamp => pool => weights
    mapping(uint256 => uint256) internal totalWeightsPerEpoch; // timestamp => total weights
    mapping(address => uint256) public lastVoted; // user => timestamp of last vote
    mapping(address => bool) public isAlive; // crv pool => boolean [is pool alive for vote?]
    mapping(address => bool) public poolAdded; // crv pool => existance
    address[] internal pools;

    event Voted(address indexed voter, uint256 weight);

    constructor(address _voteLocker) public {
        voteLocker = _voteLocker;
    }

    // @notice Vote for pools
    // @param _poolVote array of LP addresses to vote
    // @param _weights  array of weights for each LPs
    function vote(address[] calldata _poolVote, uint256[] calldata _weights) external nonReentrant {
        _voteDelay(msg.sender);
        _vote(msg.sender, _poolVote, _weights);
        lastVoted[msg.sender] = _epochTimestamp() + 1;
    }

    function _vote(address _user, address[] memory _poolVote, uint256[] memory _weights) internal {
        _reset(_user);
        uint256 _poolCnt = _poolVote.length;
        uint256 _weight = ITORUSLockerV2(voteLocker).balanceOf(_user);
        uint256 _totalVoteWeight = 0;
        uint256 _totalWeight = 0;
        uint256 _usedWeight = 0;
        uint256 _time = _epochTimestamp();
        active_period = _time;
        
        for (uint256 i = 0; i < _poolCnt; i++) {
            if (isAlive[_poolVote[i]]) _totalVoteWeight += _weights[i];
        }

        for (uint256 i = 0; i < _poolCnt; i++) {
            address _pool = _poolVote[i];

            if (isAlive[_pool]) {
                uint256 _poolWeight = _weights[i] * _weight / _totalVoteWeight;

                require(votes[_user][_pool] == 0);
                require(_poolWeight != 0);

                poolVote[_user].push(_pool);
                weightsPerEpoch[_time][_pool] += _poolWeight;

                votes[_user][_pool] += _poolWeight;

                _usedWeight += _poolWeight;
                _totalWeight += _poolWeight;
                emit Voted(msg.sender, _poolWeight);
            }
        }
        totalWeightsPerEpoch[_time] += _totalWeight;
    }

    function _reset(address _user) internal {
        address[] storage _poolVote = poolVote[_user];
        uint256 _poolVoteCnt = _poolVote.length;
        uint256 _totalWeight = 0;
        uint256 _time = _epochTimestamp();

        for (uint256 i; i < _poolVoteCnt; i++) {
            address _pool = _poolVote[i];
            uint256 _votes = votes[_user][_pool];

            if (_votes != 0) {
                if (lastVoted[_user] > _time) {
                    weightsPerEpoch[_time][_pool] -= _votes;
                }
                votes[_user][_pool] = 0;

                if (isAlive[_pool]) {
                    _totalWeight += _votes;
                }
            }
        }

        if (lastVoted[_user] < _time) {
            _totalWeight = 0;
        }
        totalWeightsPerEpoch[_time] -= _totalWeight;
    }

    /// @notice check if user can vote
    function _voteDelay(address _user) internal view {
        require(block.timestamp > lastVoted[_user] + VOTE_DELAY, "ERR: VOTE_DELAY");
    }

    function addPool(address _pool) external onlyOwner {
        require(!poolAdded[_pool], "Already added");
        pools.push(_pool);
        poolAdded[_pool] = true;
    }

    function _epochTimestamp() internal view returns (uint256) {
        return block.timestamp / 1 weeks * 1 weeks;
    }

    function setPoolState(address _pool, bool _state) external onlyOwner {
        if (poolAdded[_pool]) {
            isAlive[_pool] = _state;
        }
    }

    function getPoolVote(address _user) external view returns (address[] memory) {
        return poolVote[_user];
    }

    function getPools() external view returns (address[] memory) {
        return pools;
    }

    function getPoolWeightPerEpoch(uint256 _timestamp, address _pool) external view returns (uint256) {
        return weightsPerEpoch[_timestamp][_pool];
    }
}

// File: node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: node_modules/@openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: interfaces/tokenomics/ITORUSLockerV2.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.20;

import "../../libraries/MerkleProof.sol";

interface ITORUSLockerV2 {
    event Locked(address indexed account, uint256 amount, uint256 unlockTime, bool relocked);
    event UnlockExecuted(address indexed account, uint256 amount);
    event Relocked(address indexed account, uint256 amount);
    event KickExecuted(address indexed account, address indexed kicker, uint256 amount);
    event FeesReceived(address indexed sender, uint256 crvAmount, uint256 cvxAmount);
    event FeesClaimed(address indexed claimer, uint256 crvAmount, uint256 cvxAmount);
    event AirdropBoostClaimed(address indexed claimer, uint256 amount);
    event Shutdown();
    event TokenRecovered(address indexed token);

    struct VoteLock {
        uint256 amount;
        uint64 unlockTime;
        uint128 boost;
        uint64 id;
    }

    function lock(uint256 amount, uint64 lockTime) external;

    function lock(
        uint256 amount,
        uint64 lockTime,
        bool relock
    ) external;

    function lockFor(
        uint256 amount,
        uint64 lockTime,
        bool relock,
        address account
    ) external;

    function relock(uint64 lockId, uint64 lockTime) external;

    function relock(uint64 lockTime) external;

    function relockMultiple(uint64[] calldata lockIds, uint64 lockTime) external;

    function totalBoosted() external view returns (uint256);

    function shutDown() external;

    function recoverToken(address token) external;

    function executeAvailableUnlocks() external returns (uint256);

    function executeAvailableUnlocksFor(address dst) external returns (uint256);

    function executeUnlocks(address dst, uint64[] calldata lockIds) external returns (uint256);

    // This will need to include the boosts etc.
    function balanceOf(address user) external view returns (uint256);

    function unlockableBalance(address user) external view returns (uint256);

    function unlockableBalanceBoosted(address user) external view returns (uint256);

    function kick(address user, uint64 lockId) external;

    function receiveFees(uint256 amountCrv, uint256 amountCvx) external;

    function claimableFees(address account)
        external
        view
        returns (uint256 claimableCrv, uint256 claimableCvx);

    function claimFees() external returns (uint256 crvAmount, uint256 cvxAmount);

    function computeBoost(uint128 lockTime) external view returns (uint128);

    function claimedAirdrop(address account) external view returns (bool);

    function totalVoteBoost(address account) external view returns (uint256);

    function totalRewardsBoost(address account) external view returns (uint256);

    function userLocks(address account) external view returns (VoteLock[] memory);
}

// File: node_modules/@openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: libraries/MerkleProof.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.20;

library MerkleProof {
    struct Proof {
        uint16 nodeIndex;
        bytes32[] hashes;
    }

    function isValid(
        Proof memory proof,
        bytes32 node,
        bytes32 merkleTorus
    ) internal pure returns (bool) {
        uint256 length = proof.hashes.length;
        uint16 nodeIndex = proof.nodeIndex;
        for (uint256 i = 0; i < length; i++) {
            if (nodeIndex % 2 == 0) {
                node = keccak256(abi.encodePacked(node, proof.hashes[i]));
            } else {
                node = keccak256(abi.encodePacked(proof.hashes[i], node));
            }
            nodeIndex /= 2;
        }

        return node == merkleTorus;
    }
}