// File: contracts/SlothEquipment.sol



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

import "./interfaces/ISlothItemV3.sol";
import "./interfaces/ISpecialSlothItem.sol";
import "./interfaces/IItemType.sol";
import "./interfaces/IEquipment.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract SlothEquipment is Ownable {
  address private _slothAddr;
  address private _slothItemAddr;
  address private _specialSlothItemAddr;
  address private _userGeneratedSlothItemAddr;
  uint8 private constant _ITEM_NUM = 5;

  function _getSpecialType(uint256 _itemTokenId) internal view returns (uint256) {
    ISpecialSlothItem specialSlothItem = ISpecialSlothItem(_specialSlothItemAddr);
    return specialSlothItem.getSpecialType(_itemTokenId);
  }

  function _checkIsCombinationalCollabo(uint256 _specialType) internal view returns (bool) {
    ISpecialSlothItem specialSlothItem = ISpecialSlothItem(_specialSlothItemAddr);
    return specialSlothItem.isCombinational(_specialType);
  }

  function _checkOwner(uint256 _itemTokenId, IItemType.ItemMintType _itemMintType, address sender) internal view {
    if (_itemMintType == IItemType.ItemMintType.SLOTH_ITEM) {
      ISlothItemV3 slothItem = ISlothItemV3(_slothItemAddr);
      require(slothItem.exists(_itemTokenId), "token not exists");
      require(slothItem.ownerOf(_itemTokenId) == sender, "not owner");
      return;
    }
    
    if (uint(_itemMintType) == uint(IItemType.ItemMintType.SPECIAL_SLOTH_ITEM)) {
      ISpecialSlothItem specialSlothItem = ISpecialSlothItem(_specialSlothItemAddr);
      require(specialSlothItem.exists(_itemTokenId), "token not exists");
      require(specialSlothItem.ownerOf(_itemTokenId) == sender, "not owner");  
      return;
    }

    revert("wrorng itemMintType");
  }

  function _checkItemType(uint256 _itemTokenId, IItemType.ItemMintType _itemMintType, IItemType.ItemType _itemType) internal view {
    if (_itemMintType == IItemType.ItemMintType.SLOTH_ITEM) {
      ISlothItemV3 slothItem = ISlothItemV3(_slothItemAddr);
      require(slothItem.getItemType(_itemTokenId) == _itemType, "wrong item type");
      return;
    }

    if (_itemMintType == IItemType.ItemMintType.SPECIAL_SLOTH_ITEM) {
      ISpecialSlothItem specialSlothItem = ISpecialSlothItem(_specialSlothItemAddr);
      require(specialSlothItem.getItemType(_itemTokenId) == _itemType, "wrong item type");
      return;
    }

    revert("wrorng itemMintType");
  }

  function validateSetItems(uint256[] calldata equipmentItemIds, IEquipment.EquipmentTargetItem[] calldata equipmentTargetItems, address sender) external view returns (bool) {
    uint8 equipmentTargetSlothItemNum = 0;
    uint8 specialItemCount = 0;
    uint256 latestSpecialType = 99;
    bool latestSpecialTypeCombinationable = true;
  
    for (uint8 i = 0; i < _ITEM_NUM; i++) {
      uint256 _itemTokenId = equipmentTargetItems[i].itemTokenId;
      IItemType.ItemMintType _itemMintType = equipmentTargetItems[i].itemMintType;
      // token存在チェック、オーナーチェック
      if (_itemTokenId != 0) {
        if (equipmentItemIds[i] != _itemTokenId) {
          _checkOwner(_itemTokenId, _itemMintType, sender);
        }

        if (_itemMintType == IItemType.ItemMintType.SPECIAL_SLOTH_ITEM) {
          _checkItemType(_itemTokenId, _itemMintType, IItemType.ItemType(i));
          // コラボアイテムだった場合に、併用可不可のチェックを行う
          uint256 _specialType = _getSpecialType(_itemTokenId);
          if (latestSpecialType != _specialType) {
            bool combinationable = _checkIsCombinationalCollabo(_specialType);
            latestSpecialTypeCombinationable = combinationable;
            specialItemCount++;
            if (specialItemCount >= 2) {
              // 2個目以降のコラボが出てきたときにconbinationのチェックを行う
              if (combinationable && latestSpecialTypeCombinationable) {
                // 併用可の場合は何もしない
              } else {
                // 併用不可の場合はエラーを返す
                revert("not combinationable");
              }
            }
            latestSpecialType = _specialType;
          }
        } else {
          _checkItemType(_itemTokenId, _itemMintType, IItemType.ItemType(i));

          equipmentTargetSlothItemNum++;
        }
      }
    }
    if (latestSpecialTypeCombinationable == false && equipmentTargetSlothItemNum > 0) {
      revert("not combinationable");
    }
    return true;
  }

  function getTargetItemContractAddress(IItemType.ItemMintType _itemMintType) external view returns (address) {
    if (_itemMintType == IItemType.ItemMintType.SLOTH_ITEM) {
      return _slothItemAddr;
    } else if (_itemMintType == IItemType.ItemMintType.SPECIAL_SLOTH_ITEM) {
      return _specialSlothItemAddr;
    } else if (_itemMintType == IItemType.ItemMintType.USER_GENERATED_SLOTH_ITEM) {
      return _userGeneratedSlothItemAddr;
    } else {
      revert("invalid itemMintType");
    }
  }

  function setSlothAddr(address newSlothAddr) external onlyOwner {
    _slothAddr = newSlothAddr;
  }
  function setSlothItemAddr(address newSlothItemAddr) external onlyOwner {
    _slothItemAddr = newSlothItemAddr;
  }
  function setSpecialSlothItemAddr(address newSpecialSlothItemAddr) external onlyOwner {
    _specialSlothItemAddr = newSpecialSlothItemAddr;
  }
}
// File: contracts/interfaces/IEquipment.sol



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

