/*
 * Copyright (C) 2003, 2006 Apple Computer, Inc.  All rights reserved.
 * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
 * Copyright (C) 2009, 2012 Google 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 COMPUTER, 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 COMPUTER, 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 "FormData.h"
#include "HTTPHeaderMap.h"
#include "KURL.h"
#include "ResourceLoadPriority.h"

#include <wtf/OwnPtr.h>

namespace WebCore {

enum ResourceRequestCachePolicy : uint8_t {
    UseProtocolCachePolicy, // normal load, equivalent to fetch "default" cache mode.
    ReloadIgnoringCacheData, // reload, equivalent to fetch "reload"cache mode.
    ReturnCacheDataElseLoad, // back/forward or encoding change - allow stale data, equivalent to fetch "force-cache" cache mode.
    ReturnCacheDataDontLoad, // results of a post - allow stale data and only use cache, equivalent to fetch "only-if-cached" cache mode.
    DoNotUseAnyCache, // Bypass the cache entirely, equivalent to fetch "no-store" cache mode.
    RefreshAnyCacheData, // Serve cache data only if revalidated, equivalent to fetch "no-cache" mode.
};

class ResourceRequest;
struct CrossThreadResourceRequestData;

// Do not use this type directly.  Use ResourceRequest instead.
class ResourceRequestBase {
	WTF_MAKE_FAST_ALLOCATED;
public:
	static PassOwnPtr<ResourceRequest> adopt(PassOwnPtr<CrossThreadResourceRequestData>);

	// Gets a copy of the data suitable for passing to another thread.
	PassOwnPtr<CrossThreadResourceRequestData> copyData() const;

	bool isNull() const;
	bool isEmpty() const;

	const KURL& url() const;
	void setURL(const KURL& url);

	void removeCredentials();

	ResourceRequestCachePolicy cachePolicy() const;
	void setCachePolicy(ResourceRequestCachePolicy cachePolicy);

	double timeoutInterval() const; // May return 0 when using platform default.
	void setTimeoutInterval(double timeoutInterval);

	const KURL& firstPartyForCookies() const;
	void setFirstPartyForCookies(const KURL& firstPartyForCookies);

	const String& httpMethod() const;
	void setHTTPMethod(const String& httpMethod);

	const HTTPHeaderMap& httpHeaderFields() const;
	String httpHeaderField(const String& name) const;
	String httpHeaderField(const ASCIILiteral& name) const;
	String httpHeaderField(HTTPHeaderName headerName) const;
	void setHTTPHeaderField(const String& name, const String& value);
	void setHTTPHeaderField(const ASCIILiteral& name, const String& value);
	void setHTTPHeaderField(HTTPHeaderName headerName, const String& value);
	void setHTTPHeaderFields(const HTTPHeaderMap& headerFields);
	void addHTTPHeaderField(const String& name, const String& value);
	void addHTTPHeaderField(HTTPHeaderName headerName, const String& value);
	void addHTTPHeaderFields(const HTTPHeaderMap& headerFields);
	void addHTTPHeaderFieldIfNotPresent(HTTPHeaderName, const String&);

	bool hasHTTPHeaderField(HTTPHeaderName) const;

	void clearHTTPAuthorization();

	ALWAYS_INLINE String httpContentType() const { return httpHeaderField(HTTPHeaderName::ContentType);  }
	ALWAYS_INLINE void setHTTPContentType(const String& httpContentType) { setHTTPHeaderField(HTTPHeaderName::ContentType, httpContentType); }
	void clearHTTPContentType();

	bool hasHTTPHeader(HTTPHeaderName) const;

	ALWAYS_INLINE String httpReferrer() const { return httpHeaderField(HTTPHeaderName::Referer); }
	bool hasHTTPReferrer() const;
	ALWAYS_INLINE void setHTTPReferrer(const String& httpReferrer) { setHTTPHeaderField(HTTPHeaderName::Referer, httpReferrer); }
	void clearHTTPReferrer();

	ALWAYS_INLINE String httpOrigin() const { return httpHeaderField(HTTPHeaderName::Origin); }
	bool hasHTTPOrigin() const;
	ALWAYS_INLINE void setHTTPOrigin(const String& httpOrigin) { setHTTPHeaderField(HTTPHeaderName::Origin, httpOrigin); }
	void clearHTTPOrigin();

	ALWAYS_INLINE String httpUserAgent() const { return httpHeaderField(HTTPHeaderName::UserAgent); }
	ALWAYS_INLINE void setHTTPUserAgent(const String& httpUserAgent) { setHTTPHeaderField(HTTPHeaderName::UserAgent, httpUserAgent); }
	void clearHTTPUserAgent();

	ALWAYS_INLINE String httpAccept() const { return httpHeaderField(HTTPHeaderName::Accept); }
	ALWAYS_INLINE void setHTTPAccept(const String& httpAccept) { setHTTPHeaderField(HTTPHeaderName::Accept, httpAccept); }
	void clearHTTPAccept();

	void clearHTTPAcceptEncoding();

	const Vector<String>& responseContentDispositionEncodingFallbackArray() const { return m_responseContentDispositionEncodingFallbackArray; }
	void setResponseContentDispositionEncodingFallbackArray(const String& encoding1, const String& encoding2 = String(), const String& encoding3 = String());

	FormData* httpBody() const;
	void setHTTPBody(PassRefPtr<FormData> httpBody);

	bool allowCookies() const;
	void setAllowCookies(bool allowCookies);

	ResourceLoadPriority priority() const;
	void setPriority(ResourceLoadPriority);

    WEBCORE_EXPORT static String partitionName(const String& domain);

	bool isConditional() const;
	void makeUnconditional();

	// Whether the associated ResourceHandleClient needs to be notified of
	// upload progress made for that resource.
	bool reportUploadProgress() const { return m_reportUploadProgress; }
	void setReportUploadProgress(bool reportUploadProgress) { m_reportUploadProgress = reportUploadProgress; }

	// Whether the timing information should be collected for the request.
	bool reportLoadTiming() const { return m_reportLoadTiming; }
	void setReportLoadTiming(bool reportLoadTiming) { m_reportLoadTiming = reportLoadTiming; }

	// Whether actual headers being sent/received should be collected and reported for the request.
	bool reportRawHeaders() const { return m_reportRawHeaders; }
	void setReportRawHeaders(bool reportRawHeaders) { m_reportRawHeaders = reportRawHeaders; }

	static bool compare(const ResourceRequest&, const ResourceRequest&);

protected:
	// Used when ResourceRequest is initialized from a platform representation of the request
	ALWAYS_INLINE ResourceRequestBase()
		: m_cachePolicy(UseProtocolCachePolicy)
		, m_timeoutInterval(0)
		, m_allowCookies(true)
		, m_resourceRequestUpdated(false)
		, m_platformRequestUpdated(true)
		, m_reportUploadProgress(false)
		, m_reportLoadTiming(false)
		, m_reportRawHeaders(false)
		, m_priority(ResourceLoadPriorityLow)
	{
	}

	ALWAYS_INLINE ResourceRequestBase(const KURL& url, ResourceRequestCachePolicy policy)
		: m_url(url)
		, m_cachePolicy(policy)
		, m_timeoutInterval(0)
		, m_httpMethod(ASCIILiteral("GET"))
		, m_allowCookies(true)
		, m_resourceRequestUpdated(true)
		, m_platformRequestUpdated(false)
		, m_reportUploadProgress(false)
		, m_reportLoadTiming(false)
		, m_reportRawHeaders(false)
		, m_priority(ResourceLoadPriorityLow)
	{
	}

	void updatePlatformRequest() const;
	void updateResourceRequest() const;

	// The ResourceRequest subclass may "shadow" this method to compare platform specific fields
	static bool platformCompare(const ResourceRequest&, const ResourceRequest&) { return true; }

	KURL m_url;

	double m_timeoutInterval; // 0 is a magic value for platform default on platforms that have one.
	KURL m_firstPartyForCookies;
	String m_httpMethod;
	HTTPHeaderMap m_httpHeaderFields;
	Vector<String> m_responseContentDispositionEncodingFallbackArray;
	RefPtr<FormData> m_httpBody;
	unsigned m_cachePolicy : 3;
	unsigned m_allowCookies : 1;
	mutable unsigned m_resourceRequestUpdated : 1;
	mutable unsigned m_platformRequestUpdated : 1;
	unsigned m_reportUploadProgress : 1;
	unsigned m_reportLoadTiming : 1;
	unsigned m_reportRawHeaders : 1;
	unsigned m_priority : 4;

private:
	const ResourceRequest& asResourceRequest() const;
};

bool equalIgnoringHeaderFields(const ResourceRequestBase&, const ResourceRequestBase&);

// FIXME: Find a better place for these functions.
inline String toRegistrableDomain(const KURL& a)
{
    auto host = a.host().toString();
    auto registrableDomain = ResourceRequestBase::partitionName(host);
    // Fall back to the host if we cannot determine the registrable domain.
    return registrableDomain.isEmpty() ? host : registrableDomain;
}

inline bool registrableDomainsAreEqual(const KURL& a, const KURL& b)
{
    return toRegistrableDomain(a) == toRegistrableDomain(b);
}
inline bool registrableDomainsAreEqual(const KURL& a, const String& registrableDomain)
{
    return toRegistrableDomain(a) == registrableDomain;
}

ALWAYS_INLINE bool operator==(const ResourceRequest& a, const ResourceRequest& b) { return ResourceRequestBase::compare(a, b); }
ALWAYS_INLINE bool operator!=(ResourceRequest& a, const ResourceRequest& b) { return !(a == b); }

struct CrossThreadResourceRequestDataBase {
	WTF_MAKE_NONCOPYABLE(CrossThreadResourceRequestDataBase); WTF_MAKE_FAST_ALLOCATED;
public:
	CrossThreadResourceRequestDataBase() { }
	KURL m_url;

	ResourceRequestCachePolicy m_cachePolicy;
	double m_timeoutInterval;
	KURL m_firstPartyForCookies;

	String m_httpMethod;
	OwnPtr<CrossThreadHTTPHeaderMapData> m_httpHeaders;
	Vector<String> m_responseContentDispositionEncodingFallbackArray;
	RefPtr<FormData> m_httpBody;
	bool m_allowCookies;
	ResourceLoadPriority m_priority;
};

unsigned initializeMaximumHTTPConnectionCountPerHost();

#if USE(CURL)
ALWAYS_INLINE void ResourceRequestBase::updatePlatformRequest() const
{
    m_platformRequestUpdated = true;
}

ALWAYS_INLINE void ResourceRequestBase::updateResourceRequest() const
{
    m_resourceRequestUpdated = true;
}

ALWAYS_INLINE FormData* ResourceRequestBase::httpBody() const
{ 
    updateResourceRequest(); 
    
    return m_httpBody.get(); 
}

ALWAYS_INLINE const String& ResourceRequestBase::httpMethod() const
{
    updateResourceRequest(); 
    
    return m_httpMethod; 
}

ALWAYS_INLINE const HTTPHeaderMap& ResourceRequestBase::httpHeaderFields() const
{
    updateResourceRequest(); 

    return m_httpHeaderFields; 
}

ALWAYS_INLINE const KURL& ResourceRequestBase::url() const
{
    updateResourceRequest(); 
    
    return m_url;
}

ALWAYS_INLINE void ResourceRequestBase::setURL(const KURL& url)
{ 
    updateResourceRequest(); 

    m_url = url;     
    m_platformRequestUpdated = false;
}

ALWAYS_INLINE String ResourceRequestBase::httpHeaderField(const String& name) const
{
    updateResourceRequest();

    return m_httpHeaderFields.get(name);
}

ALWAYS_INLINE String ResourceRequestBase::httpHeaderField(const ASCIILiteral& name) const
{
    updateResourceRequest();

    return m_httpHeaderFields.get(name);
}

ALWAYS_INLINE String ResourceRequestBase::httpHeaderField(HTTPHeaderName headerName) const
{
    updateResourceRequest();

    return m_httpHeaderFields.get(headerName);
}

ALWAYS_INLINE ResourceRequestCachePolicy ResourceRequestBase::cachePolicy() const
{
    updateResourceRequest();

    return static_cast<ResourceRequestCachePolicy>(m_cachePolicy);
}

ALWAYS_INLINE const KURL& ResourceRequestBase::firstPartyForCookies() const
{
    updateResourceRequest();

    return m_firstPartyForCookies;
}

ALWAYS_INLINE double ResourceRequestBase::timeoutInterval() const
{
    updateResourceRequest();

    return m_timeoutInterval;
}

ALWAYS_INLINE ResourceLoadPriority ResourceRequestBase::priority() const
{
    updateResourceRequest();

    return static_cast<ResourceLoadPriority>(m_priority);
}
#endif

inline bool ResourceRequestBase::hasHTTPHeader(HTTPHeaderName name) const
{
    return m_httpHeaderFields.contains(name);
}

inline bool ResourceRequestBase::hasHTTPHeaderField(HTTPHeaderName headerName) const
{
    return m_httpHeaderFields.contains(headerName);
}

} // namespace WebCore
