/*
 * Copyright (C) 2016 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include "ActiveDOMObject.h"
#include "CSSFontFaceSet.h"
#include "DOMCoreException.h"
#include "DOMPromiseProxy.h"
#include "EventTarget.h"
#include "FontFaceSetLoadStatus.h"
#include "JSDOMPromiseDeferred.h"
#include <wtf/Optional.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

class Document;
class FontFace;

class FontFaceSet FINAL : public RefCounted<FontFaceSet>, private CSSFontFaceSet::FontEventClient, public EventTargetWithInlineData, public ActiveDOMObject {
public:
	using LoadStatus = FontFaceSetLoadStatus;

    static Ref<FontFaceSet> create(Document*, const Vector<RefPtr<FontFace>>&);
    static Ref<FontFaceSet> create(Document*, CSSFontFaceSet& backing);
    virtual ~FontFaceSet();

    bool has(FontFace&) const;
    size_t size();
    FontFaceSet* add(FontFace&);
    bool remove(FontFace&);
    void clear();

    void load(const String& font, const String& text, RefPtr<DeferredPromise> promise);
    bool check(const String& font, const String& text, ExceptionCode&);
    
    String status() const;

    typedef DOMPromiseProxyWithResolveCallback<FontFaceSet> ReadyPromise;
    ReadyPromise& ready() { return m_readyPromise; }
    void documentDidFinishLoading();

    CSSFontFaceSet& backing() { return m_backing; }

    class Iterator {
    public:
        explicit Iterator(FontFaceSet&);
        RefPtr<FontFace> next();
    private:
        RefPtr<FontFaceSet> m_target;
        size_t m_index; // FIXME: There needs to be a mechanism to handle when fonts are added or removed from the middle of the FontFaceSet.
    };
    Iterator createIterator() { return Iterator(*this); }

    using RefCounted<FontFaceSet>::ref;
    using RefCounted<FontFaceSet>::deref;

    virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE { return ActiveDOMObject::scriptExecutionContext(); }

private:
    struct PendingPromise : public RefCounted<PendingPromise> {
        typedef DOMPromiseDeferred<Vector<RefPtr<FontFace>>, ExceptionCode> Promise;
        static PassRefPtr<PendingPromise> create(Promise promise)
        {
            return adoptRef(new PendingPromise(promise));
        }
        ~PendingPromise();

    private:
        PendingPromise(Promise);

    public:
        Vector<RefPtr<FontFace>> faces;
        Promise promise;
        bool hasReachedTerminalState;
    };

    FontFaceSet(Document&, const Vector<RefPtr<FontFace>>&);
    FontFaceSet(Document&, CSSFontFaceSet&);

    // CSSFontFaceSet::FontEventClient
    virtual void faceFinished(CSSFontFace&, CSSFontFace::Status) FINAL;
    virtual void startedLoading() FINAL;
    virtual void completedLoading() FINAL;

    // ActiveDOMObject
    virtual const char* activeDOMObjectName() const FINAL { return "FontFaceSet"; }
    virtual bool canSuspendForDocumentSuspension() const FINAL;

    // EventTarget
    virtual EventTargetInterface eventTargetInterface() const FINAL { return FontFaceSetEventTargetInterfaceType; }
    virtual void refEventTarget() FINAL { ref(); }
    virtual void derefEventTarget() FINAL { deref(); }

    FontFaceSet& readyPromiseResolve();

    Ref<CSSFontFaceSet> m_backing;
    HashMap<RefPtr<FontFace>, Vector<RefPtr<PendingPromise>>> m_pendingPromises;
    ReadyPromise m_readyPromise;

    bool m_isDocumentLoaded;
};

}
