// File: @chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol



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

interface VRFCoordinatorV2Interface {
  /**
   * @notice Get configuration relevant for making requests
   * @return minimumRequestConfirmations global min for request confirmations
   * @return maxGasLimit global max for request gas limit
   * @return s_provingKeyHashes list of registered key hashes
   */
  function getRequestConfig()
    external
    view
    returns (
      uint16,
      uint32,
      bytes32[] memory
    );

  /**
   * @notice Request a set of random words.
   * @param keyHash - Corresponds to a particular oracle job which uses
   * that key for generating the VRF proof. Different keyHash's have different gas price
   * ceilings, so you can select a specific one to bound your maximum per request cost.
   * @param subId  - The ID of the VRF subscription. Must be funded
   * with the minimum subscription balance required for the selected keyHash.
   * @param minimumRequestConfirmations - How many blocks you'd like the
   * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
   * for why you may want to request more. The acceptable range is
   * [minimumRequestBlockConfirmations, 200].
   * @param callbackGasLimit - How much gas you'd like to receive in your
   * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
   * may be slightly less than this amount because of gas used calling the function
   * (argument decoding etc.), so you may need to request slightly more than you expect
   * to have inside fulfillRandomWords. The acceptable range is
   * [0, maxGasLimit]
   * @param numWords - The number of uint256 random values you'd like to receive
   * in your fulfillRandomWords callback. Note these numbers are expanded in a
   * secure way by the VRFCoordinator from a single random value supplied by the oracle.
   * @return requestId - A unique identifier of the request. Can be used to match
   * a request to a response in fulfillRandomWords.
   */
  function requestRandomWords(
    bytes32 keyHash,
    uint64 subId,
    uint16 minimumRequestConfirmations,
    uint32 callbackGasLimit,
    uint32 numWords
  ) external returns (uint256 requestId);

  /**
   * @notice Create a VRF subscription.
   * @return subId - A unique subscription id.
   * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
   * @dev Note to fund the subscription, use transferAndCall. For example
   * @dev  LINKTOKEN.transferAndCall(
   * @dev    address(COORDINATOR),
   * @dev    amount,
   * @dev    abi.encode(subId));
   */
  function createSubscription() external returns (uint64 subId);

  /**
   * @notice Get a VRF subscription.
   * @param subId - ID of the subscription
   * @return balance - LINK balance of the subscription in juels.
   * @return reqCount - number of requests for this subscription, determines fee tier.
   * @return owner - owner of the subscription.
   * @return consumers - list of consumer address which are able to use this subscription.
   */
  function getSubscription(uint64 subId)
    external
    view
    returns (
      uint96 balance,
      uint64 reqCount,
      address owner,
      address[] memory consumers
    );

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @param newOwner - proposed new owner of the subscription
   */
  function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @dev will revert if original owner of subId has
   * not requested that msg.sender become the new owner.
   */
  function acceptSubscriptionOwnerTransfer(uint64 subId) external;

  /**
   * @notice Add a consumer to a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - New consumer which can use the subscription
   */
  function addConsumer(uint64 subId, address consumer) external;

  /**
   * @notice Remove a consumer from a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - Consumer to remove from the subscription
   */
  function removeConsumer(uint64 subId, address consumer) external;

  /**
   * @notice Cancel a subscription
   * @param subId - ID of the subscription
   * @param to - Where to send the remaining LINK to
   */
  function cancelSubscription(uint64 subId, address to) external;

  /*
   * @notice Check to see if there exists a request commitment consumers
   * for all consumers and keyhashes for a given sub.
   * @param subId - ID of the subscription
   * @return true if there exists at least one unfulfilled request for the subscription, false
   * otherwise.
   */
  function pendingRequestExists(uint64 subId) external view returns (bool);
}

// File: @chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol



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

