// File: contracts/Album.sol



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

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

import "./AlbumBuyoutManager.sol";
import "./AlbumNftManager.sol";
import "./AlbumTokenSaleManager.sol";

contract Album is
    Ownable,
    ERC721Holder,
    AlbumBuyoutManager,
    AlbumNftManager,
    AlbumTokenSaleManager
{
    // The token for this album.
    IERC20 public token;

    constructor(
        address governance,
        address _token,
        address creator,
        TokenSaleParams memory tokenSaleParams,
        address[] memory _nftAddrs,
        uint256[] memory _nftIds,
        uint256 _minReservePrice
    ) AlbumTokenSaleManager(creator, tokenSaleParams) {
        transferOwnership(governance);
        token = IERC20(_token);
        _addNfts(_nftAddrs, _nftIds);
        _setMinReservePrice(_minReservePrice);
    }

    function addNfts(address[] memory _nfts, uint256[] memory _ids)
        public
        onlyOwner
    {
        _addNfts(_nfts, _ids);
    }

    function sendNfts(address to, uint256[] memory idxs) public onlyOwner {
        _sendNfts(to, idxs);
    }

    function setTimeout(uint256 _timeout) public onlyOwner {
        _setTimeout(_timeout);
    }

    function sendAllToSender() internal override {
        address[] memory nfts = getNfts();
        uint256[] memory ids = getIds();
        bool[] memory sent = getSent();
        for (uint256 i = 0; i < nfts.length; i++) {
            if (!sent[i]) {
                IERC721(nfts[i]).safeTransferFrom(
                    address(this),
                    msg.sender,
                    ids[i]
                );
            }
        }
    }

    function setMinReservePrice(uint256 _minReservePrice) public onlyOwner {
        _setMinReservePrice(_minReservePrice);
    }

    function setBuyout(address _buyer, uint256 _cost) public onlyOwner {
        _setBuyout(_buyer, _cost);
    }

    function checkOwedAmount(uint256 _amount, uint256 buyoutCost)
        internal
        override
        returns (uint256 owed)
    {
        token.transferFrom(msg.sender, address(this), _amount);
        owed = (_amount * buyoutCost) / token.totalSupply();
    }

    function getToken() public view override returns (IERC20) {
        return token;
    }
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

// File: @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address,
        address,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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 `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @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);
}

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



// SPDX-License-Identifier: MIT

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() {
        _setOwner(_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 {
        _setOwner(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");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: contracts/AlbumBuyoutManager.sol



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

abstract contract AlbumBuyoutManager {
    event BuyoutSet(address buyer, uint256 cost, uint256 end);
    event Buyout(address buyer, uint256 cost);
    event BuyoutPortionClaimed(address claimer, uint256 amount, uint256 owed);
    event MinReservePriceSet(uint256 minReservePrice);

    address private buyer;
    uint256 private buyoutCost;
    uint256 private buyoutEnd;
    bool private bought;
    uint256 private minReservePrice;
    // Initialized to 7 days in seconds
    uint256 private timeout = 60 * 60 * 24 * 7;

    function sendAllToSender() internal virtual;

    function checkOwedAmount(uint256 _amount, uint256 _buyoutCost)
        internal
        virtual
        returns (uint256 owed);

    // Requires no completed or ongoing buyout.
    modifier noBuyout() {
        require(!bought, "A buyout was already completed");
        require(
            block.timestamp >= buyoutEnd || buyer == address(0),
            "A buyout is in progress"
        );
        _;
    }

    function getBuyoutData()
        public
        view
        returns (
            address _buyer,
            uint256 _buyoutCost,
            uint256 _buyoutEnd,
            bool _bought,
            uint256 _timeout,
            uint256 _minReservePrice
        )
    {
        return (buyer, buyoutCost, buyoutEnd, bought, timeout, minReservePrice);
    }

    function _setTimeout(uint256 _timeout) internal {
        timeout = _timeout;
    }

    function _setMinReservePrice(uint256 _minReservePrice) internal {
        minReservePrice = _minReservePrice;
        emit MinReservePriceSet(_minReservePrice);
    }

    function _setBuyout(address _buyer, uint256 _cost) internal noBuyout {
        require(
            _cost >= minReservePrice,
            "Album can't be bought out for amount less than minReservePrice!"
        );
        buyer = _buyer;
        buyoutCost = _cost;
        buyoutEnd = block.timestamp + timeout;
        emit BuyoutSet(buyer, buyoutCost, buyoutEnd);
    }

    function buyout() public payable {
        require(!bought, "Album has already been bought out");
        require(msg.sender == buyer, "Caller is not the buyer.");
        require(msg.value == buyoutCost, "Not enough ETH.");
        require(block.timestamp < buyoutEnd, "Buyout timeout already passed.");
        sendAllToSender();
        bought = true;
        emit Buyout(buyer, buyoutCost);
    }

    function claim(uint256 _amount) public {
        require(bought, "No buyout yet.");
        uint256 owed = checkOwedAmount(_amount, buyoutCost);
        payable(msg.sender).transfer(owed);
        emit BuyoutPortionClaimed(msg.sender, _amount, owed);
    }
}

// File: contracts/AlbumNftManager.sol



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

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

abstract contract AlbumNftManager {
    event AddNfts(address[] nfts, uint256[] ids);
    event SendNfts(address to, uint256[] idxs);

    // NFTs owned by this album.
    address[] private nfts;
    uint256[] private ids;
    bool[] private sent;

    function getNfts() public view returns (address[] memory) {
        return nfts;
    }

    function getIds() public view returns (uint256[] memory) {
        return ids;
    }

    function getSent() public view returns (bool[] memory) {
        return sent;
    }

    function _addNfts(address[] memory _nfts, uint256[] memory _ids) internal {
        require(
            _nfts.length == _ids.length,
            "Input array lenghts don't match."
        );
        for (uint256 i = 0; i < _nfts.length; i++) {
            address nftAddr = _nfts[i];
            IERC721 nft = IERC721(nftAddr);
            uint256 id = _ids[i];
            address owner = nft.ownerOf(id);
            if (owner != address(this)) {
                nft.safeTransferFrom(owner, address(this), id);
            }
            nfts.push(nftAddr);
            ids.push(id);
            sent.push(false);
        }
        emit AddNfts(_nfts, _ids);
    }

    function _sendNfts(address to, uint256[] memory idxs) internal {
        uint256 idx;
        for (uint256 i = 0; i < idxs.length; i++) {
            idx = idxs[i];
            IERC721(nfts[idx]).safeTransferFrom(address(this), to, ids[idx]);
            sent[idx] = true;
        }
        emit SendNfts(to, idxs);
    }
}

// File: contracts/AlbumTokenSaleManager.sol



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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

abstract contract AlbumTokenSaleManager {
    event SaleInitialized(
        address creator,
        uint256 tokensPerMilliEth,
        uint256 saleStart,
        uint256 saleEnd,
        uint256 numTokens
    );
    event TokenSale(address buyer, uint256 amount, uint256 paid);
    event SaleSwept(uint256 saleProceeds, uint256 amountUnsold);

    uint256 public constant MILLIETH = 1e15;

    address public immutable CREATOR;
    // Number of tokens to sell per wei (1e-18 ETH)
    uint256 public immutable TOKENS_PER_WEI;
    uint256 public immutable SALE_START;
    uint256 public immutable SALE_END;

    uint256 private saleProceeds;
    uint256 private amountUnsold;
    bool private swept;

    modifier saleOver(bool want) {
        bool isOver = block.timestamp >= SALE_END;
        require(want == isOver, "Sale state is invalid for this method");
        _;
    }

    struct TokenSaleParams {
        uint256 price;
        uint256 saleStart;
        uint256 saleEnd;
        uint256 numTokens;
    }

    constructor(address creator, TokenSaleParams memory params) {
        require(params.saleStart < params.saleEnd);
        CREATOR = creator;
        TOKENS_PER_WEI = params.price;
        SALE_START = params.saleStart;
        SALE_END = params.saleEnd;
        amountUnsold = params.numTokens;
        emit SaleInitialized(
            creator,
            params.price,
            params.saleStart,
            params.saleEnd,
            params.numTokens
        );
    }

    function getToken() public view virtual returns (IERC20 token);

    function buyTokens() public payable saleOver(false) {
        require(block.timestamp >= SALE_START, "Sale has not started yet");
        uint256 amount = msg.value * TOKENS_PER_WEI;
        require(amountUnsold >= amount, "Attempted to purchase too many tokens!");
        amountUnsold -= amount;
        getToken().transfer(msg.sender, amount);
        saleProceeds += msg.value;
        emit TokenSale(msg.sender, amount, msg.value);
    }

    // Anyone can trigger a sweep, but the proceeds always get sent to the creator.
    function sweepProceeds() public saleOver(true) {
        require(!swept, "Already swept");
        swept = true;
        payable(CREATOR).transfer(saleProceeds);
        getToken().transfer(CREATOR, amountUnsold);
        emit SaleSwept(saleProceeds, amountUnsold);
    }

    function getTokenSaleData()
        public
        view
        returns (
            address creator,
            uint256 tokensPerWei,
            uint256 saleStart,
            uint256 saleEnd,
            uint256 _saleProceeds,
            uint256 _amountUnsold,
            bool _swept
        )
    {
        return (
            CREATOR,
            TOKENS_PER_WEI,
            SALE_START,
            SALE_END,
            saleProceeds,
            amountUnsold,
            swept
        );
    }
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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



// SPDX-License-Identifier: MIT

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;
    }
}