/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 * Copyright (C) 2003-2017 Apple Inc. All rights reserved.
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#pragma once

#include <WebCore/CSSStyleSheet.h>
#include <WebCore/CachedResourceHandle.h>
#include <WebCore/CachedStyleSheetClient.h>
#include <WebCore/DOMTokenList.h>
#include <WebCore/HTMLElement.h>
#include <WebCore/LinkLoader.h>
#include <WebCore/LinkLoaderClient.h>
#include <WebCore/LinkRelAttribute.h>
#include <wtf/CheckedPtr.h>

namespace WebCore {

class DOMTokenList;
class ExpectIdTargetObserver;
class HTMLLinkElement;
class Page;
struct MediaQueryParserContext;

enum class RequestPriority : uint8_t;

template<typename T, typename Counter> class EventSender;
using LinkEventSender = EventSender<HTMLLinkElement, WeakPtrImplWithEventTargetData>;

class HTMLLinkElement final : public HTMLElement, public CachedStyleSheetClient, public LinkLoaderClient {
    WTF_MAKE_TZONE_ALLOCATED(HTMLLinkElement);
    WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR(HTMLLinkElement);
public:
    USING_CAN_MAKE_WEAKPTR(HTMLElement);

    static Ref<HTMLLinkElement> create(const QualifiedName&, Document&, bool createdByParser);
    virtual ~HTMLLinkElement();

    // CachedResourceClient.
    void ref() const final { HTMLElement::ref(); }
    void deref() const final { HTMLElement::deref(); }

    URL href() const;
    WEBCORE_EXPORT const AtomString& NODELETE rel() const;

#if ENABLE(WEB_PAGE_SPATIAL_BACKDROP)
    URL environmentMap() const;
    bool isSpatialBackdrop() const { return m_relAttribute.isSpatialBackdrop; }
#endif

    AtomString target() const final;

    const AtomString& NODELETE type() const;

    std::optional<LinkIconType> NODELETE iconType() const;

    CSSStyleSheet* sheet() const { return m_sheet.get(); }

    bool NODELETE styleSheetIsLoading() const;

    bool isDisabled() const { return m_disabledState == Disabled; }
    bool isEnabledViaScript() const { return m_disabledState == EnabledViaScript; }
    DOMTokenList& sizes();

    WEBCORE_EXPORT bool mediaAttributeMatches() const;

    WEBCORE_EXPORT String crossOrigin() const;
    WEBCORE_EXPORT String as() const;

    void dispatchPendingEvent(LinkEventSender*, const AtomString& eventType);
    static void dispatchPendingLoadEvents(Page*);

    WEBCORE_EXPORT DOMTokenList& relList();
    WEBCORE_EXPORT DOMTokenList& blocking();

#if ENABLE(APPLICATION_MANIFEST)
    bool isApplicationManifest() const { return m_relAttribute.isApplicationManifest; }
#endif

    void allowPrefetchLoadAndErrorForTesting() { m_allowPrefetchLoadAndErrorForTesting = true; }

    String referrerPolicyForBindings() const;
    ReferrerPolicy referrerPolicy() const;

    String fetchPriorityForBindings() const;
    RequestPriority fetchPriority() const;

    // If element is specified, checks if that Element satisfies the link.
    // Otherwise checks if any Element in the tree does.
    void processInternalResourceLink(Element* = nullptr);

private:
    void attributeChanged(const QualifiedName&, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason) final;

    bool shouldLoadLink() final;
    void process();
    static void processCallback(Node*);
    void clearSheet();

    void potentiallyBlockRendering();
    void unblockRendering();
    bool NODELETE isImplicitlyPotentiallyRenderBlocking() const;

    NeedsPostConnectionSteps insertionSteps(InsertionType, ContainerNode&) final;
    void postConnectionSteps() final;
    void removingSteps(RemovalType, ContainerNode&) final;

    void initializeStyleSheet(Ref<StyleSheetContents>&&, const CachedCSSStyleSheet&, MediaQueryParserContext);

    // from CachedResourceClient
    void setCSSStyleSheet(const String& href, const URL& baseURL, ASCIILiteral charset, const CachedCSSStyleSheet*) final;
    bool sheetLoaded() final;
    void notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred) final;
    void startLoadingDynamicSheet() final;

    void linkLoaded() final;
    void linkLoadingErrored() final;

    bool isAlternate() const { return m_disabledState == Unset && m_relAttribute.isAlternate; }
    
    void setDisabledState(bool);

    bool NODELETE isURLAttribute(const Attribute&) const final;

    HTMLLinkElement(const QualifiedName&, Document&, bool createdByParser);

    void addSubresourceAttributeURLs(OrderedHashSet<URL>&) const final;

    void finishParsingChildren() final;

    String debugDescription() const final;

    enum class PendingSheetType : uint8_t { Unknown, Active, Inactive };
    void addPendingSheet(PendingSheetType);

    void removePendingSheet();

    const Ref<LinkLoader> m_linkLoader;
    CheckedPtr<Style::Scope> m_styleScope;
    CachedResourceHandle<CachedCSSStyleSheet> m_cachedSheet;
    RefPtr<CSSStyleSheet> m_sheet;
    enum DisabledState : uint8_t {
        Unset,
        EnabledViaScript,
        Disabled
    };

    String m_type;
    String m_media;
    String m_integrityMetadataForPendingSheetRequest;
    URL m_url;
#if ENABLE(WEB_PAGE_SPATIAL_BACKDROP)
    URL m_environmentMapURL;
#endif
    const std::unique_ptr<DOMTokenList> m_sizes;
    const std::unique_ptr<DOMTokenList> m_relList;
    const std::unique_ptr<DOMTokenList> m_blockingList;
    std::unique_ptr<ExpectIdTargetObserver> m_expectIdTargetObserver;
    DisabledState m_disabledState;
    LinkRelAttribute m_relAttribute;
    bool m_loading : 1;
    bool m_createdByParser : 1;
    bool m_loadedResource : 1;
    bool m_isHandlingBeforeLoad : 1;
    bool m_allowPrefetchLoadAndErrorForTesting : 1;
    bool m_isRenderBlocking : 1 { false };
    PendingSheetType m_pendingSheetType;
};

}