/** ****************************************************************************
 * @notice Interface for contracts using VRF randomness
 * *****************************************************************************
 * @dev PURPOSE
 *
 * @dev Reggie the Random Oracle (not his real job) wants to provide randomness
 * @dev to Vera the verifier in such a way that Vera can be sure he's not
 * @dev making his output up to suit himself. Reggie provides Vera a public key
 * @dev to which he knows the secret key. Each time Vera provides a seed to
 * @dev Reggie, he gives back a value which is computed completely
 * @dev deterministically from the seed and the secret key.
 *
 * @dev Reggie provides a proof by which Vera can verify that the output was
 * @dev correctly computed once Reggie tells it to her, but without that proof,
 * @dev the output is indistinguishable to her from a uniform random sample
 * @dev from the output space.
 *
 * @dev The purpose of this contract is to make it easy for unrelated contracts
 * @dev to talk to Vera the verifier about the work Reggie is doing, to provide
 * @dev simple access to a verifiable source of randomness. It ensures 2 things:
 * @dev 1. The fulfillment came from the VRFCoordinator
 * @dev 2. The consumer contract implements fulfillRandomWords.
 * *****************************************************************************
 * @dev USAGE
 *
 * @dev Calling contracts must inherit from VRFConsumerBase, and can
 * @dev initialize VRFConsumerBase's attributes in their constructor as
 * @dev shown:
 *
 * @dev   contract VRFConsumer {
 * @dev     constructor(<other arguments>, address _vrfCoordinator, address _link)
 * @dev       VRFConsumerBase(_vrfCoordinator) public {
 * @dev         <initialization with other arguments goes here>
 * @dev       }
 * @dev   }
 *
 * @dev The oracle will have given you an ID for the VRF keypair they have
 * @dev committed to (let's call it keyHash). Create subscription, fund it
 * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
 * @dev subscription management functions).
 * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
 * @dev callbackGasLimit, numWords),
 * @dev see (VRFCoordinatorInterface for a description of the arguments).
 *
 * @dev Once the VRFCoordinator has received and validated the oracle's response
 * @dev to your request, it will call your contract's fulfillRandomWords method.
 *
 * @dev The randomness argument to fulfillRandomWords is a set of random words
 * @dev generated from your requestId and the blockHash of the request.
 *
 * @dev If your contract could have concurrent requests open, you can use the
 * @dev requestId returned from requestRandomWords to track which response is associated
 * @dev with which randomness request.
 * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
 * @dev if your contract could have multiple requests in flight simultaneously.
 *
 * @dev Colliding `requestId`s are cryptographically impossible as long as seeds
 * @dev differ.
 *
 * *****************************************************************************
 * @dev SECURITY CONSIDERATIONS
 *
 * @dev A method with the ability to call your fulfillRandomness method directly
 * @dev could spoof a VRF response with any random value, so it's critical that
 * @dev it cannot be directly called by anything other than this base contract
 * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
 *
 * @dev For your users to trust that your contract's random behavior is free
 * @dev from malicious interference, it's best if you can write it so that all
 * @dev behaviors implied by a VRF response are executed *during* your
 * @dev fulfillRandomness method. If your contract must store the response (or
 * @dev anything derived from it) and use it later, you must ensure that any
 * @dev user-significant behavior which depends on that stored value cannot be
 * @dev manipulated by a subsequent VRF request.
 *
 * @dev Similarly, both miners and the VRF oracle itself have some influence
 * @dev over the order in which VRF responses appear on the blockchain, so if
 * @dev your contract could have multiple VRF requests in flight simultaneously,
 * @dev you must ensure that the order in which the VRF responses arrive cannot
 * @dev be used to manipulate your contract's user-significant behavior.
 *
 * @dev Since the block hash of the block which contains the requestRandomness
 * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
 * @dev miner could, in principle, fork the blockchain to evict the block
 * @dev containing the request, forcing the request to be included in a
 * @dev different block with a different hash, and therefore a different input
 * @dev to the VRF. However, such an attack would incur a substantial economic
 * @dev cost. This cost scales with the number of blocks the VRF oracle waits
 * @dev until it calls responds to a request. It is for this reason that
 * @dev that you can signal to an oracle you'd like them to wait longer before
 * @dev responding to the request (however this is not enforced in the contract
 * @dev and so remains effective only in the case of unmodified oracle software).
 */
