/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2010, 2011, 2012 Apple 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.
 *
 */

#include "config.h"
#include "HTMLFormControlsCollection.h"

#include "HTMLFormControlElement.h"
#include "HTMLFormElement.h"
#include "HTMLImageElement.h"
#include "HTMLNames.h"
#include "JSHTMLFormControlsCollection.h"
#include "JSNode.h"
#include "JSRadioNodeList.h"
#include "ScriptDisallowedScope.h"

namespace WebCore {

using namespace HTMLNames;

// Since the collections are to be "live", we have to do the
// calculation every time if anything has changed.

inline HTMLFormControlsCollection::HTMLFormControlsCollection(ContainerNode* ownerNode, CollectionType type)
	: CachedHTMLCollection<HTMLFormControlsCollection, CollectionTypeTraits<FormControls>::traversalType>(ownerNode, FormControls)
    , m_cachedElement(0)
	, m_cachedElementOffsetInArray(0)
{
    ASSERT(ownerNode->hasTagName(formTag));
}

PassRefPtr<HTMLFormControlsCollection> HTMLFormControlsCollection::create(ContainerNode* ownerNode, CollectionType type)
{
    return adoptRef(new HTMLFormControlsCollection(ownerNode, type));
}

HTMLFormControlsCollection::~HTMLFormControlsCollection()
{
}

JSC::JSValue HTMLFormControlsCollection::namedItemOrItems(JSC::ExecState* exec, JSHTMLFormControlsCollection* collection, const String& name) const
{
    auto namedItems = this->namedItems(name);

    if (namedItems.isEmpty())
        return JSC::jsNull();
    if (namedItems.size() == 1)
        return toJS(exec, collection->globalObject(), namedItems[0].get());

    return toJS(exec, collection->globalObject(), ownerNode().radioNodeList(name).get());
}

static unsigned findFormAssociatedElement(const Vector<WeakPtr<HTMLElement>>& elements, const Element& element)
{
    for (unsigned i = 0; i < elements.size(); ++i) {
    	RefPtr<HTMLElement> currentElement = elements[i].get();
        ASSERT(currentElement);
        auto* associatedElement = currentElement->asFormAssociatedElement();
        ASSERT(associatedElement);
        if (associatedElement->isEnumeratable() && currentElement == &element)
            return i;
    }
    return elements.size();
}

Element* HTMLFormControlsCollection::customElementAfter(Element* current) const
{
    ScriptDisallowedScope::InMainThread scriptDisallowedScope;
    const Vector<WeakPtr<HTMLElement>>& elements = ownerNode().unsafeAssociatedElements();
    unsigned start;
    if (!current)
        start = 0;
    else if (m_cachedElement == current)
        start = m_cachedElementOffsetInArray + 1;
    else
        start = findFormAssociatedElement(elements, *current) + 1;

    for (unsigned i = start; i < elements.size(); ++i) {
    	RefPtr<HTMLElement> element = elements[i].get();
        ASSERT(element);
        ASSERT(element->asFormAssociatedElement());
        if (element->asFormAssociatedElement()->isEnumeratable()) {
            m_cachedElement = element.get();
            m_cachedElementOffsetInArray = i;
            return element.get();
        }
    }
    return 0;
}

static HTMLElement* firstNamedItem(const Vector<FormAssociatedElement*>& elementsArray,
    const Vector<WeakPtr<HTMLImageElement>>* imageElementsArray, const QualifiedName& attrName, const String& name)
{
    ASSERT(attrName == idAttr || attrName == nameAttr);

    for (unsigned i = 0; i < elementsArray.size(); ++i) {
        HTMLElement& element = elementsArray[i]->asHTMLElement();
        if (elementsArray[i]->isEnumeratable() && element.attributeWithoutSynchronization(attrName) == name)
            return &element;
    }

    if (!imageElementsArray)
        return 0;

    for (unsigned i = 0; i < imageElementsArray->size(); ++i) {
    	const WeakPtr<HTMLImageElement>& elementPtr = imageElementsArray->at(i);
        if (!elementPtr)
            continue;
        HTMLImageElement& element = *elementPtr;
        if (element.attributeWithoutSynchronization(attrName) == name)
            return &element;
    }

    return 0;
}

HTMLFormElement& HTMLFormControlsCollection::ownerNode() const
{
    return toHTMLFormElement(CachedHTMLCollection<HTMLFormControlsCollection, CollectionTypeTraits<FormControls>::traversalType>::ownerNode());
}

void HTMLFormControlsCollection::updateNamedElementCache() const
{
    if (hasNamedElementCache())
        return;

    OwnPtr<CollectionNamedElementCache> cache = adoptPtr(new CollectionNamedElementCache());

    HashSet<AtomicStringImpl*> foundInputElements;

    ScriptDisallowedScope::InMainThread scriptDisallowedScope;
    {
		const Vector<WeakPtr<HTMLElement>>& elementsArray = ownerNode().unsafeAssociatedElements();
		for (unsigned i = 0; i < elementsArray.size(); ++i) {
			const WeakPtr<HTMLElement>& weakElement = elementsArray[i];
	        RefPtr<HTMLElement> element = weakElement.get();
	        ASSERT(element);
	        auto* associatedElement = element->asFormAssociatedElement();
	        ASSERT(associatedElement);
	        if (associatedElement->isEnumeratable()) {
	            const AtomicString& id = element->getIdAttribute();
				if (!id.isEmpty()) {
					cache->appendToIdCache(id, *element);
					foundInputElements.add(id.impl());
				}
				const AtomicString& name = element->getNameAttribute();
				if (!name.isEmpty() && id != name) {
					cache->appendToNameCache(name, *element);
					foundInputElements.add(name.impl());
				}
			}
		}
    }

	auto& imageElementsArray = ownerNode().imageElements();
	for (unsigned i = 0; i < imageElementsArray.size(); ++i) {
		const WeakPtr<HTMLImageElement>& elementPtr = imageElementsArray[i];
		if (!elementPtr)
			continue;
		HTMLImageElement& element = *elementPtr;
		const AtomicString& id = element.getIdAttribute();
		if (!id.isEmpty() && !foundInputElements.contains(id.impl()))
			cache->appendToIdCache(id, element);
		const AtomicString& name = element.getNameAttribute();
		if (!name.isEmpty() && id != name && !foundInputElements.contains(name.impl()))
			cache->appendToNameCache(name, element);
	}

    setNamedItemCache(cache.release());
}

void HTMLFormControlsCollection::invalidateCacheForDocument(Document& document)
{
	CachedHTMLCollection<HTMLFormControlsCollection, CollectionTypeTraits<FormControls>::traversalType>::invalidateCacheForDocument(document);
	m_cachedElement = 0;
    m_cachedElementOffsetInArray = 0;
}

}
