contract Holidaze is ERC721Enumerable, Ownable, ReentrancyGuard {
    using Strings for uint256;
    
    struct AddressMintCount{
        uint256 mintCount;
        bool approved;
    }
    
    struct TokenUrlState{
        uint256 holidazeUrlKey;
        bool locked;
    }
   
    struct HolidazeUrlName{
        string baseUrl;
        string holidayName;
    }
   
    uint256 public constant MAX_SUPPLY = 10000;
    uint256 public constant MAX_PER_PURCHASE = 20;
    uint256 public constant SALE_PRICE = 0.025 ether;
    uint256 public constant RESERVE_QTY = 450; // Yes, we know this is a big number, but there's good reasons for that
    uint256 public constant MAX_ALOHA_ALPHA_ADDRESS_QTY = 2;

    bool public publicMintActive = false;
    bool public alohaAlphaMintActive = false;
    
    /**
     * @dev Specified whether or not owners can lock/unlock their tokens
     */
    bool public lockingAllowed = false; 

    /**
     * @dev Specifies whether or not the contract has been locked - forever - preventing
     * changes from being made that could affect the metadata
     */
    bool public contractLockedForever = false;

    /**
     * @dev The sha256 string of concatenated sha256 of all images in their natural order
     * @notice This will only be set after the last Holidaze collection url has been set 
     * because the images will - intentionally - change for any tokens that the owner has
     * explicitly unlocked
     */
    string public provenanceHash;

    // Payout addresses
    address private constant _founder = 0x737dc5b854f6ff99df8e86f6206e68F6708e70a8; // Founder
    address private constant _dev = 0x86190c50d1dD3Eeb2Ab1dbb8E7195F2195AF321f; // Solidity dev
    address private constant _artist = 0xaF030d8B42f4a046203305fBa46C175Ae25bc443; // OG Artist
    
    uint256 private constant _totalShares = 10000;

    bool private _adminsSet = false;
    uint256 private _qtyReserved = 0;
    uint256 private _currentHolidazeUrlKey = 0;
    
    IAlohaAlphaValidation private _alohaAlphaInstance;

    address[3] private _shareholders = [_founder, _dev, _artist];
    address[2] private _admins;
    
    mapping(address => uint256) private _shares;
    mapping(address => AddressMintCount) private _approvedAlohaAlphaHolders;
    mapping(uint256 => TokenUrlState) private _lockedTokenUrls;
    mapping(uint256 => HolidazeUrlName) private _holidazeUrls;

    event Mint(address indexed recipient, uint256 indexed tokenId);
    event HolidazeUrlAdded(uint256 urlKey, string tokenUrl, address addedBy);
    event Locked(address locker, uint256 indexed tokenId, uint256 urlKey);
    event Unlocked(address unlocker, uint256 indexed tokenId, uint256 previousUrlKey, uint256 urlKey);

    constructor(string memory name, string memory symbol) ERC721(name, symbol) {
        require(bytes(name).length > 0 && bytes(symbol).length > 0, "Name and Symbol");
        
        _shares[_founder] = 1650;
        _shares[_dev] = 1650;
        _shares[_artist] = 1650;
        // Remaining 50.5% goes to the contract/project owner
    }

    function mint(uint256 qty) external payable nonReentrant {
        require(publicMintActive, "Minting is not active");
        require(qty > 0, "Quantity cannot be zero");
        require(
            qty <= MAX_PER_PURCHASE,
            "Exceeds per-order limit"
        );
        require(msg.value == (SALE_PRICE * qty), "Incorrect payment amount");

        internalMint(_msgSender(), qty);
    }

    function alohaAlphaMint(uint256 qty) external onlyAlohaAlphaHolder {
        require(alohaAlphaMintActive, "Aloha Alpha minting is not active");
        require(_approvedAlohaAlphaHolders[_msgSender()].approved, "Aloha Alpha holder not approved");
        require(qty > 0, "Quantity cannot be zero");
        require(_approvedAlohaAlphaHolders[_msgSender()].mintCount + qty <= MAX_ALOHA_ALPHA_ADDRESS_QTY, "Aloha Alpha mints already claimed");
        _approvedAlohaAlphaHolders[_msgSender()].mintCount+=qty;
        internalMint(_msgSender(), qty);
    }

    function internalMint(address recipient, uint256 qty) private {
        require(qty > 0, "Quantity cannot be zero");
        require((totalSupply() + qty + RESERVE_QTY) <= MAX_SUPPLY, "Exceeds total supply");
        require(_currentHolidazeUrlKey > 0, "No urls set");

        for (uint256 i = 0; i < qty; i++) {
            uint256 tokenId = totalSupply() + 1;

            _safeMint(recipient, tokenId);

            TokenUrlState memory tokenUrlState = TokenUrlState(_currentHolidazeUrlKey, true);
            _lockedTokenUrls[tokenId] = tokenUrlState;
            
            emit Locked(_msgSender(), tokenId, tokenUrlState.holidazeUrlKey);
            emit Mint(recipient, tokenId);
        }
    }

    /**
     * @dev Mints and sends the specified number of tokens to the specified address for donation, marketing, reward use
     */
    function distributeFromReserve(uint256 qty, address recipient) external nonReentrant onlyOwner {
        require(
            (totalSupply() + qty + RESERVE_QTY) <= MAX_SUPPLY,
            "Exceeds total supply"
        );
        require(
            _qtyReserved + qty <= RESERVE_QTY,
            "Exceed reserve quantity"
        );

        for (uint256 i = 0; i < qty; i++) {
            _qtyReserved++;
            
            internalMint(recipient, 1);
        }
    }

    /**
     * @dev Locks the specified token
     * @notice Locking a token will -
     * 1. Lock the token to use the metadata from the current Holidaze url
     * 2. Prevent the metadata url from changing for the specified token when
     *    a new Holidaze collection is added
     */
    function lockTokenHolidazeUrl(uint256 tokenId) external validTokenOwner(tokenId) notLocked {
        require(lockingAllowed, 'Locking not currently allowed');
        require(_lockedTokenUrls[tokenId].locked == false, "Token already locked");
        
        TokenUrlState memory tokenUrlState = TokenUrlState(_currentHolidazeUrlKey, true);
        
        _lockedTokenUrls[tokenId] = tokenUrlState;
        
        emit Locked(_msgSender(), tokenId, _currentHolidazeUrlKey);
    }

    /**
     * @dev Allows the owner of the specified token to explicitly unlock their token
     * @notice Tokens are locked by default, so unlocking them will -
     * 1. Instantly result in the metadata and image changing to that of the most recent
     *    Holidaze collection
     * 2. Allow the metadata and image to continue changing each time a new Holidaze
     *    collection url is added, unless the token is explicitly locked by the user 
     *    prior to the new collection being added
     * @notice Unlocking a token _will_ result in the image, traits, description & rarity
     * changing, and this will also impact the overall rarity of the Holidaze collection
     */
    function unlockTokenHolidazeUrl(uint256 tokenId) external validTokenOwner(tokenId) notLocked {
        require(lockingAllowed, 'Unlocking not currently allowed');
        require(_lockedTokenUrls[tokenId].locked == true, "Token already unlocked");
        
        uint256 previousUrlKey = _lockedTokenUrls[tokenId].holidazeUrlKey;

        _lockedTokenUrls[tokenId] = TokenUrlState(0, false);
        
        emit Unlocked(_msgSender(), tokenId, previousUrlKey, _currentHolidazeUrlKey);
    }

    /**
     * @dev Adds the specified metadata url and name for a new holidaze collection
     * @notice Any tokens that were explicitly unlocked by their owners - before this function
     * is called - will have their metadata urls change to use the specified value
     */
    function addHolidazeUrl(string calldata url, string calldata name) external onlyOwnerOrAdmin notLocked {
        require(bytes(url).length > 0, "Invalid url");
        require(bytes(name).length > 0, "Invalid name");
        
        _currentHolidazeUrlKey++;
        
        _holidazeUrls[_currentHolidazeUrlKey] = HolidazeUrlName(url, name);
        
        emit HolidazeUrlAdded(_currentHolidazeUrlKey, url, _msgSender());
    }
    
    /**
     * @dev Specifies whether or not token holders are allowed to lock/unlock their tokens
     * @notice Once the url for the final collection has been added, lockingAllowed will be
     * set to true
     */
    function setLockingState(bool allowed) external onlyOwnerOrAdmin notLocked {
        lockingAllowed = allowed;
    }
    
    /**
     * @dev Addes the specified addresses to the list of approved alpha aloha holders
     */
    function addAlohaAlpha(address[] calldata aaAddresses) external onlyOwnerOrAdmin notLocked {
        for (uint256 i = 0; i < aaAddresses.length; i++) {
            if(!isApprovedAlohaAlpha(aaAddresses[i])){
                _approvedAlohaAlphaHolders[aaAddresses[i]] = AddressMintCount(0, true);
            }
        }
    }

    /**
     * @dev Removes the specified addresses from the list of approved alpha aloha holders
     */
    function removeAlohaAlpha(address[] calldata aaAddresses) external onlyOwnerOrAdmin {
        for (uint256 i = 0; i < aaAddresses.length; i++) {
            if(isApprovedAlohaAlpha(aaAddresses[i])){
                _approvedAlohaAlphaHolders[aaAddresses[i]].approved = false;
            }
        }
    }
    
    /**
     * @dev Returns the number of free mints claimed by the approved alpha aloha holders
     */
    function alohaAlphaMintsClaimed(address aaAddress) public view returns(uint256){
        return _approvedAlohaAlphaHolders[aaAddress].mintCount;
    }

    /**
     * @dev Returns a boolean indicating whether or not the specified address has been
     * approved to claim 2 free mints
     */
    function isApprovedAlohaAlpha(address aaAddress) public view returns (bool) {
        return _approvedAlohaAlphaHolders[aaAddress].approved;
    }

    /**
     * @dev Returns the full metadata url for the specified token
     * @notice
     * All tokens are locked to the current url at the time that they were minted.
     * If the token was minted before the first reveal, then it would effectively be locked to the 
     * pre-reveal url (key 1) until the first reveal url has been set (key 2).
     * Any tokens that were minted post-reveal, would be locked using the reveal url that was
     * set at the time of minting.
     * Any tokens that the holder has explicitly unlocked will use the most recent reveal url - regardless
     * of what the url was at the time of minting.  This means that the images and metadata for 
     * unlocked tokens will be changed automatically when a new reveal url is added.
     * When a holder of a token locks it, the reveal url for that token will not change unless the holder
     * explicitly re-locks it
     */
    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        require(_exists(tokenId), "Token does not exist");

        TokenUrlState memory urlState = _lockedTokenUrls[tokenId];
        
        string memory url;
        
        bool firstRevealUrlSet = _currentHolidazeUrlKey > 1;

        if(!firstRevealUrlSet){
            // We haven't reveal yet, so use the pre-reveal url
            url = _holidazeUrls[1].baseUrl;
        }
        else if(urlState.locked && urlState.holidazeUrlKey == 1){
            // The holder hasn't explicity unlocked the token and it's still locked to the pre-reveal
            // url.  Since the first reveal url has been set, the token is effectively locked to use
            // the reveal url
            url = _holidazeUrls[2].baseUrl;
        }
        else if(urlState.locked && urlState.holidazeUrlKey > 1){
            // The token is locked to a post-reveal url, so that's the url that will be used
            url = _holidazeUrls[urlState.holidazeUrlKey].baseUrl;
        }
        else{
            // The token has been explicitly unlocked, so the url that is used should be for the most 
            // recently added url (collection)
            url = _holidazeUrls[_currentHolidazeUrlKey].baseUrl;
        }

        return string(abi.encodePacked(url, "/", tokenId.toString(), ".json"));
    }

    /**
     * @dev Returns the lock state of the specified token. i.e., tells us -
     * 1. Whether or not the token has been locked to use a specific metadata url
     * 2. Which metadata url "key" the token is locked to. Using the key rather than 
     *    the _actual_ url allows us to save a bunch of gas
     */
    function getTokenUrlState(uint256 tokenId) public view returns (TokenUrlState memory){
        require(_exists(tokenId), "Token does not exist");
        return _lockedTokenUrls[tokenId];
    }

    function setAdmins(address[2] calldata adminAddresses) external onlyOwner {
        for (uint256 i = 0; i < adminAddresses.length; i++) {
            address admin = adminAddresses[i];

            require(admin != address(0), "Nope, that's not a good idea");
            _admins[i] = admin;
        }

        _adminsSet = true;
    }

    /**
     * @dev Creates a "limted functionality" instance of the contract for the specified address
     */
    function setAlohaAlphaInstance(address instanceAddress) external onlyOwner notLocked {
        _alohaAlphaInstance = IAlohaAlphaValidation(instanceAddress);
    }

    /**
     * @dev Distrubtes the balance to all shareholders as defined in the constructor and
     * then the remainder goes to the contract owner
     */
    function cashOut() external onlyOwner nonReentrant {
        require(address(this).balance > 0, "Insufficient balance");

        uint256 originalAmt = address(this).balance;
        uint256 balance = originalAmt;

        for (uint256 i = 0; i < _shareholders.length; i++) {
            address payee = _shareholders[i];
            uint256 payeeShares = _shares[payee];
            uint256 paymentAmount = (originalAmt * payeeShares) / _totalShares;

            balance -= paymentAmount;

            payable(payee).transfer(paymentAmount);
        }

        payable(_msgSender()).transfer(balance);
    }

    /**
     * @dev Activates/inactivates public minting
     */
    function setActive(bool active) public onlyOwnerOrAdmin {
        if(active) {
            require(_currentHolidazeUrlKey > 0, "No Holidaze urls exist");
        }
        publicMintActive = active;
    }

    /**
     * @dev Allow current holders of Poi Puppy Colony tokens to claim 2 NFTs for free,
     * provided they have also been added to the approved list of addresses
     */
    function setAlohaAlphaMintActive(bool active) public onlyOwnerOrAdmin {
        if(active) {
            require(_currentHolidazeUrlKey > 0, "No Holidaze urls exist");
        }
        require(address(_alohaAlphaInstance) != address(0), 'Aloha Alpha instance not set');
        alohaAlphaMintActive = active;
    }

    /*     
    * Sets the provenance hash - only set once the final collection has dropped because the 
    * images and metadata will - intentionally - change if any owners explicitly unlock
    * their tokens
    */
    function setProvenanceHash(string memory provenance) public onlyOwner notLocked {
        provenanceHash = provenance;
    }

    function getMaxHolidazeUrlKey() external view onlyOwnerOrAdmin returns(uint256) {
        return _currentHolidazeUrlKey;
    }

    function getHolidazeUrl(uint256 key) external view onlyOwnerOrAdmin returns(HolidazeUrlName memory) {
        return _holidazeUrls[key];
    }

    function tokensOfOwner(address owner) external view returns (uint256[] memory) {
        uint256 tokenCount = balanceOf(owner);
        if (tokenCount == 0) {
            return new uint256[](0);
        } else {
            uint256[] memory result = new uint256[](tokenCount);
            uint256 index;
            for (index =0; index < tokenCount; index++) {
                result[index] = tokenOfOwnerByIndex(owner, index);
            }
            return result;
        }
    }

    /**
     * @dev Locks the contract (prevents adding of new Holidaze collection urls, 
     * adding aloha alpha approvals, etc.), but does not prevent minting
     * @notice This action cannot be undone, so contract owner, be careful
     */
    function lockContractForever() public onlyOwner notLocked {
        require(_currentHolidazeUrlKey > 1, "Nope, no locking before reveal!");
        contractLockedForever = true;
    }

    /**
     * @dev Throws if called by any account other than the owner or one of the predefined admins.
     */
    modifier onlyOwnerOrAdmin() {
        require(
            _msgSender() == owner() ||
                (_adminsSet &&
                    (_msgSender() == _admins[0] || _msgSender() == _admins[1])),
            "Caller is not the owner or an admin"
        );
        _;
    }

    /**
     * @dev Throws if the specified token doesn't exist, or if the message sender isn't the 
     * owner of the specified token - to prevent others from modifying the tokens of others
     */
    modifier validTokenOwner(uint256 tokenId){
        require(_exists(tokenId), "The specified tokenId does not exist");
        require(_msgSender() == ownerOf(tokenId), "This can only be performed by the token owner");
        _;
    }
    
    /**
     *  @dev Throws if the message sender doe not currently hold any Poi Puppy Colony tokens 
     */
    modifier onlyAlohaAlphaHolder() {
        require(_alohaAlphaInstance.balanceOf(_msgSender()) > 0, "Not an Aloha Alpha holder");
        _;
    }
    
    /**
    * @dev Throws if the contract is locked
    */
    modifier notLocked() {
        require(!contractLockedForever, "Contract locked, forever!");
        _;
    }
}
/**
 * @notice This contract allows for the multiple metadata urls, one for each Holidaze collection.
 * If token holders explicitly unlock their tokens it will allow the image, metadata, and rarity
 * of that token to change.  Additionally, when a given token's metadata changes, it will affect
 * the overall rarity of the other tokens until the contract is locked after the last 
 * Holidaze collection url has been added.  Only once the contract has been locked will the true
 * rarities be available.
 * 
 * Each Holidaze collection will have completely different artwork, theme, traits, rarities, etc.,
 * but this will not impact any of the minted NFTs unless the token owner(s) explicitly unlock
 * their token.
 * 
 * Unlocking your token will result in the traits, image, etc. (and rarity) changing, so the result 
 * of unlocking is a gamble.
 * 
 * Tokens that an owner has previously unlocked can be re-locked, and the metadata and image will
 * be "locked" to whatever the most recent collection is
 */
function addHolidazeUrl(string calldata url, string calldata name) external onlyOwnerOrAdmin notLocked {
    require(bytes(url).length > 0, "Invalid url");
    require(bytes(name).length > 0, "Invalid name");
        
    _currentHolidazeUrlKey++;
        
    _holidazeUrls[_currentHolidazeUrlKey] = HolidazeUrlName(url, name);
        
    emit HolidazeUrlAdded(_currentHolidazeUrlKey, url, _msgSender());
}

/**
 * @dev Adds the specified metadata url and name for a new holidaze collection
 * @notice Any tokens that were explicitly unlocked by their owners - before this function
 * is called - will have their metadata urls change to use the specified value
 */