abstract contract VRFConsumerBaseV2 {
  error OnlyCoordinatorCanFulfill(address have, address want);
  address private immutable vrfCoordinator;

  /**
   * @param _vrfCoordinator address of VRFCoordinator contract
   */
  constructor(address _vrfCoordinator) {
    vrfCoordinator = _vrfCoordinator;
  }

  /**
   * @notice fulfillRandomness handles the VRF response. Your contract must
   * @notice implement it. See "SECURITY CONSIDERATIONS" above for important
   * @notice principles to keep in mind when implementing your fulfillRandomness
   * @notice method.
   *
   * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
   * @dev signature, and will call it once it has verified the proof
   * @dev associated with the randomness. (It is triggered via a call to
   * @dev rawFulfillRandomness, below.)
   *
   * @param requestId The Id initially returned by requestRandomness
   * @param randomWords the VRF output expanded to the requested number of words
   */
  function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;

  // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
  // proof. rawFulfillRandomness then calls fulfillRandomness, after validating
  // the origin of the call
  function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
    if (msg.sender != vrfCoordinator) {
      revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
    }
    fulfillRandomWords(requestId, randomWords);
  }
}

// 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/interfaces/IERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol)

pragma solidity ^0.8.0;

import "../token/ERC1155/IERC1155.sol";

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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;
    }
}

// File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

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

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



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

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: contracts/shop/interface/IProductComicV2.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

interface IProductComic {
    error InvalidWeights();
    error TotalSupplyOverMaxSupply();
    error ParamLengthMissMatch();
    error InvalidInvoker();
    error SupplyOverflow();
    error CardBackSUpplyOverflow();
    error EmptyRequestFulfillment();
    error RequestAlreadyFulfilled();

    event SubscriptionIdSet(uint64 subscriptionId);
    event KeyHashSet(bytes32 keyHash);
    event VrfCoordinatorSet(address vrfCoordinator);
    event PullFromAddressSet(address pullFromAddress);
    event ComicAddressSet(address comicAddress);
    event ShardAddressSet(address shardAddress);
    event ParallelAlphaAddressSet(address parallelAlphaAddress);
    event ShopContractSet(address shopAddress);
    event ComicSupplySet(uint256[2] comicTokenIds, uint256[2] comicSupply);
    event CardBackSupplySet(
        uint256[] cardBackTokenIds,
        uint256[] cardBackSupply
    );
    event CardBackDisabledSet(bool isCardBackDisabled);

    event ComicPurchased(
        address to,
        uint256 amount,
        uint256 requestId,
        uint256 transactionId
    );
    event RequestRecovered(
        address to,
        uint256 amount,
        uint256 requestId,
        uint256 transactionId
    );

    event ComicTransferred(
        address to,
        uint256 amount,
        uint256 requestId,
        uint256 transactionId,
        uint256[] comicTokenId,
        uint256[] cardBackTokenIds
    );
}

// File: contracts/shop/libraries/ProductComicLib.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

library ProductComicLib {
    /// @notice Keeps track of comic purchase to be updated upon VRF fullfil call
    struct Request {
        address owner;
        bool isAssigned;
        uint256 numComicsToSend;
        uint256 transactionId;
    }
}

// File: contracts/shop/ProductComicV2.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

import { IERC1155 } from "@openzeppelin/contracts/interfaces/IERC1155.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { VRFCoordinatorV2Interface } from "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import { VRFConsumerBaseV2 } from "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import { ProductComicLib } from "./libraries/ProductComicLib.sol";
import { IProductComic } from "./interface/IProductComicV2.sol";

