// File: Context.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

/*
 * @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 GSN 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) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: Koku.sol



// SPDX-License-Identifier: unlicensed
// Solidity files have to start with this pragma.
// It will be used by the Solidity compiler to validate its version.
pragma solidity ^0.8.13;

//import "hardhat/console.sol";
import "./Ownable.sol";
import "./SafeMath.sol";

abstract contract ERC721 {
    // This doesn't have to match the real contract name. Call it what you like.
    function tokensOfOwner(address _owner) public view virtual returns (uint256[] memory);
    function ownerOf(uint256 tokenId) public view virtual returns (address);
}

contract Koku is Ownable {
    using SafeMath for uint256;

    /**
    * @dev Throws if called with any other non-contract added.
    */
    modifier onlyOwnedContracts(address _contract) {
        require(contracts[_contract], "The rewarded contract must be added");
        _;
    }

    bool private pause = false;

    mapping (address => bool) public contracts;
    mapping (address => uint256) public contractsRewardStart;
    mapping (address => uint256) public contractsRewardRate;
    mapping (address => uint256) public contractsRewardInterval;
    mapping (address => mapping (uint256 => uint256)) public contractsLastUpdated;

    event RewardPaid(address indexed user, uint256 reward);

    constructor()
    {
    }

    function claimContractsReward(address[] calldata _contracts) public  {
        require(!pause, "Rewards are paused");

        uint256 reward;
        uint256 timeStamp = block.timestamp;

        for(uint i; i < _contracts.length; i++)
        {
            (uint256[] memory tokens,uint256[] memory rewards) = getTokensAndClaimable(_contracts[i], msg.sender);
            for (uint256 j; j < tokens.length; j++)
            {
                reward += rewards[j];
                contractsLastUpdated[_contracts[i]][tokens[j]] = timeStamp;
            }
        }
        
        require(reward > 0, "None to claim");
        emit RewardPaid(msg.sender, reward);
    }

    function claimContractReward(address _contract) public onlyOwnedContracts(_contract) {
        require(!pause, "Rewards are paused");

        uint256 reward;
        uint256 timeStamp = block.timestamp;
        (uint256[] memory tokens,uint256[] memory rewards) = getTokensAndClaimable(_contract, msg.sender);

        for (uint256 i; i < tokens.length; i++) 
        {
            reward += rewards[i];
            contractsLastUpdated[_contract][tokens[i]] = timeStamp;
        }

        require(reward > 0, "None to claim");
        emit RewardPaid(msg.sender, reward);
    }

    function claimTokenReward(address _contract, uint256 _token) onlyOwnedContracts(_contract) public {
        require(!pause, "Rewards are paused");

        require(ERC721(_contract).ownerOf(_token) == msg.sender, "Wrong token owner");

        uint256 reward = getTokenClaimable(_contract, _token);
        contractsLastUpdated[_contract][_token] = block.timestamp;

        require(reward > 0, "None to claim");
        emit RewardPaid(msg.sender, reward);
    }
    
    function claimTokensReward(address _contract, uint256[] calldata _tokens) public onlyOwnedContracts(_contract){
        require(!pause, "Rewards are paused");
        
        uint256 total;
        uint256 reward;
        uint256 time = block.timestamp;
        
        for (uint256 i; i < _tokens.length; i++) 
        {
            require(ERC721(_contract).ownerOf(_tokens[i]) == msg.sender, "Not Owner");
            reward = getTokenClaimable(_contract, _tokens[i]);
            if (reward > 0)
            {
                total += reward;
                contractsLastUpdated[_contract][_tokens[i]] = time;
            }
        }
        require(total > 0, "None to claim");
        emit RewardPaid(msg.sender, total);
    }

    function getTokenClaimable( address _contract, uint256 _token) public view returns (uint256) 
    {       
        uint256 lastDate = (contractsLastUpdated[_contract][_token] > contractsRewardStart[_contract]) ? contractsLastUpdated[_contract][_token] : contractsRewardStart[_contract];
        uint256 rewardPeriods = (block.timestamp - lastDate) / contractsRewardInterval[_contract] * contractsRewardRate[_contract];
        return (rewardPeriods * contractsRewardRate[_contract]);
    }

    function getContractClaimable(address _contract, address _user) public view onlyOwnedContracts(_contract) returns (uint256) {

        uint256 time = block.timestamp;
        //Get Wallet of owner

        uint256[] memory wallet = ERC721(_contract).tokensOfOwner(_user);
        uint256 claimableRewards;

        for (uint256 i; i < wallet.length; i++) {
            if (contractsLastUpdated[_contract][wallet[i]] == 0) {
                claimableRewards += contractsRewardRate[_contract].mul(time.sub(contractsRewardStart[_contract])).div(contractsRewardInterval[_contract]);
            } else {
                claimableRewards += contractsRewardRate[_contract].mul(time.sub(contractsLastUpdated[_contract][wallet[i]])).div(contractsRewardInterval[_contract]);
            }
        }
        return claimableRewards;
    }

    function getContractsClaimable(address[] calldata _contracts, address _user) public view returns (uint256) {

        uint256 claimableRewards;
        for(uint i; i < _contracts.length; i++) {
            claimableRewards += getContractClaimable(_contracts[i], _user);
        }

        return claimableRewards;
    }
    
    function getTokensAndClaimable( address _contract, address _user ) public onlyOwnedContracts(_contract) view returns (uint256[] memory, uint256[] memory)
    {
        uint256 time = block.timestamp;
        uint256[] memory wallet = ERC721(_contract).tokensOfOwner(_user);
        uint256[] memory claimableRewards = new uint256[](wallet.length);

        for (uint256 i; i < wallet.length; i++) 
        {
            if (contractsLastUpdated[_contract][wallet[i]] == 0) {
                claimableRewards[i] = contractsRewardRate[_contract].mul(time.sub(contractsRewardStart[_contract])).div(contractsRewardInterval[_contract]);
            } else {
                claimableRewards[i] = contractsRewardRate[_contract].mul(time.sub(contractsLastUpdated[_contract][wallet[i]])).div(contractsRewardInterval[_contract]);
            }
        }

        return (wallet, claimableRewards);
    }

    function getContractStart( address _contract) public onlyOwnedContracts(_contract) view returns (uint256) 
    {
        return contractsRewardStart[_contract];
    }

    function getContractRate( address _contract) public onlyOwnedContracts(_contract) view returns (uint256) 
    {
        return contractsRewardRate[_contract];
    }
   
    function getContractInterval( address _contract) public onlyOwnedContracts(_contract) view returns (uint256) 
    {
        return contractsRewardInterval[_contract];
    }
 
    function setContract( address _contract, uint256 _start, uint256 _rate, uint256 _interval) public onlyOwner
    {
        contracts[_contract] = true;
        contractsRewardStart[_contract] = _start; //ex. 1651795200 May 6, 2022 12:00:00
        contractsRewardRate[_contract] = _rate; //ex. 1 = 1 koku
        contractsRewardInterval[_contract] = _interval; //86400 = 1 day
    }
     
    function clearContract( address _contract) public onlyOwner
    {
        contracts[_contract] = false;
    }

    function setContractRewardStart(address _contract, uint256 _start) public onlyOwner onlyOwnedContracts(_contract) {
        //ex. 1651795200 May 6, 2022 12:00:00
        contractsRewardStart[_contract] = _start;
    }
    
    function setContractRewardRate(address _contract, uint256 _rate) public onlyOwner onlyOwnedContracts(_contract) {
        //ex. 1 = 1 koku
        contractsRewardRate[_contract] = _rate;
    }
        
    function setContractRewardInterval(address _contract, uint256 _interval) public onlyOwner onlyOwnedContracts(_contract) {
        //86400 = 1 day
        contractsRewardInterval[_contract] = _interval;
    }

    function setRewardsPause(bool _pause) public onlyOwner {
        pause = _pause;
    }
}
// File: Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.13;

import "./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 Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        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: SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}