/*
 * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
 * Copyright (C) 2004, 2005, 2006, 2008 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 "CSSParserSelector.h"

#include "CSSCustomPropertyValue.h"
#include "CSSParserIdioms.h"
#include "CSSPrimitiveValue.h"
#include "CSSFunctionValue.h"
#include "CSSParser.h"
#include "CSSSelector.h"
#include "CSSSelectorList.h"
#include "SelectorPseudoTypeMap.h"
#include <wtf/text/StringBuilder.h>

namespace WebCore {

using namespace WTF;

PassOwnPtr<CSSParserSelector> CSSParserSelector::parsePagePseudoSelector(const AtomicString& pseudoTypeString)
{
    CSSSelector::PagePseudoClassType pseudoType;
    if (equalLettersIgnoringASCIICase(pseudoTypeString.string(), "first"))
        pseudoType = CSSSelector::PagePseudoClassFirst;
    else if (equalLettersIgnoringASCIICase(pseudoTypeString.string(), "left"))
        pseudoType = CSSSelector::PagePseudoClassLeft;
    else if (equalLettersIgnoringASCIICase(pseudoTypeString.string(), "right"))
        pseudoType = CSSSelector::PagePseudoClassRight;
    else
        return nullptr;

    OwnPtr<CSSParserSelector> selector = adoptPtr(new CSSParserSelector());
    selector->m_selector->setMatch(CSSSelector::PagePseudoClass);
    selector->m_selector->setPagePseudoType(pseudoType);
    return selector.release();
}

PassOwnPtr<CSSParserSelector> CSSParserSelector::parsePseudoElementSelectorFromStringView(StringView& pseudoTypeString)
{
    AtomicString name = pseudoTypeString.toAtomicString();

    CSSSelector::PseudoElementType pseudoType = CSSSelector::parsePseudoElementType(name);
    if (pseudoType == CSSSelector::PseudoElementUnknown)
        return nullptr;

    OwnPtr<CSSParserSelector> selector = adoptPtr(new CSSParserSelector());
    selector->m_selector->setMatch(CSSSelector::PseudoElement);
    selector->m_selector->setPseudoElementType(pseudoType);
    if (pseudoType == CSSSelector::PseudoElementWebKitCustomLegacyPrefixed) {
        ASSERT_WITH_MESSAGE(name == "-webkit-input-placeholder", "-webkit-input-placeholder is the only LegacyPrefix pseudo type.");
        if (name == "-webkit-input-placeholder")
            name = AtomicString("placeholder", AtomicString::ConstructFromLiteral);
    }
    selector->m_selector->setValue(name);
    return selector.release();
}

PassOwnPtr<CSSParserSelector> CSSParserSelector::parsePseudoClassSelectorFromStringView(StringView& pseudoTypeString)
{
    PseudoClassOrCompatibilityPseudoElement pseudoType = parsePseudoClassAndCompatibilityElementString(pseudoTypeString);
    if (pseudoType.pseudoClass != CSSSelector::PseudoClassUnknown) {
    	OwnPtr<CSSParserSelector> selector = adoptPtr(new CSSParserSelector());
        selector->m_selector->setMatch(CSSSelector::PseudoClass);
        selector->m_selector->setPseudoClassType(pseudoType.pseudoClass);
        return selector.release();
    }
    if (pseudoType.compatibilityPseudoElement != CSSSelector::PseudoElementUnknown) {
    	OwnPtr<CSSParserSelector> selector = adoptPtr(new CSSParserSelector());
        selector->m_selector->setMatch(CSSSelector::PseudoElement);
        selector->m_selector->setPseudoElementType(pseudoType.compatibilityPseudoElement);
        AtomicString name = pseudoTypeString.toAtomicString();
        selector->m_selector->setValue(name);
        return selector.release();
    }
    return nullptr;
}

int gCSSParserSelectorCount;

CSSParserSelector::CSSParserSelector()
    : m_selector(adoptPtr(new CSSSelector()))
{
	++gCSSParserSelectorCount;
}

CSSParserSelector::CSSParserSelector(const QualifiedName& tagQName)
    : m_selector(adoptPtr(new CSSSelector(tagQName)))
{
	++gCSSParserSelectorCount;
}

CSSParserSelector::~CSSParserSelector()
{
	--gCSSParserSelectorCount;
    if (!m_tagHistory)
        return;
    Vector<OwnPtr<CSSParserSelector>, 16> toDelete;
    OwnPtr<CSSParserSelector> selector = m_tagHistory.release();
    while (true) {
        OwnPtr<CSSParserSelector> next = selector->m_tagHistory.release();
        toDelete.append(selector.release());
        if (!next)
            break;
        selector = next.release();
    }
}

void CSSParserSelector::adoptSelectorVector(Vector<OwnPtr<CSSParserSelector>>&& selectorVector)
{
    OwnPtr<CSSSelectorList> selectorList = adoptPtr(new CSSSelectorList());
    selectorList->adoptSelectorVector(WTFMove(selectorVector));
    m_selector->setSelectorList(selectorList.release());
}


void CSSParserSelector::setArgumentList(PassOwnPtr<Vector<AtomicString>> argumentList)
{
    ASSERT_WITH_MESSAGE(!argumentList->isEmpty(), "No CSS Selector takes an empty argument list.");
    m_selector->setArgumentList(argumentList);
}

void CSSParserSelector::setSelectorList(PassOwnPtr<CSSSelectorList> selectorList)
{
    m_selector->setSelectorList(selectorList);
}

bool CSSParserSelector::isSimple() const
{
    if (m_selector->selectorList() || m_selector->matchesPseudoElement())
        return false;

    if (!m_tagHistory)
        return true;

    if (m_selector->m_match == CSSSelector::Tag) {
        // We can't check against anyQName() here because namespace may not be nullAtom.
        // Example:
        //     @namespace "http://www.w3.org/2000/svg";
        //     svg:not(:root) { ...
        if (m_selector->tagQName().localName() == starAtom)
            return m_tagHistory->isSimple();
    }

    return false;
}

static bool selectorListMatchesPseudoElement(const CSSSelectorList* selectorList)
{
    if (!selectorList)
        return false;

    for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
        for (const CSSSelector* selector = subSelector; selector; selector = selector->tagHistory()) {
            if (selector->matchesPseudoElement())
                return true;
            if (const CSSSelectorList* subselectorList = selector->selectorList()) {
                if (selectorListMatchesPseudoElement(subselectorList))
                    return true;
            }
        }
    }
    return false;
}

bool CSSParserSelector::matchesPseudoElement() const
{
    return m_selector->matchesPseudoElement() || selectorListMatchesPseudoElement(m_selector->selectorList());
}

void CSSParserSelector::insertTagHistory(CSSSelector::RelationType before, PassOwnPtr<CSSParserSelector> selector, CSSSelector::RelationType after)
{
    if (m_tagHistory)
        selector->setTagHistory(m_tagHistory.release());
    setRelation(before);
    selector->setRelation(after);
    m_tagHistory = selector;
}

void CSSParserSelector::appendTagHistory(CSSSelector::RelationType relation, PassOwnPtr<CSSParserSelector> selector)
{
    CSSParserSelector* end = this;
    while (end->tagHistory())
        end = end->tagHistory();

    end->setRelation(relation);
    end->setTagHistory(selector);
}

void CSSParserSelector::appendTagHistory(CSSParserSelectorCombinator relation, PassOwnPtr<CSSParserSelector> selector)
{
    CSSParserSelector* end = this;
    while (end->tagHistory())
        end = end->tagHistory();

    CSSSelector::RelationType selectorRelation;
    switch (relation) {
    case CSSParserSelectorCombinator::Child:
        selectorRelation = CSSSelector::Child;
        break;
    case CSSParserSelectorCombinator::DescendantSpace:
        selectorRelation = CSSSelector::DescendantSpace;
        break;
    case CSSParserSelectorCombinator::DirectAdjacent:
        selectorRelation = CSSSelector::DirectAdjacent;
        break;
    case CSSParserSelectorCombinator::IndirectAdjacent:
        selectorRelation = CSSSelector::IndirectAdjacent;
        break;
    }
    end->setRelation(selectorRelation);
    end->setTagHistory(selector);
}

void CSSParserSelector::prependTagSelector(const QualifiedName& tagQName, bool tagIsForNamespaceRule)
{
    OwnPtr<CSSParserSelector> second = adoptPtr(new CSSParserSelector);
    second->m_selector = m_selector.release();
    second->m_tagHistory = m_tagHistory.release();
    m_tagHistory = second.release();

    m_selector = adoptPtr(new CSSSelector(tagQName, tagIsForNamespaceRule));
    m_selector->m_relation = CSSSelector::Subselector;
}

PassOwnPtr<CSSParserSelector> CSSParserSelector::releaseTagHistory()
{
    setRelation(CSSSelector::Subselector);
    return m_tagHistory.release();
}

// FIXME-NEWPARSER: Add support for :host-context
bool CSSParserSelector::isHostPseudoSelector() const
{
    return match() == CSSSelector::PseudoClass && pseudoClassType() == CSSSelector::PseudoClassHost;
}

}

