/*
 * 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,
 * 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 "URLSearchParams.h"

#include "DOMURL.h"
#include "JSDOMConvertRecord.h"
#include "URLParser.h"

namespace WebCore {

inline URLSearchParams::URLSearchParams(const String& init, DOMURL* associatedURL)
	: m_associatedURL(makeWeakPtr(associatedURL))
    , m_pairs(init.startsWith('?') ? URLParser::parseURLEncodedForm(StringView(init).substring(1)) : URLParser::parseURLEncodedForm(init))
{
}

inline URLSearchParams::URLSearchParams(Vector<std::pair<String, String>>&& pairs)
    : m_pairs(WTFMove(pairs))
{
}

PassRefPtr<URLSearchParams> URLSearchParams::create(JSC::ExecState& state, JSC::JSValue init, ExceptionCode& ec)
{
	if(!init || init.isUndefinedOrNull())
		return adoptRef(new URLSearchParams(emptyString(), 0));

	auto& vm = state.vm();

	if(init.isObject()) {
		JSC::JSObject* object = JSC::asObject(init);

		// sequence<sequence<USVString>>
		if (hasIteratorMethod(state, object)) {
			Vector<Vector<String>> vector = toNativeArray<Vector<String>>(state, object);
			if(UNLIKELY(vm.exception()))
				return nullptr;

			Vector<std::pair<String, String>> pairs;
			pairs.reserveCapacity(vector.size());

			for(int i = 0 ; i < vector.size(); ++i) {
				auto& pair = vector[i];
				if (pair.size() != 2) {
					ec = TypeError;
					return nullptr;
				}

				pairs.uncheckedAppend(std::make_pair(pair[0], pair[1]));
			}

			return adoptRef(new URLSearchParams(WTFMove(pairs)));
		}

		// record<USVString, USVString>
		auto pairs = ConverterIDLRecord<String, String, Detail::IdentifierConverterIDLUSVString>::convert(state, init);
		if(UNLIKELY(vm.exception()))
			return nullptr;

		return adoptRef(new URLSearchParams(WTFMove(pairs)));
	}

	String string = valueToUSVString(state, init);
	if(UNLIKELY(vm.exception()))
		return nullptr;

	// USVString
	return adoptRef(new URLSearchParams(string, 0));
}

String URLSearchParams::get(const String& name) const
{
	for(int i = 0; i < m_pairs.size(); ++i) {
        if (m_pairs[i].first == name)
            return m_pairs[i].second;
    }
    return String();
}

bool URLSearchParams::has(const String& name) const
{
	for(int i = 0; i < m_pairs.size(); ++i) {
        if (m_pairs[i].first == name)
            return true;
    }
    return false;
}

void URLSearchParams::sort()
{
    std::stable_sort(m_pairs.begin(), m_pairs.end(), [] (const std::pair<String, String>& a, const std::pair<String, String>& b) {
        return WTF::codePointCompareLessThan(a.first, b.first);
    });
    updateURL();
}

void URLSearchParams::set(const String& name, const String& value)
{
	for(int i = 0; i < m_pairs.size(); ++i) {
		std::pair<String, String>& pair = m_pairs[i];
        if (pair.first != name)
            continue;
        if (pair.second != value)
            pair.second = value;
        for (int j = m_pairs.size() - 1; j > i; --j) { // remove remaining
            if (m_pairs[j].first == name)
            	m_pairs.remove(j);
        }
        updateURL();
        return;
    }
    m_pairs.append(std::make_pair(name, value));
    updateURL();
}

void URLSearchParams::append(const String& name, const String& value)
{
    m_pairs.append(std::make_pair(name, value));
    updateURL();
}

Vector<String> URLSearchParams::getAll(const String& name) const
{
    Vector<String> values;
    values.reserveInitialCapacity(m_pairs.size());
	for(int i = 0; i < m_pairs.size(); ++i) {
        if (m_pairs[i].first == name)
            values.uncheckedAppend(m_pairs[i].second);
    }
    return values;
}

void URLSearchParams::remove(const String& name)
{
    unsigned matchCount = 0;
    for (int i = m_pairs.size() - 1; i >= 0; --i) {
        if (m_pairs[i].first == name) {
        	m_pairs.remove(i);
        	++matchCount;
        }
	}

    if (matchCount)
        updateURL();
}

String URLSearchParams::toString() const
{
    return URLParser::serialize(m_pairs);
}

void URLSearchParams::updateURL()
{
    if (m_associatedURL)
        m_associatedURL->setQuery(URLParser::serialize(m_pairs));
}

void URLSearchParams::updateFromAssociatedURL()
{
    ASSERT(m_associatedURL);
    String search = m_associatedURL->search();
    m_pairs = search.startsWith('?') ? URLParser::parseURLEncodedForm(StringView(search).substring(1)) : URLParser::parseURLEncodedForm(search);
}

Optional<WTF::KeyValuePair<String, String>> URLSearchParams::Iterator::next()
{
	const Vector<std::pair<String, String>>& pairs = m_target->pairs();
    if (m_index >= pairs.size())
        return Nullopt;

    const std::pair<String, String>& pair = pairs[m_index++];
    return WTF::KeyValuePair<String, String>(pair.first, pair.second);
}

URLSearchParams::Iterator::Iterator(URLSearchParams& params)
    : m_target(&params)
	, m_index(0)
{
}

}