import "./IItemType.sol";

interface IEquipment {
  struct EquipmentTargetItem {
    uint256 itemTokenId;
    IItemType.ItemMintType itemMintType; 
  }
  struct Equipment {
    uint256 itemId;
    address itemAddr;
  }
  struct EquipmentTargetSpecial {
    uint256 specialType;
    bool combinationable;
  }
}
// File: contracts/interfaces/IItemType.sol



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

interface IItemType {
  enum ItemType { CLOTHES, HEAD, HAND, FOOT, STAMP }
  enum ItemMintType { SLOTH_ITEM, SPECIAL_SLOTH_ITEM, USER_GENERATED_SLOTH_ITEM }
}
// File: contracts/interfaces/ISpecialSlothItem.sol



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

import "./IItemType.sol";
import { IERC721AQueryableUpgradeable } from "erc721a-upgradeable/contracts/interfaces/IERC721AQueryableUpgradeable.sol";

interface ISpecialSlothItem is IERC721AQueryableUpgradeable, IItemType {
  function getItemType(uint256 tokenId) external view returns (ItemType);
  function getSpecialType(uint256 tokenId) external view returns (uint256);
  function getClothType(uint256 tokenId) external view returns (uint256);
  function exists(uint256 tokenId) external view returns (bool);
  function isCombinational(uint256 _specialType) external view returns (bool);
  function mintPoupelle(address sender, uint256 quantity) external;
}
// File: contracts/interfaces/ISlothItemV3.sol



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

import { IERC721AQueryableUpgradeable } from "erc721a-upgradeable/contracts/interfaces/IERC721AQueryableUpgradeable.sol";
import "./IItemType.sol";

interface ISlothItemV3 is IERC721AQueryableUpgradeable {
  function getItemType(uint256 tokenId) external view returns (IItemType.ItemType);
  function getItemMintCount(address sender) external view returns (uint256);
  function exists(uint256 tokenId) external view returns (bool);
  function clothesMint(address sender, uint256 quantity) external;
  function itemMint(address sender, uint256 quantity) 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: erc721a-upgradeable/contracts/interfaces/IERC721AQueryableUpgradeable.sol



// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.2
// Creator: Chiru Labs

pragma solidity ^0.8.4;

import '../extensions/IERC721AQueryableUpgradeable.sol';

// File: erc721a-upgradeable/contracts/extensions/IERC721AQueryableUpgradeable.sol



// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.2
// Creator: Chiru Labs

pragma solidity ^0.8.4;

import '../IERC721AUpgradeable.sol';

/**
 * @dev Interface of ERC721AQueryable.
 */
interface IERC721AQueryableUpgradeable is IERC721AUpgradeable {
    /**
     * Invalid query range (`start` >= `stop`).
     */
    error InvalidQueryRange();