contract ProductComicV2 is
    VRFConsumerBaseV2,
    Ownable,
    IProductComic,
    ReentrancyGuard
{
    // Chainlink Parameters
    VRFCoordinatorV2Interface public vrfCoordinator;
    uint64 public subscriptionId;
    bytes32 public keyHash;
    uint32 public callbackGasLimit = 2000000;
    uint32 public numWords = 1;
    uint16 public requestConfirmations = 3;

    // Pull from address for different NFTs (comics, hoodies, etc)
    address public pullFromAddress = 0x716E6b6873038a8243F5EB44e2b09D85DEFf45Ec;

    address public comicAddress = 0x6A82872743217A0988E4d72975D74432CfDeF9D7;
    address public parallelAlphaAddress =
        0x76BE3b62873462d2142405439777e971754E8E77;

    address public shopAddress = 0xd32034B5502910e5B56f5AC94ACb4198315c2Da2;

    uint256 public comicSupplyRemaining;
    uint256 public cardBackSupplyRemaining;
    uint256 public numRequestsRemaining;

    uint256[] public comicTokenIds;
    uint256[] public cardBackTokenIds;

    bool public isCardBackDisabled;

    mapping(uint256 => ProductComicLib.Request) public vrfRequestIdToRequest;
    mapping(uint256 => uint256) public comicMaxSupply;
    mapping(uint256 => uint256) public comicPurchased;
    mapping(uint256 => uint256) public cardBackMaxSupply;
    mapping(uint256 => uint256) public cardBackPurchased;

    constructor(
        uint64 _subscriptionId,
        address _coordinator,
        bytes32 _keyHash
    ) VRFConsumerBaseV2(_coordinator) {
        // Chainlink Addresses Doc: https://docs.chain.link/docs/vrf-contracts/#ethereum-mainnet
        // Ethereum Mainnet
        // VRF Coordinator 0x271682DEB8C4E0901D1a1550aD2e64D568E69909
        // Key Hash 200 GWei 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef
        // Key Hash 500 GWei 0xff8dedfbfa60af186cf3c830acbc32c05aae823045ae5ea7da1e45fbfaba4f92
        // Key Hash 1000 GWei 0x9fe0eebf5e446e3c998ec9bb19951541aee00bb90ea201ae456421a2ded86805
        // Goerli testnet
        // VRF Coordinator 0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D
        // Key Hash 0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15
        vrfCoordinator = VRFCoordinatorV2Interface(_coordinator);
        subscriptionId = _subscriptionId;
        keyHash = _keyHash;
    }

    /**
     * @notice Updates subscription id
     * @dev Only callable by owner
     * @param _subscriptionId New subscription id
     */
    function setSubscriptionId(uint64 _subscriptionId) public onlyOwner {
        subscriptionId = _subscriptionId;
        emit SubscriptionIdSet(subscriptionId);
    }

    /**
     * @notice Updates key hash
     * @dev Only callable by owner
     * @param _keyHash New key hash
     */
    function setKeyHash(bytes32 _keyHash) public onlyOwner {
        keyHash = _keyHash;
        emit KeyHashSet(keyHash);
    }

    /**
     * @notice Updates vfr coordinator
     * @dev Only callable by owner
     * @param _vrfCoordinator New vrf coordinator
     */
    function setVrfCoordinator(address _vrfCoordinator) public onlyOwner {
        vrfCoordinator = VRFCoordinatorV2Interface(_vrfCoordinator);
        emit VrfCoordinatorSet(_vrfCoordinator);
    }

    /**
     * @notice Updates pull from address
     * @dev Only callable by owner
     * @param _pullFromAddress New pull from address
     */
    function setPullFromAddress(address _pullFromAddress) external onlyOwner {
        pullFromAddress = _pullFromAddress;
        emit PullFromAddressSet(pullFromAddress);
    }

    /**
     * @notice Updates comic address
     * @dev Only callable by owner
     * @param _comicAddress New comic address
     */
    function setComicAddress(address _comicAddress) external onlyOwner {
        comicAddress = _comicAddress;
        emit ComicAddressSet(comicAddress);
    }

    /**
     * @notice Updates parallel alpha address
     * @dev Only callable by owner
     * @param _parallelAlphaAddress New parallel alpha address
     */
    function setParallelAlphaAddress(
        address _parallelAlphaAddress
    ) external onlyOwner {
        parallelAlphaAddress = _parallelAlphaAddress;
        emit ParallelAlphaAddressSet(parallelAlphaAddress);
    }

    /**
     * @notice Updates shop address
     * @dev Only callable by owner
     * @param _shopAddress New shop address
     */
    function setShopAddress(address _shopAddress) external onlyOwner {
        shopAddress = _shopAddress;
        emit ShopContractSet(shopAddress);
    }

    /**
     * @notice Sets comic max supply for each comic tier
     * @dev Only callable by owner
     * @param _comicSupply List of comic supply for each comic tier
     */
    function setComicMaxSupply(
        uint256[2] memory _comicTokenIds,
        uint256[2] memory _comicSupply
    ) external onlyOwner {
        if (_comicTokenIds.length != _comicSupply.length) {
            revert ParamLengthMissMatch();
        }

        comicSupplyRemaining = 0;
        numRequestsRemaining = 0;
        comicTokenIds = _comicTokenIds;

        for (uint256 i = 0; i < comicTokenIds.length; i++) {
            comicPurchased[comicTokenIds[i]] = 0;
            comicMaxSupply[comicTokenIds[i]] = _comicSupply[i];
            comicSupplyRemaining += _comicSupply[i];
            numRequestsRemaining += _comicSupply[i];
        }
        emit ComicSupplySet(_comicTokenIds, _comicSupply);
    }

    /**
     * @notice Sets card back max supply along with card back token ids
     * @dev Only callable by owner
     * @param _cardBackTokenIds List of card back token ids
     * @param _cardBackSupply List card back supply for each token id
     */
    function setCardBackTokenIds(
        uint256[] memory _cardBackTokenIds,
        uint256[] memory _cardBackSupply
    ) external onlyOwner {
        if (_cardBackTokenIds.length != _cardBackSupply.length) {
            revert ParamLengthMissMatch();
        }

        cardBackSupplyRemaining = 0;
        cardBackTokenIds = _cardBackTokenIds;
        for (uint256 i = 0; i < _cardBackTokenIds.length; i++) {
            cardBackPurchased[_cardBackTokenIds[i]] = 0;
            cardBackMaxSupply[_cardBackTokenIds[i]] = _cardBackSupply[i];
            cardBackSupplyRemaining += _cardBackSupply[i];
        }
        emit CardBackSupplySet(_cardBackTokenIds, _cardBackSupply);
    }

    /**
     * @notice Updates card back disable status
     * @dev Only callable by owner
     * @param _isCardBackDisabled New card back disable status
     */
    function setCardBackDisabled(bool _isCardBackDisabled) external onlyOwner {
        isCardBackDisabled = _isCardBackDisabled;
        emit CardBackDisabledSet(isCardBackDisabled);
    }

    /**
     * @notice Kicks off VRF request for the given user
     * @dev Only callable by shop contract
     * @param _to Destination address
     * @param _amount Number of comics to assign
     * @param _transactionId Id based by server to include in event for tracking
     */
    function getComics(
        address _to,
        uint256 _amount,
        uint256 _transactionId
    ) external {
        if (msg.sender != shopAddress) {
            revert InvalidInvoker();
        }

        if (numRequestsRemaining < _amount) {
            revert SupplyOverflow();
        }
        numRequestsRemaining -= _amount;

        // Create request struct and store in mapping under VRF request Id
        ProductComicLib.Request memory newRequest;
        newRequest.owner = _to;
        newRequest.numComicsToSend = _amount;

        // Request VRF
        uint256 requestId = vrfCoordinator.requestRandomWords(
            keyHash,
            subscriptionId,
            requestConfirmations,
            callbackGasLimit,
            numWords
        );

        vrfRequestIdToRequest[requestId] = newRequest;
        emit ComicPurchased(_to, _amount, requestId, _transactionId);
    }

    /**
     * @notice Callback function hit by ChainLink VRF. Assigns comics, shards and card back (if need be)
     */
    function fulfillRandomWords(
        uint256 _requestId,
        uint256[] memory _randomWords
    ) internal override nonReentrant {
        ProductComicLib.Request storage request = vrfRequestIdToRequest[
            _requestId
        ];
        if (request.owner == address(0)) {
            revert EmptyRequestFulfillment();
        }
        if (request.isAssigned) {
            revert RequestAlreadyFulfilled();
        }

        uint256 randomSeed;
        uint256[] memory assignedComicTokenIds = new uint256[](
            request.numComicsToSend
        );
        uint256[] memory assignedCardBackTokenIds = new uint256[](
            request.numComicsToSend
        );
        for (uint256 i = 0; i < request.numComicsToSend; i++) {
            randomSeed = uint256(
                keccak256(abi.encodePacked(_randomWords[0], i))
            );
            assignedComicTokenIds[i] = _getComicTokenId(randomSeed);

            IERC1155(comicAddress).safeTransferFrom(
                pullFromAddress,
                request.owner,
                assignedComicTokenIds[i],
                1,
                bytes("")
            );

            if (!isCardBackDisabled) {
                randomSeed = uint256(
                    keccak256(abi.encodePacked(randomSeed, i))
                );
                assignedCardBackTokenIds[i] = _getCardBackTokenId(randomSeed);
                IERC1155(parallelAlphaAddress).safeTransferFrom(
                    pullFromAddress,
                    request.owner,
                    assignedCardBackTokenIds[i],
                    1,
                    bytes("")
                );
            }
        }

        request.isAssigned = true;
        emit ComicTransferred(
            request.owner,
            request.numComicsToSend,
            _requestId,
            request.transactionId,
            assignedComicTokenIds,
            assignedCardBackTokenIds
        );
    }

    /**
     * @notice Re-trigger request. Deletes the old request
     * @dev Old request most not be fulfilled. Only callable by owner
     * @param _oldRequestId If of the request to re-trigger
     */
    function recoverRequestId(uint256 _oldRequestId) external onlyOwner {
        ProductComicLib.Request memory oldRequest = vrfRequestIdToRequest[
            _oldRequestId
        ];
        if (oldRequest.isAssigned) {
            revert RequestAlreadyFulfilled();
        }

        // fire off new one
        uint256 newRequestId = vrfCoordinator.requestRandomWords(
            keyHash,
            subscriptionId,
            requestConfirmations,
            callbackGasLimit,
            numWords
        );
        ProductComicLib.Request memory newRequest;
        newRequest.owner = oldRequest.owner;
        newRequest.numComicsToSend = oldRequest.numComicsToSend;
        newRequest.transactionId = oldRequest.transactionId;

        vrfRequestIdToRequest[newRequestId] = newRequest;

        // delete old request
        delete vrfRequestIdToRequest[_oldRequestId];

        // Emit new requestId
        emit RequestRecovered(
            newRequest.owner,
            newRequest.numComicsToSend,
            newRequestId,
            newRequest.transactionId
        );
    }

    /**
     * @notice Calculates random comic token id based on the remaining supply
     * @param _randomSeed Random seed to use for token id selection
     */
    function _getComicTokenId(uint256 _randomSeed) internal returns (uint256) {
        uint256 randomPercent = _randomSeed % 100;

        uint256 silverPercent = ((comicMaxSupply[comicTokenIds[0]] -
            comicPurchased[comicTokenIds[0]]) * 100) / comicSupplyRemaining;

        comicSupplyRemaining -= 1;

        if (randomPercent < silverPercent) {
            comicPurchased[comicTokenIds[0]] += 1;
            return comicTokenIds[0];
        } else {
            comicPurchased[comicTokenIds[1]] += 1;
            return comicTokenIds[1];
        }
    }

    /**
     * @notice Calculates random card back token id based on the remaining supply
     * @param _randomSeed Random seed to use for token if selection
     */
    function _getCardBackTokenId(
        uint256 _randomSeed
    ) internal returns (uint256) {
        uint256 randomPercent = _randomSeed % 100;
        uint256 selectedIndex;
        uint256 cardBackPercent;
        while (selectedIndex != cardBackTokenIds.length - 1) {
            cardBackPercent +=
                ((cardBackMaxSupply[cardBackTokenIds[selectedIndex]] -
                    cardBackPurchased[cardBackTokenIds[selectedIndex]]) * 100) /
                cardBackSupplyRemaining;
            if (randomPercent < cardBackPercent) {
                break;
            }
            selectedIndex += 1;
        }
        uint256 selectedTokenId = cardBackTokenIds[selectedIndex];
        if (
            cardBackPurchased[selectedTokenId] ==
            cardBackMaxSupply[selectedTokenId]
        ) {
            revert CardBackSUpplyOverflow();
        }
        cardBackPurchased[selectedTokenId] += 1;
        cardBackSupplyRemaining -= 1;
        if (
            cardBackPurchased[selectedTokenId] ==
            cardBackMaxSupply[selectedTokenId]
        ) {
            cardBackTokenIds[selectedIndex] = cardBackTokenIds[
                cardBackTokenIds.length - 1
            ];
            cardBackTokenIds.pop();
        }

        return selectedTokenId;
    }
}