/*
 * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2009 Torch Mobile, Inc.
 *
 * 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. 
 */

#include "config.h"
#include "CachedSVGFont.h"

#if ENABLE(SVG_FONTS)

#include "FontDescription.h"
#include "FontPlatformData.h"
#include "NoEventDispatchAssertion.h"
#include "NodeList.h"
#include "ResourceBuffer.h"
#include "SVGDocument.h"
#include "SVGElement.h"
#include "SVGFontData.h"
#include "SVGFontElement.h"
#include "SVGFontFaceElement.h"
#include "SVGGElement.h"
#include "SVGNames.h"
#include "SharedBuffer.h"
#include "TextResourceDecoder.h"
//#include "TypedElementDescendantIterator.h"

#if ENABLE(SVG_OTF_CONVERTER)
#include "SVGToOTFFontConversion.h"
#endif

namespace WebCore {

CachedSVGFont::CachedSVGFont(CachedResourceRequest& request)
    : CachedFont(request, SVGFontResource)
    , m_externalSVGFontElement(0)
{
}

PassRefPtr<SimpleFontData> CachedSVGFont::getFontData(const FontDescription& fontDescription, const AtomicString& remoteURI, bool syntheticBold, bool syntheticItalic)
{
#if ENABLE(SVG_OTF_CONVERTER)
    ASSERT(firstFontFace(remoteURI));
	return CachedFont::getFontData(fontDescription, remoteURI, syntheticBold, syntheticItalic/*, fontFaceFeatures, fontFaceVariantSettings*/);
#else
    //UNUSED_PARAM(fontFaceFeatures);
    //UNUSED_PARAM(fontFaceVariantSettings);
    if (SVGFontFaceElement* firstFontFace = this->firstFontFace(remoteURI))
        return SimpleFontData::create(SVGFontData::create(firstFontFace), fontDescription, syntheticBold, syntheticItalic);
    return nullptr;
#endif
}

bool CachedSVGFont::ensureCustomFontData(const AtomicString& remoteURI)
{
    if (!m_externalSVGDocument && !errorOccurred() && !isLoading() && m_data) {
    	bool sawError = false;
		{
            // We may get here during render tree updates when events are forbidden.
            // Frameless document can't run scripts or call back to the client so this is safe.
			m_externalSVGDocument = SVGDocument::create(0, url());
			RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");

            NoEventDispatchAssertion::EventAllowedScope allowedScope(*m_externalSVGDocument);

			m_externalSVGDocument->setContent(decoder->decodeAndFlush(m_data->data(), m_data->size()));
			sawError = decoder->sawError();
		}

        if (sawError)
            m_externalSVGDocument = 0;
#if ENABLE(SVG_OTF_CONVERTER)
        if (m_externalSVGDocument)
            maybeInitializeExternalSVGFontElement(remoteURI);
        if (!m_externalSVGFontElement || !firstFontFace(remoteURI))
            return false;
        if (auto convertedFont = convertSVGToOTFFont(*m_externalSVGFontElement))
            m_convertedFont = SharedBuffer::adoptVector(convertedFont.value());
        else {
            m_externalSVGDocument = nullptr;
            m_externalSVGFontElement = 0;
            return false;
        }
#else
        UNUSED_PARAM(remoteURI);
#endif
    }
#if !ENABLE(SVG_OTF_CONVERTER)
    return m_externalSVGDocument;
#else
    return m_externalSVGDocument && CachedFont::ensureCustomFontData(m_convertedFont.get());
#endif
}

SVGFontElement* CachedSVGFont::getSVGFontById(const String& fontName) const
{
    ASSERT(m_externalSVGDocument);
    RefPtr<NodeList> list = m_externalSVGDocument->getElementsByTagNameNS(SVGNames::fontTag.namespaceURI(), SVGNames::fontTag.localName());
    if (!list)
        return 0;

    unsigned listLength = list->length();
    if (!listLength)
        return 0;

#ifndef NDEBUG
    for (unsigned i = 0; i < listLength; ++i) {
        ASSERT(list->item(i));
        ASSERT(list->item(i)->hasTagName(SVGNames::fontTag));
    }
#endif

    if (fontName.isEmpty())
        return static_cast<SVGFontElement*>(list->item(0));

    for (unsigned i = 0; i < listLength; ++i) {
        SVGFontElement* element = static_cast<SVGFontElement*>(list->item(i));
        if (element->getIdAttribute() == fontName)
            return element;
    }

    return 0;
}

SVGFontElement* CachedSVGFont::maybeInitializeExternalSVGFontElement(const AtomicString& remoteURI)
{
    if (m_externalSVGFontElement)
        return m_externalSVGFontElement;
    String fragmentIdentifier;
    size_t start = remoteURI.find('#');
    if (start != notFound)
        fragmentIdentifier = remoteURI.string().substring(start + 1);
    m_externalSVGFontElement = getSVGFontById(fragmentIdentifier);
    return m_externalSVGFontElement;
}

SVGFontFaceElement* CachedSVGFont::firstFontFace(const AtomicString& remoteURI)
{
    if (!maybeInitializeExternalSVGFontElement(remoteURI))
        return 0;

    // Select first <font-face> child
    for (Node* fontChild = m_externalSVGFontElement->firstChild(); fontChild; fontChild = fontChild->nextSibling()) {
        if (fontChild->hasTagName(SVGNames::font_faceTag)) {
            return static_cast<SVGFontFaceElement*>(fontChild);
        }
    }

    return 0;
}

}

#endif
