// File: src/PaymentHelper.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.20;

import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";
import {IPaymentSplitter} from "./IPaymentSplitter.sol";

struct TokenPayment {
    address token;
    uint256 amount;
}

interface ICollectionPaymentReader {
    function paymentSplitter() external view returns (IPaymentSplitter);
    function paymentSplitterRoyalties() external view returns (IPaymentSplitter);
}

/**
 * @notice Helper functions for claiming payments.
 * @dev This is intentionally agnostic from Alba and should be independently replaceable
 * for another solution later if needed.
 */
contract PaymentHelper {
    event PaymentsClaimed(address indexed collection, address user);

    /**
     * @notice Returns the payment splitters for a collection.
     */
    function splittersForCollection(address collection) internal view returns (IPaymentSplitter, IPaymentSplitter) {
        IPaymentSplitter paymentSplitter = ICollectionPaymentReader(collection).paymentSplitter();
        IPaymentSplitter paymentSplitterRoyalties = ICollectionPaymentReader(collection).paymentSplitterRoyalties();

        return (paymentSplitter, paymentSplitterRoyalties);
    }

    /**
     * @notice Returns the amount of ETH that can be claimed by the caller for a collection.
     * @return (primaryEth, secondaryEth) amounts.
     */
    function availableETH(address collection) public view returns (uint256, uint256) {
        (IPaymentSplitter paymentSplitter, IPaymentSplitter paymentSplitterRoyalties) =
            splittersForCollection(collection);

        uint256 available = paymentSplitter.releasable(msg.sender);
        uint256 availableRoyalties = 0;
        if (address(paymentSplitterRoyalties) != address(0)) {
            availableRoyalties = paymentSplitterRoyalties.releasable(msg.sender);
        }
        return (available, availableRoyalties);
    }

    /**
     * @notice Returns the amount of payments that can be claimed by the user.
     * @dev The uses msg.sender so can be called by the artist or by Alba.
     */
    function availableERC20(address collection, address[] calldata primaryTokens, address[] calldata secondaryTokens)
        public
        view
        returns (TokenPayment[] memory, TokenPayment[] memory)
    {
        TokenPayment[] memory primaryAmounts = new TokenPayment[](primaryTokens.length);
        TokenPayment[] memory secondaryAmounts = new TokenPayment[](secondaryTokens.length);

        if (primaryTokens.length == 0 && secondaryTokens.length == 0) {
            return (primaryAmounts, secondaryAmounts);
        }

        (IPaymentSplitter paymentSplitter, IPaymentSplitter paymentSplitterRoyalties) =
            splittersForCollection(collection);

        for (uint256 i = 0; i < primaryTokens.length; i++) {
            primaryAmounts[i] =
                TokenPayment(primaryTokens[i], paymentSplitter.releasable(IERC20(primaryTokens[i]), msg.sender));
        }

        for (uint256 i = 0; i < secondaryTokens.length; i++) {
            secondaryAmounts[i] = TokenPayment(
                secondaryTokens[i], paymentSplitterRoyalties.releasable(IERC20(secondaryTokens[i]), msg.sender)
            );
        }

        return (primaryAmounts, secondaryAmounts);
    }

    /**
     * @notice Convenience function to claim all payments for a collection.
     */
    function claimPayments(address collection, address[] calldata primaryTokens, address[] calldata secondaryTokens)
        external
    {
        _claimPayments(collection, primaryTokens, secondaryTokens);
    }

    /**
     * @notice Convenience function to claim all payments for multiple collections.
     * @dev To reduce gas, don't pass token addresses if there is no available balance for that token.
     */
    function claimPaymentsBatch(
        address[] calldata collections,
        address[][] calldata primaryTokens,
        address[][] calldata secondaryTokens
    ) external {
        uint256 numCollections = collections.length;
        for (uint256 i = 0; i < numCollections; i++) {
            _claimPayments(collections[i], primaryTokens[i], secondaryTokens[i]);
        }
    }

    /**
     * @notice Convenience function to claim all payments for a collection.
     * @dev This can be used by both the artist and Alba to claim their payments.
     * When upgraded to 4.8.X, we can use the `releasable` function to check payments
     * for the specific caller rather than just checking the balance.
     * Note that we don't authz as that is done by the splitters directly.
     * TODO: We can make this more gas efficient by passing flags for which splitter to claim, and doing the
     * available calls off-chain.
     */
    function _claimPayments(address collection, address[] calldata primaryTokens, address[] calldata secondaryTokens)
        internal
    {
        (IPaymentSplitter paymentSplitter, IPaymentSplitter paymentSplitterRoyalties) =
            splittersForCollection(collection);
        bool claimed = false;

        // Claim ETH payments.
        (uint256 ethPrimary, uint256 ethSecondary) = availableETH(collection);
        if (ethPrimary > 0) {
            paymentSplitter.release(payable(msg.sender));
            claimed = true;
        }
        if (ethSecondary > 0) {
            paymentSplitterRoyalties.release(payable(msg.sender));
            claimed = true;
        }

        // Claim ERC20 payments if given.
        if (primaryTokens.length != 0 || secondaryTokens.length != 0) {
            (TokenPayment[] memory primaryTokenAmounts, TokenPayment[] memory secondaryTokenAmounts) =
                availableERC20(collection, primaryTokens, secondaryTokens);

            uint256 numPrimaryTokens = primaryTokenAmounts.length;
            for (uint256 i = 0; i < numPrimaryTokens; i++) {
                if (primaryTokenAmounts[i].amount > 0) {
                    paymentSplitter.release(IERC20(primaryTokenAmounts[i].token), payable(msg.sender));
                    claimed = true;
                }
            }

            uint256 numSecondaryTokens = secondaryTokenAmounts.length;
            for (uint256 i = 0; i < numSecondaryTokens; i++) {
                if (secondaryTokenAmounts[i].amount > 0) {
                    paymentSplitterRoyalties.release(IERC20(secondaryTokenAmounts[i].token), payable(msg.sender));
                    claimed = true;
                }
            }
        }

        if (claimed) {
            emit PaymentsClaimed(collection, msg.sender);
        }
    }
}

// File: lib/openzeppelin-contracts/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: src/IPaymentSplitter.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.13;

import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";

interface IPaymentSplitter {
    function releasable(address account) external view returns (uint256);
    function releasable(IERC20 token, address account) external view returns (uint256);

    function release(address payable account) external;
    function release(IERC20 token, address account) external;
}