abstract contract EaselyMarketplaceCollection is ERC721Enumerable, Ownable {
    using ECDSA for bytes32;
    using Strings for uint256;

    /**
     * @dev Auction structure that includes:
     * 
     * @param address topBidder - Current top bidder who has already paid the price param below. Is
     *        initialized with address(0) when there have been no bids. When a bidder gets outBid,
     *        the old topBidder will get the price they paid returned.
     * @param uint256 price - Current top price paid by the topBidder.
     * @param uint256 startTimestamp - When the auction can start getting bidded on.
     * @param uint256 endTimestamp - When the auction can no longer get bid on.
     * @param uint256 minBidIncrement - The minimum each new bid has to be greater than the previous
     *        bid in order to be the next topBidder.
     * @param uint256 minLastBidDuration - The minimum time each bid must hold the highest price before
     *        the auction can settle. If people keep bidding, the auction can last for much longer than 
     *        the initial endTimestamp, and endTimestamp will continually be updated.
     */
    struct Auction {
        address topBidder;
        uint256 tokenId;
        uint256 price;
        uint256 startTimestamp;
        uint256 endTimestamp;
        uint256 minBidIncrement;
        uint256 minLastBidDuration;
    }

    /* see {IEaselyPayout} for more */
    address public payoutContractAddress;
    /* Let's the owner enable another address to lazy mint */
    address public alternateSignerAddress;
    uint256 internal nextAuctionId;
    uint256 public timePerDecrement;

    uint256 public constant maxRoyaltiesBPS = 9500;
    /* Optional basis points for the owner for secondary sales of this collection */
    uint256 public constant maxSecondaryBPS = 1000;
    
    /* Optional basis points for the owner for secondary sales of this collection */
    uint256 public secondaryOwnerBPS;
    /* Optional addresses to distribute royalties for primary sales of this collection */
    address[] public royalties;
    /* Optional basis points for above royalties addresses for primary sales of this collection */
    uint256[] public royaltiesBPS;

    /* Mapping if a tokenId has an active auction or not */
    mapping(uint256 => uint256) private _tokenIdToAuctionId;
    /* Mapping for all auctions that have happened. */
    mapping(uint256 => Auction) private _auctionIdToAuction;

    /* Mapping to the active version for all signed transactions */
    mapping(address => uint256) internal _addressToActiveVersion;
    /* Cancelled or finalized sales by hash to determine buyabliity */
    mapping(bytes32 => bool) internal _cancelledOrFinalizedSales;

    // Events related to an auction
    event AuctionCreated(uint256 indexed auctionId, uint256 indexed tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration, address indexed seller);
    event AuctionTimeAltered(uint256 indexed auctionId, uint256 indexed tokenId, uint256 startTime, uint256 endTime, address indexed seller);
    event AuctionCancelled(uint256 indexed auctionId, uint256 indexed tokenId, address indexed seller);
    event AuctionBidded(uint256 indexed auctionId, uint256 indexed tokenId, uint256 newPrice, uint256 timestamp, address indexed bidder);
    event AuctionSettled(uint256 indexed auctionId, uint256 indexed tokenId, uint256 price, address buyer, address indexed seller);

    // Events related to lazy selling
    event SaleCancelled(address indexed seller, bytes32 hash);
    event SaleCompleted(uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash);

    // Miscellaneous events
    event VersionChanged(address indexed seller, uint256 version);
    event AltSignerChanged(address newSigner);
    
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId 
            || interfaceId == type(Ownable).interfaceId
            || interfaceId == type(IERC2981).interfaceId
            || super.supportsInterface(interfaceId);
    }

    /**
     * @dev see {IERC2981-supportsInterface}
     */
    function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
        uint256 royalty = _salePrice * secondaryOwnerBPS / 10000;
        return (owner(), royalty);
    }

    /**
     * @dev Returns the current auction variables for a tokenId if the auction is present
     */
    function getAuctionForTokenId(uint256 tokenId) external view returns (Auction memory) {
        // _getAuctionId will error if token is not on an auction
        uint256 auctionId = _getAuctionId(tokenId);

        return _auctionIdToAuction[auctionId];
    }

    /**
     * @dev See {_getAuctionId}
     */
    function getAuctionId(uint256 tokenId) external view returns (uint256) {
        return _getAuctionId(tokenId);
    }

    /**
     * @dev Returns the current auction variables for a tokenId if the auction is present
     */
    function getAuction(uint256 auctionId) external view returns (Auction memory) {
        require(_auctionIdToAuction[auctionId].minBidIncrement != 0, "This auction does not exist");
        return _auctionIdToAuction[auctionId];
    }

    /** 
     * @dev See {_currentPrice}
     */
    function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) {
        return _currentPrice(pricesAndTimestamps);
    }

    /**
     * @dev Returns the current activeVersion of an address both used to create signatures
     * and to verify signatures of {buyToken} and {buyNewToken}
     */
    function getActiveVersion(address address_) external view returns (uint256) {
        return _addressToActiveVersion[address_];
    }

    /**
     * @dev Allows the owner to change who the alternate signer is 
     */
    function setAltSigner(address alt) external onlyOwner {
        alternateSignerAddress = alt;
        emit AltSignerChanged(alt);
    }

    /**
     * @dev see {_setRoyalties}
     */
    function setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) external onlyOwner {
        _setRoyalties(newRoyalties, bps);
    }

    /**
     * @dev see {_setSecondary}
     */
    function setSecondaryBPS(uint256 bps) external onlyOwner() {
        _setSecondary(bps);
    }

    /**
     * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if
     * an address wants to mass invalidate their signatures without having to call cancelSale on each one.
     */
    function updateVersion(uint256 version) external {
        _addressToActiveVersion[_msgSender()] = version;
        emit VersionChanged(_msgSender(), version);
    }

    /**
     * @dev Creates an auction for a token and locks it from being transferred until the auction ends
     * the auction can end if the endTimestamp has been reached and can be cancelled prematurely if
     * there has been no bids yet.
     *
     * @param tokenId uint256 for the token to put on auction. Must exist and be on the auction already
     * @param startingPrice uint256 for the starting price an interested owner must bid
     * @param startingTimestamp uint256 for when the auction can start taking bids
     * @param endingTimestamp uint256 for when the auction has concluded and can no longer take bids
     * @param minBidIncrement uint256 the minimum each interested owner must bid over the latest bid
     * @param minLastBidDuration uint256 the minimum time a bid needs to be live before the auction can end.
     *        this means that an auction can extend past its original endingTimestamp
     */
    function createAuction(
        uint256 tokenId,
        uint256 startingPrice,
        uint256 startingTimestamp,
        uint256 endingTimestamp,
        uint256 minBidIncrement,
        uint256 minLastBidDuration
    ) external {
        require(endingTimestamp > block.timestamp, "Cannot create an auction in the past");
        require(!_onAuction(tokenId), "Token is already on auction");
        require(minBidIncrement > 0, "Min bid must be a positive number");
        require(_msgSender() == ownerOf(tokenId), "Must own token to create auction");

        Auction memory auction = Auction(address(0), tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration);
        // This locks the token from being sold
        _tokenIdToAuctionId[tokenId] = nextAuctionId;
        _auctionIdToAuction[nextAuctionId] = auction;
        
        emit AuctionCreated(nextAuctionId, tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration, ownerOf(tokenId));
        nextAuctionId += 1;
    }

    /** 
     * @dev Lets the token owner alter the start and end time of an auction in case they want to 
     * end an auction early, extend the auction, or start it early. 
     * 
     * Changes to endTime can only be made when the auction is not within a minLastBidDuration from ending.
     * Changes to startTime can only be made when the auction has not yet started.
     */
    function alterAuctionTime(uint256 tokenId, uint256 startTime, uint256 endTime) external {
        // _getAuctionId will error if token is not on an auction
        uint256 auctionId = _getAuctionId(tokenId);
        uint256 time = block.timestamp;

        require(_msgSender() == ownerOf(tokenId), "Only token owner can alter end time");
        Auction memory auction = _auctionIdToAuction[auctionId];
        require(auction.endTimestamp > time + auction.minLastBidDuration, "Auction has ended or is close to ending");

        // if the auction has already started we cannot change the start time
        if (auction.startTimestamp > time) {
            auction.startTimestamp = startTime;
        }
        auction.endTimestamp = endTime;

        _auctionIdToAuction[auctionId] = auction;
        emit AuctionTimeAltered(auctionId, tokenId, startTime, endTime, ownerOf(tokenId));
    }

    /**
     * @dev Allows the token owner to cancel an auction that does not yet have a bid.
     */
    function cancelAuction(uint256 tokenId) external {
        // _getAuctionId will error if token is not on an auction
        uint256 auctionId = _getAuctionId(tokenId);

        require(_msgSender() == ownerOf(tokenId), "Only token owner can cancel auction");
        require(_auctionIdToAuction[auctionId].topBidder == address(0), "Cannot cancel an auction with a bid");

        _tokenIdToAuctionId[tokenId] = 0;

        emit AuctionCancelled(auctionId, tokenId, ownerOf(tokenId));
    }

    /**
     * @dev Method that anyone can call to settle the auction. It is available to everyone
     * because the settlement is not dependent on the message sender, and will allow either
     * the buyer, the seller, or a third party to cover the gas fees to settle. The burdern of
     * the auction to settle should be on the seller, but in case there are issues with
     * the seller settling we will not be locked from settling.
     *
     * If the seller is the contract owner, this is considered a primary sale and royalties will
     * be paid to primiary royalties. If the seller is a user then it is a secondary sale and
     * the contract owner will get a secondary sale cut.
     */
    function settleAuction(uint256 tokenId) external {
        // _getAuctionId will error if token is not on an auction
        uint256 auctionId = _getAuctionId(tokenId);        
        
        Auction memory auction = _auctionIdToAuction[auctionId];
        address tokenOwner = ownerOf(tokenId);
        require(block.timestamp > auction.endTimestamp, "Auction must end to be settled");
        require(auction.topBidder != address(0), "No bidder, cancel the auction instead");

        // This will allow transfers again
        _tokenIdToAuctionId[tokenId] = 0;

        _transfer(tokenOwner, auction.topBidder, tokenId);
    
        if (tokenOwner == owner()) {
            IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, royalties, royaltiesBPS);
        } else {
            address[] memory ownerRoyalties = new address[](1);
            uint256[] memory ownerBPS = new uint256[](1);
            ownerRoyalties[0] = owner();
            ownerBPS[0] = secondaryOwnerBPS;

            IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, ownerRoyalties, ownerBPS);
        }

        emit AuctionSettled(auctionId, tokenId, auction.price, auction.topBidder, tokenOwner);
    }

    /**
     * @dev Allows any potential buyer to submit a bid on a token with an auction. When outbidding the current topBidder
     * the contract returns the value that the previous bidder had escrowed to the contract.
     */
    function bidOnAuction(uint256 tokenId) external payable {
        // _getAuctionId will error if token is not on an auction
        uint256 auctionId = _getAuctionId(tokenId);      
        
        uint256 timestamp = block.timestamp;
        Auction memory auction = _auctionIdToAuction[auctionId];
        uint256 msgValue = msg.value;

        address prevBidder = auction.topBidder;
        uint256 prevPrice = auction.price;

        // Tokens that are not on auction always have an endTimestamp of 0
        require(timestamp <= auction.endTimestamp, "Auction has already ended");
        require(timestamp >= auction.startTimestamp, "Auction has not started yet");

        uint256 minPrice = prevPrice + auction.minBidIncrement;
        if (prevBidder == address(0)) {
            minPrice = prevPrice;
        }
        require(msgValue >= minPrice, "Bid is too small");

        uint256 endTime = auction.endTimestamp;
        if (endTime < auction.minLastBidDuration + timestamp) {
            endTime = timestamp + auction.minLastBidDuration;
        }

        auction.endTimestamp = endTime;
        auction.price = msgValue;
        auction.topBidder = _msgSender();

        _auctionIdToAuction[auctionId] = auction;
        
        if (prevBidder != address(0)) {
            // Give the old top bidder their money back
            payable(prevBidder).transfer(prevPrice);
        }
        emit AuctionBidded(auctionId, tokenId, auction.price, timestamp, auction.topBidder);
    }

    /**
     * @dev Usable by the owner of any token initiate a sale for their token. This does not
     * lock the tokenId and the owner can freely trade their token because unlike auctions
     * sales would be immediate.
     */
    function hashToSignToSellToken(
        uint256 version,
        uint256 nonce,
        uint256 tokenId,
        uint256[4] memory pricesAndTimestamps
    ) external view returns (bytes32) {
        require(_msgSender() == ownerOf(tokenId), "Not the owner of the token");
        return _hashForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps);
    }

    /**
     * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy
     * the token from the seller. These are all considered secondary sales and will give a cut to the 
     * owner of the contract based on the secondaryOwnerBPS.
     */
    function buyToken(
        address seller,
        uint256 version,
        uint256 nonce,
        uint256 tokenId,
        uint256[4] memory pricesAndTimestamps,
        bytes memory signature
    ) external payable {
        uint256 currentPrice = _currentPrice(pricesAndTimestamps);

        require(_addressToActiveVersion[seller] == version, "Incorrect signature version");
        require(msg.value >= currentPrice, "Not enough ETH to buy");

        _markHashSold(seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature);

        _transfer(seller, _msgSender(), tokenId);

        IEaselyPayout(payoutContractAddress).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS());
        payable(_msgSender()).transfer(msg.value - currentPrice);
    }

    /**
     * @dev Usable to cancel hashes generated from {hashToSignToSellToken}
     */
    function cancelSale(
        uint256 version,
        uint256 nonce,
        uint256 tokenId,
        uint256[4] memory pricesAndTimestamps
    ) external {
        bytes32 hash = _hashToCheckForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps);
        _cancelledOrFinalizedSales[hash] = true;
        emit SaleCancelled(_msgSender(), hash);
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual override returns (string memory) {
        return "ipfs://";
    }

    /**
     * @dev Changing _beforeTokenTransfer to lock tokens that are in an auction so
     * that owner cannot transfer the token as people are bidding on it.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual override { 
        require(!_onAuction(tokenId), "Cannot transfer a token in an auction");

        super._beforeTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev checks if a token is in an auction or not. We make sure that no active auction can 
     * have an endTimestamp of 0.
     */
    function _onAuction(uint256 tokenId) internal view returns (bool) {
        return _tokenIdToAuctionId[tokenId] != 0;
    }

    /**
     * @dev returns the auctionId of a tokenId if the token is on auction.
     */
    function _getAuctionId(uint256 tokenId) internal view returns (uint256) {
        require(_onAuction(tokenId), "This token is not on auction");
        return _tokenIdToAuctionId[tokenId];
    }

    /**
     * @dev helper method get ownerRoyalties into an array form
     */
    function _ownerRoyalties() internal view returns (address[] memory) {
        address[] memory ownerRoyalties = new address[](1);
        ownerRoyalties[0] = owner();
        return ownerRoyalties;
    }

    /**
     * @dev helper method get secondary BPS into array form
     */
    function _ownerBPS() internal view returns (uint256[] memory) {
        uint256[] memory ownerBPS = new uint256[](1);
        ownerBPS[0] = secondaryOwnerBPS;
        return ownerBPS;
    }

    /**
     * @dev Current price for a sale which is calculated for the case of a descending auction. So
     * the ending price must be less than the starting price and the auction must have already started.
     * Standard single fare sales will have a matching starting and ending price.
     */
    function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) {
        uint256 startingPrice = pricesAndTimestamps[0];
        uint256 endingPrice = pricesAndTimestamps[1];
        uint256 startingTimestamp = pricesAndTimestamps[2];
        uint256 endingTimestamp = pricesAndTimestamps[3];

        uint256 currTime = block.timestamp;
        require(currTime >= startingTimestamp, "Has not started yet");
        require(startingTimestamp < endingTimestamp, "Must end after it starts");
        require(startingPrice >= endingPrice, "Ending price cannot be bigger");

        if (startingPrice == endingPrice || currTime > endingTimestamp) {
            return endingPrice;
        }

        uint256 diff = startingPrice - endingPrice;
        uint256 decrements = (currTime - startingTimestamp) / timePerDecrement;
        if (decrements == 0) {
            return startingPrice;
        }

        // decrements will equal 0 before totalDecrements does so we will not divide by 0
        uint256 totalDecrements = (endingTimestamp - startingTimestamp) / timePerDecrement;

        return startingPrice - diff / totalDecrements * decrements;
    }

    /**
     * @dev Sets secondary BPS amount
     */
    function _setSecondary(uint256 secondary) internal {
        secondaryOwnerBPS = secondary;
        require(secondaryOwnerBPS <= maxSecondaryBPS, "Cannot take more than 10% of secondaries");
    }

    /**
     * @dev Sets primary royalties
     */
    function _setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) internal {
        require(bps[0] + bps[1] + bps[2] + bps[3] <= maxRoyaltiesBPS, "Royalties too high");
        royalties = newRoyalties;
        royaltiesBPS = bps;
    }

    /**
     * @dev Checks if an address is either the owner, or the approved alternate signer.
     */
    function _checkValidSigner(address signer) internal view {
        require(signer == owner() || signer == alternateSignerAddress, "Not valid signer.");
    }

    /**
     * toEthSignedMessageHash
     * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
     * and hash the result
     */
    function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed
     * and that the correct address has given the signature. If both checks pass we mark the hash as complete and
     * emit an event.
     */
    function _markHashSold(
        address owner,
        uint256 version,
        uint256 nonce,
        uint256 tokenId,
        uint256[4] memory pricesAndTimestamps,
        uint256 salePrice,
        bytes memory signature
    ) internal {
        bytes32 hash = _hashToCheckForSale(owner, version, nonce, tokenId, pricesAndTimestamps);
        require(!_cancelledOrFinalizedSales[hash], "Sale no longer active");
        require(hash.recover(signature) == owner, "Not signed by current token owner");
        _cancelledOrFinalizedSales[hash] = true;

        emit SaleCompleted(tokenId, salePrice, owner, _msgSender(), hash);
    }

    /**
     * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
     * @return Hash of message prefix and order hash per Ethereum format
     */
    function _hashToCheckForSale(
        address owner,
        uint256 version,
        uint256 nonce,
        uint256 tokenId,
        uint256[4] memory pricesAndTimestamps
    ) internal view returns (bytes32) {
        return _toEthSignedMessageHash(_hashForSale(owner, version, nonce, tokenId, pricesAndTimestamps));
    }

    /**
     * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
     * @return Hash of message prefix and order hash per Ethereum format
     */
    function _hashForSale(
        address owner,
        uint256 version,
        uint256 nonce,
        uint256 tokenId,
        uint256[4] memory pricesAndTimestamps
    ) internal view returns (bytes32) {
        return keccak256(abi.encode(address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps));
    }
}
/** 
 * @dev Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-sales
 * and auctions do not have to be done on another contract. This saves gas fees on secondary sales because
 * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying.
 *
 * Easely will help power the lazy-selling and auctions as well as lazy minting that take place on 
 * directly on the collection, which is why we take a cut of these transactions. Our cut can 
 * be publically seen in the connected EaselyPayout contract.
 */
function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) {
    return _currentPrice(pricesAndTimestamps);
}

/** 
 * @dev See {_currentPrice}
 */