    /**
     * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
     *
     * If the `tokenId` is out of bounds:
     *
     * - `addr = address(0)`
     * - `startTimestamp = 0`
     * - `burned = false`
     * - `extraData = 0`
     *
     * If the `tokenId` is burned:
     *
     * - `addr = <Address of owner before token was burned>`
     * - `startTimestamp = <Timestamp when token was burned>`
     * - `burned = true`
     * - `extraData = <Extra data when token was burned>`
     *
     * Otherwise:
     *
     * - `addr = <Address of owner>`
     * - `startTimestamp = <Timestamp of start of ownership>`
     * - `burned = false`
     * - `extraData = <Extra data at start of ownership>`
     */
    function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory);

    /**
     * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
     * See {ERC721AQueryable-explicitOwnershipOf}
     */
    function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory);

    /**
     * @dev Returns an array of token IDs owned by `owner`,
     * in the range [`start`, `stop`)
     * (i.e. `start <= tokenId < stop`).
     *
     * This function allows for tokens to be queried if the collection
     * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
     *
     * Requirements:
     *
     * - `start < stop`
     */
    function tokensOfOwnerIn(
        address owner,
        uint256 start,
        uint256 stop
    ) external view returns (uint256[] memory);

    /**
     * @dev Returns an array of token IDs owned by `owner`.
     *
     * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
     * It is meant to be called off-chain.
     *
     * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
     * multiple smaller scans if the collection is large enough to cause
     * an out-of-gas error (10K collections should be fine).
     */
    function tokensOfOwner(address owner) external view returns (uint256[] memory);
}

// File: erc721a-upgradeable/contracts/IERC721AUpgradeable.sol



// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.2
// Creator: Chiru Labs

pragma solidity ^0.8.4;

/**
 * @dev Interface of ERC721A.
 */
interface IERC721AUpgradeable {
    /**
     * The caller must own the token or be an approved operator.
     */
    error ApprovalCallerNotOwnerNorApproved();

    /**
     * The token does not exist.
     */
    error ApprovalQueryForNonexistentToken();

    /**
     * The caller cannot approve to their own address.
     */
    error ApproveToCaller();

    /**
     * Cannot query the balance for the zero address.
     */
    error BalanceQueryForZeroAddress();

    /**
     * Cannot mint to the zero address.
     */
    error MintToZeroAddress();

    /**
     * The quantity of tokens minted must be more than zero.
     */
    error MintZeroQuantity();

    /**
     * The token does not exist.
     */
    error OwnerQueryForNonexistentToken();

    /**
     * The caller must own the token or be an approved operator.
     */
    error TransferCallerNotOwnerNorApproved();

    /**
     * The token must be owned by `from`.
     */
    error TransferFromIncorrectOwner();

    /**
     * Cannot safely transfer to a contract that does not implement the
     * ERC721Receiver interface.
     */
    error TransferToNonERC721ReceiverImplementer();

    /**
     * Cannot transfer to the zero address.
     */
    error TransferToZeroAddress();

    /**
     * The token does not exist.
     */
    error URIQueryForNonexistentToken();

    /**
     * The `quantity` minted with ERC2309 exceeds the safety limit.
     */
    error MintERC2309QuantityExceedsLimit();

    /**
     * The `extraData` cannot be set on an unintialized ownership slot.
     */
    error OwnershipNotInitializedForExtraData();

    // =============================================================
    //                            STRUCTS
    // =============================================================

    struct TokenOwnership {
        // The address of the owner.
        address addr;
        // Stores the start time of ownership with minimal overhead for tokenomics.
        uint64 startTimestamp;
        // Whether the token has been burned.
        bool burned;
        // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
        uint24 extraData;
    }

    // =============================================================
    //                         TOKEN COUNTERS
    // =============================================================

    /**
     * @dev Returns the total number of tokens in existence.
     * Burned tokens will reduce the count.
     * To get the total number of tokens minted, please see {_totalMinted}.
     */
    function totalSupply() external view returns (uint256);

    // =============================================================
    //                            IERC165
    // =============================================================

    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);

    // =============================================================
    //                            IERC721
    // =============================================================

    /**
     * @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,
        bytes calldata data
    ) external;

    /**
     * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` 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 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 the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

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

    // =============================================================
    //                        IERC721Metadata
    // =============================================================

    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);

    // =============================================================
    //                           IERC2309
    // =============================================================

    /**
     * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
     * (inclusive) is transferred from `from` to `to`, as defined in the
     * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
     *
     * See {_mintERC2309} for more details.
     */
    event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}

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