// File: contracts/EmissionControllerKeeper.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { KeeperCompatibleInterface } from "./interfaces/KeeperCompatibleInterface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IGaugeVoterV2 } from "./interfaces/IGaugeVoterV2.sol";
import { IEmissionController } from "./interfaces/IEmissionController.sol";
import { IRegistry } from "./interfaces/IRegistry.sol";

/**
 * @dev This keeper contract rewards the caller with MAHA and distributes maha emissions
 * to the various gauges every week.
 */
contract EmissionControllerKeeper is Ownable, KeeperCompatibleInterface {
  IRegistry public registry;
  uint256 public mahaRewardPerEpoch;

  constructor(IRegistry _registry, uint256 _mahaRewardPerEpoch) {
    registry = _registry;
    mahaRewardPerEpoch = _mahaRewardPerEpoch;
  }

  function updateMahaReward(uint256 reward) external onlyOwner {
    mahaRewardPerEpoch = reward;
  }

  function nextUpkeepTime() external view returns (uint256) {
    return IEmissionController(registry.emissionController()).nextEpochPoint();
  }

  function checkUpkeep(bytes calldata)
    external
    view
    override
    returns (bool, bytes memory)
  {
    bool upkeepNeeded;
    if (IEmissionController(registry.emissionController()).callable())
      upkeepNeeded = true;
    else upkeepNeeded = false;
    return (upkeepNeeded, "");
  }

  function performUpkeep(bytes calldata performData) external override {
    IEmissionController(registry.emissionController()).allocateEmission();
    IGaugeVoterV2(registry.gaugeVoter()).distribute();

    // if the keeper wants a maha reward, we provide it with one; usually
    // non-chainlink keepers would ask for a MAHA reward
    if (performData.length > 0) {
      uint256 flag = abi.decode(performData, (uint256));
      if (flag >= 1) {
        require(
          IERC20(registry.maha()).balanceOf(address(this)) >=
            mahaRewardPerEpoch,
          "not enough maha for rewards"
        );
        IERC20(registry.maha()).transfer(msg.sender, mahaRewardPerEpoch);
      }
    }
  }
}

// File: contracts/interfaces/KeeperCompatibleInterface.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface KeeperCompatibleInterface {
    /**
     * @notice method that is simulated by the keepers to see if any work actually
     * needs to be performed. This method does does not actually need to be
     * executable, and since it is only ever simulated it can consume lots of gas.
     * @dev To ensure that it is never called, you may want to add the
     * cannotExecute modifier from KeeperBase to your implementation of this
     * method.
     * @param checkData specified in the upkeep registration so it is always the
     * same for a registered upkeep. This can easily be broken down into specific
     * arguments using `abi.decode`, so multiple upkeeps can be registered on the
     * same contract and easily differentiated by the contract.
     * @return upkeepNeeded boolean to indicate whether the keeper should call
     * performUpkeep or not.
     * @return performData bytes that the keeper should call performUpkeep with, if
     * upkeep is needed. If you would like to encode data to decode later, try
     * `abi.encode`.
     */
    function checkUpkeep(bytes calldata checkData)
        external
        returns (bool upkeepNeeded, bytes memory performData);

    /**
     * @notice method that is actually executed by the keepers, via the registry.
     * The data returned by the checkUpkeep simulation will be passed into
     * this method to actually be executed.
     * @dev The input to this method should not be trusted, and the caller of the
     * method should not even be restricted to any single registry. Anyone should
     * be able call it, and the input should be validated, there is no guarantee
     * that the data passed in is the performData returned from checkUpkeep. This
     * could happen due to malicious keepers, racing keepers, or simply a state
     * change while the performUpkeep transaction is waiting for confirmation.
     * Always validate the data passed in.
     * @param performData is the data which was passed back from the checkData
     * simulation. If it is encoded, it can easily be decoded into other types by
     * calling `abi.decode`. This data should not be trusted, and should be
     * validated against the contract's current state.
     */
    function performUpkeep(bytes calldata performData) external;
}

// File: contracts/interfaces/IGaugeVoterV2.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IGaugeVoterV2 {
  function attachStakerToGauge(address account) external;

  function detachStakerFromGauge(address account) external;

  function distribute(address _gauge) external;

  function distribute() external;

  function distribute(address[] memory _gauges) external;

  function reset() external;

  function resetFor(address _who) external;

  function notifyRewardAmount(uint256 amount) external;

  function attachments(address who) external view returns (uint256);

  event GaugeCreated(
    address indexed gauge,
    address creator,
    address indexed bribe,
    address indexed pool
  );
  event GaugeUpdated(
    address indexed gauge,
    address creator,
    address indexed bribe,
    address indexed pool
  );
  event Voted(address indexed voter, address tokenId, int256 weight);
  event Abstained(address tokenId, int256 weight);
  event Deposit(address indexed lp, address indexed gauge, uint256 amount);
  event Withdraw(address indexed lp, address indexed gauge, uint256 amount);
  event NotifyReward(
    address indexed sender,
    address indexed reward,
    uint256 amount
  );
  event DistributeReward(
    address indexed sender,
    address indexed gauge,
    uint256 amount
  );
  event Attach(address indexed owner, address indexed gauge);
  event Detach(address indexed owner, address indexed gauge);
  event Whitelisted(
    address indexed whitelister,
    address indexed token,
    bool value
  );
}

// File: contracts/interfaces/IEmissionController.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {IEpoch} from "./IEpoch.sol";

interface IEmissionController is IEpoch {
    function allocateEmission() external;
}

// File: contracts/interfaces/IRegistry.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IRegistry {
  event MahaChanged(address indexed whom, address _old, address _new);
  event VoterChanged(address indexed whom, address _old, address _new);
  event LockerChanged(address indexed whom, address _old, address _new);
  event GovernorChanged(address indexed whom, address _old, address _new);
  event StakerChanged(address indexed whom, address _old, address _new);
  event EmissionControllerChanged(
    address indexed whom,
    address _old,
    address _new
  );

  function maha() external view returns (address);

  function gaugeVoter() external view returns (address);

  function locker() external view returns (address);

  function staker() external view returns (address);

  function emissionController() external view returns (address);

  function governor() external view returns (address);

  function getAllAddresses()
    external
    view
    returns (
      address,
      address,
      address,
      address,
      address
    );

  function ensureNotPaused() external;

  function setMAHA(address _new) external;

  function setEmissionController(address _new) external;

  function setStaker(address _new) external;

  function setVoter(address _new) external;

  function setLocker(address _new) external;

  function setGovernor(address _new) external;
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// File: contracts/interfaces/IEpoch.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IEpoch {
    function callable() external view returns (bool);

    function getLastEpoch() external view returns (uint256);

    function getCurrentEpoch() external view returns (uint256);

    function getNextEpoch() external view returns (uint256);

    function nextEpochPoint() external view returns (uint256);

    function getPeriod() external view returns (uint256);

    function getStartTime() external view returns (uint256);
}

// File: @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;
    }
}