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

#ifndef ResourceResponseBase_h
#define ResourceResponseBase_h

#include "CacheValidation.h"
#include "HTTPHeaderMap.h"
#include "KURL.h"
#include "ResourceLoadInfo.h"
#include "ResourceLoadTiming.h"

#include <wtf/PassOwnPtr.h>
#include <wtf/RefPtr.h>

#if OS(SOLARIS)
#include <sys/time.h> // For time_t structure.
#endif

namespace WebCore {

class ResourceResponse;
struct CrossThreadResourceResponseData;

// Do not use this class directly, use the class ResponseResponse instead
class ResourceResponseBase {
    WTF_MAKE_FAST_ALLOCATED;
public:
    static PassOwnPtr<ResourceResponse> adopt(PassOwnPtr<CrossThreadResourceResponseData>);

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

    enum class Tainting { Basic, Cors, Opaque };
    static ResourceResponse filterResponse(const ResourceResponse&, Tainting);

    ALWAYS_INLINE bool isNull() const { return m_isNull; }
    bool isHTTP() const;
    bool isSuccessful() const;

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

    const String& mimeType() const;
    void setMimeType(const String& mimeType);

    long long expectedContentLength() const;
    void setExpectedContentLength(long long expectedContentLength);

    ALWAYS_INLINE long long receivedContentLength() const { return m_receivedContentLength; }
    void setReceivedContentLength(long long receivedContentLength);
    
    const String& textEncodingName() const;
    void setTextEncodingName(const String& name);

    // FIXME should compute this on the fly
    const String& suggestedFilename() const;
    void setSuggestedFilename(const String&);

    int httpStatusCode() const;
    void setHTTPStatusCode(int);
    
    const String& httpStatusText() const;
    void setHTTPStatusText(const String&);
    
    String httpHeaderField(const String& name) const;
    String httpHeaderField(const ASCIILiteral& name) const;
    String httpHeaderField(HTTPHeaderName headerName) const
    {
    	StringView name = httpHeaderNameString(headerName);
    	return httpHeaderField(name.toStringWithoutCopying());
    }
    void setHTTPHeaderField(const ASCIILiteral&, const String& value);
    void setHTTPHeaderField(const String& name, const String& value);
    void setHTTPHeaderField(HTTPHeaderName headerName, const String& value)
    {
    	StringView name = httpHeaderNameString(headerName);
    	setHTTPHeaderField(name.toStringWithoutCopying(), value);
    }

    const HTTPHeaderMap& httpHeaderFields() const;

    bool isMultipart() const { return mimeType() == ASCIILiteral("multipart/x-mixed-replace"); }

    bool isAttachment() const;
    
    // FIXME: These are used by PluginStream on some platforms. Calculations may differ from just returning plain Last-odified header.
    // Leaving it for now but this should go away in favor of generic solution.
    void setLastModifiedDate(time_t);
    time_t lastModifiedDate() const; 

    // These functions return parsed values of the corresponding response headers.
    // NaN means that the header was not present or had invalid value.
    bool cacheControlContainsNoCache() const;
    bool cacheControlContainsNoStore() const;
    bool cacheControlContainsMustRevalidate() const;
    bool hasCacheValidatorFields() const;
    double cacheControlMaxAge() const;
    double date() const;
    double age() const;
    double expires() const;
    double lastModified() const;

    unsigned connectionID() const;
    void setConnectionID(unsigned);

    bool connectionReused() const;
    void setConnectionReused(bool);

    bool wasCached() const;
    void setWasCached(bool);

    ResourceLoadTiming* resourceLoadTiming() const;
    void setResourceLoadTiming(PassRefPtr<ResourceLoadTiming>);

    PassRefPtr<ResourceLoadInfo> resourceLoadInfo() const;
    void setResourceLoadInfo(PassRefPtr<ResourceLoadInfo>);

    // The ResourceResponse subclass may "shadow" this method to provide platform-specific memory usage information
    unsigned memoryUsage() const
    {
        // average size, mostly due to URL and Header Map strings
        return 1280;
    }

    enum class Type { Basic, Cors, Default, Error, Opaque, Opaqueredirect };
    Type type() const { return m_type; }
    void setType(Type type) { m_type = type; }
    bool isRedirected() const { return m_isRedirected; }
    void setRedirected(bool isRedirected) { m_isRedirected = isRedirected; }

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

protected:
    enum InitLevel {
        Uninitialized,
        CommonFieldsOnly,
        CommonAndUncommonFields,
        AllFields
    };

    ResourceResponseBase();
    ResourceResponseBase(const KURL& url, const String& mimeType, long long expectedLength, const String& textEncodingName, const String& filename);

    void lazyInit(InitLevel) const;

    // The ResourceResponse subclass may "shadow" this method to lazily initialize platform specific fields
    ALWAYS_INLINE void platformLazyInit(InitLevel) { }

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

    KURL m_url;
    String m_mimeType;
    long long m_expectedContentLength;
    long long m_receivedContentLength;
    String m_textEncodingName;
    String m_suggestedFilename;
    int m_httpStatusCode;
    String m_httpStatusText;
    HTTPHeaderMap m_httpHeaderFields;
    time_t m_lastModifiedDate;
    bool m_wasCached : 1;
    unsigned m_connectionID;
    bool m_connectionReused : 1;
    RefPtr<ResourceLoadTiming> m_resourceLoadTiming;
    RefPtr<ResourceLoadInfo> m_resourceLoadInfo;

    bool m_isNull : 1;
    
private:
    const ResourceResponse& asResourceResponse() const;
    void parseCacheControlDirectives() const;
    void parseDate() const;
    void parseLastModified() const;
    void parseAge() const;
    void parseExpires() const;

    mutable bool m_haveParsedCacheControlHeader : 1;
    mutable bool m_haveParsedAgeHeader : 1;
    mutable bool m_haveParsedDateHeader : 1;
    mutable bool m_haveParsedExpiresHeader : 1;
    mutable bool m_haveParsedLastModifiedHeader : 1;

    mutable double m_age;
    mutable double m_date;
    mutable double m_expires;
    mutable double m_lastModified;
    mutable CacheControlDirectives m_cacheControlDirectives;

    Type m_type;
    bool m_isRedirected;
};

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

#if 0
template<class Encoder>
void ResourceResponseBase::encode(Encoder& encoder) const
{
    encoder << m_isNull;
    if (m_isNull)
        return;
    lazyInit(AllFields);

    encoder << m_url;
    encoder << m_mimeType;
    encoder << static_cast<int64_t>(m_expectedContentLength);
    encoder << m_textEncodingName;
    encoder << m_httpStatusText;
    encoder << m_httpVersion;
    encoder << m_httpHeaderFields;
    encoder << m_resourceLoadTiming;
    encoder << m_httpStatusCode;
    encoder << m_includesCertificateInfo;
    if (m_includesCertificateInfo)
        encoder << m_certificateInfo;
    encoder.encodeEnum(m_source);
    encoder.encodeEnum(m_type);
    encoder << m_isRedirected;
}

template<class Decoder>
bool ResourceResponseBase::decode(Decoder& decoder, ResourceResponseBase& response)
{
    ASSERT(response.m_isNull);
    bool responseIsNull;
    if (!decoder.decode(responseIsNull))
        return false;
    if (responseIsNull)
        return true;

    if (!decoder.decode(response.m_url))
        return false;
    if (!decoder.decode(response.m_mimeType))
        return false;
    int64_t expectedContentLength;
    if (!decoder.decode(expectedContentLength))
        return false;
    response.m_expectedContentLength = expectedContentLength;
    if (!decoder.decode(response.m_textEncodingName))
        return false;
    if (!decoder.decode(response.m_httpStatusText))
        return false;
    if (!decoder.decode(response.m_httpVersion))
        return false;
    if (!decoder.decode(response.m_httpHeaderFields))
        return false;
    if (!decoder.decode(response.m_resourceLoadTiming))
        return false;
    if (!decoder.decode(response.m_httpStatusCode))
        return false;
    if (!decoder.decode(response.m_includesCertificateInfo))
        return false;
    if (response.m_includesCertificateInfo) {
        if (!decoder.decode(response.m_certificateInfo))
            return false;
    }
    if (!decoder.decodeEnum(response.m_source))
        return false;
    if (!decoder.decodeEnum(response.m_type))
        return false;
    if (!decoder.decode(response.m_isRedirected))
        return false;
    response.m_isNull = false;

    return true;
}
#endif

struct CrossThreadResourceResponseDataBase {
    WTF_MAKE_NONCOPYABLE(CrossThreadResourceResponseDataBase);
public:
    CrossThreadResourceResponseDataBase() { }
    KURL m_url;
    String m_mimeType;
    long long m_expectedContentLength;
    long long m_receivedContentLength;
    String m_textEncodingName;
    String m_suggestedFilename;
    int m_httpStatusCode;
    String m_httpStatusText;
    OwnPtr<CrossThreadHTTPHeaderMapData> m_httpHeaders;
    time_t m_lastModifiedDate;
    RefPtr<ResourceLoadTiming> m_resourceLoadTiming;
    ResourceResponseBase::Type m_type;
    bool m_isRedirected;
};

inline ResourceResponseBase::ResourceResponseBase()
    : m_expectedContentLength(0)
    , m_receivedContentLength(0)
    , m_httpStatusCode(0)
    , m_lastModifiedDate(0)
    , m_wasCached(false)
    , m_connectionID(0)
    , m_connectionReused(false)
    , m_isNull(true)
    , m_haveParsedCacheControlHeader(false)
    , m_haveParsedAgeHeader(false)
    , m_haveParsedDateHeader(false)
    , m_haveParsedExpiresHeader(false)
    , m_haveParsedLastModifiedHeader(false)
    , m_age(0.0)
    , m_date(0.0)
    , m_expires(0.0)
    , m_lastModified(0.0)
	, m_type(Type::Default)
	, m_isRedirected(false)
{
}

inline ResourceResponseBase::ResourceResponseBase(const KURL& url, const String& mimeType, long long expectedLength, const String& textEncodingName, const String& filename)
    : m_url(url)
    , m_mimeType(mimeType)
    , m_expectedContentLength(expectedLength)
    , m_receivedContentLength(0)
    , m_textEncodingName(textEncodingName)
    , m_suggestedFilename(filename)
    , m_httpStatusCode(0)
    , m_lastModifiedDate(0)
    , m_wasCached(false)
    , m_connectionID(0)
    , m_connectionReused(false)
    , m_isNull(false)
    , m_haveParsedCacheControlHeader(false)
    , m_haveParsedAgeHeader(false)
    , m_haveParsedDateHeader(false)
    , m_haveParsedExpiresHeader(false)
    , m_haveParsedLastModifiedHeader(false)
    , m_age(0.0)
    , m_date(0.0)
    , m_expires(0.0)
    , m_lastModified(0.0)
	, m_type(Type::Default)
	, m_isRedirected(false)
{
}

#if USE(CURL)
ALWAYS_INLINE void ResourceResponseBase::lazyInit(InitLevel) const
{	
}

ALWAYS_INLINE bool ResourceResponseBase::isHTTP() const
{
    lazyInit(CommonFieldsOnly);
    return m_url.protocolIsInHTTPFamily();
}

ALWAYS_INLINE const KURL& ResourceResponseBase::url() const
{
    lazyInit(CommonFieldsOnly);

    return m_url; 
}

ALWAYS_INLINE void ResourceResponseBase::setURL(const KURL& url)
{
    lazyInit(CommonFieldsOnly);
    m_isNull = false;

    m_url = url; 
}

ALWAYS_INLINE const String& ResourceResponseBase::mimeType() const
{
    lazyInit(CommonFieldsOnly);

    return m_mimeType; 
}

ALWAYS_INLINE void ResourceResponseBase::setMimeType(const String& mimeType)
{
    lazyInit(CommonFieldsOnly);
    m_isNull = false;

    m_mimeType = mimeType; 
}

ALWAYS_INLINE long long ResourceResponseBase::expectedContentLength() const
{
    lazyInit(CommonFieldsOnly);

    return m_expectedContentLength;
}

ALWAYS_INLINE void ResourceResponseBase::setExpectedContentLength(long long expectedContentLength)
{
    lazyInit(CommonFieldsOnly);
    m_isNull = false;

    m_expectedContentLength = expectedContentLength; 
}

ALWAYS_INLINE const String& ResourceResponseBase::textEncodingName() const
{
    lazyInit(CommonFieldsOnly);

    return m_textEncodingName;
}

ALWAYS_INLINE void ResourceResponseBase::setTextEncodingName(const String& encodingName)
{
    lazyInit(CommonFieldsOnly);
    m_isNull = false;

    m_textEncodingName = encodingName; 
}

// FIXME should compute this on the fly
ALWAYS_INLINE const String& ResourceResponseBase::suggestedFilename() const
{
    lazyInit(AllFields);

    return m_suggestedFilename;
}

ALWAYS_INLINE void ResourceResponseBase::setSuggestedFilename(const String& suggestedName)
{
    lazyInit(AllFields);
    m_isNull = false;

    m_suggestedFilename = suggestedName; 
}

ALWAYS_INLINE bool ResourceResponseBase::isSuccessful() const
{
    int code = httpStatusCode();
    return code >= 200 && code < 300;
}

ALWAYS_INLINE int ResourceResponseBase::httpStatusCode() const
{
    lazyInit(CommonFieldsOnly);

    return m_httpStatusCode;
}

ALWAYS_INLINE void ResourceResponseBase::setHTTPStatusCode(int statusCode)
{
    lazyInit(CommonFieldsOnly);

    m_httpStatusCode = statusCode;
}

ALWAYS_INLINE const HTTPHeaderMap& ResourceResponseBase::httpHeaderFields() const
{
    lazyInit(CommonAndUncommonFields);

    return m_httpHeaderFields;
}

#endif

ALWAYS_INLINE bool ResourceResponseBase::cacheControlContainsNoCache() const
{
    if (!m_haveParsedCacheControlHeader)
        parseCacheControlDirectives();
    return m_cacheControlDirectives.noCache;
}

ALWAYS_INLINE bool ResourceResponseBase::cacheControlContainsNoStore() const
{
    if (!m_haveParsedCacheControlHeader)
        parseCacheControlDirectives();
    return m_cacheControlDirectives.noStore;
}

ALWAYS_INLINE bool ResourceResponseBase::cacheControlContainsMustRevalidate() const
{
    if (!m_haveParsedCacheControlHeader)
        parseCacheControlDirectives();
    return m_cacheControlDirectives.mustRevalidate;
}

ALWAYS_INLINE double ResourceResponseBase::cacheControlMaxAge() const
{
    if (!m_haveParsedCacheControlHeader)
        parseCacheControlDirectives();
    return m_cacheControlDirectives.maxAge;
}

ALWAYS_INLINE void ResourceResponseBase::setLastModifiedDate(time_t lastModifiedDate)
{
    lazyInit(CommonAndUncommonFields);

    m_lastModifiedDate = lastModifiedDate;
}

ALWAYS_INLINE time_t ResourceResponseBase::lastModifiedDate() const
{
    lazyInit(CommonAndUncommonFields);

    return m_lastModifiedDate;
}

ALWAYS_INLINE double ResourceResponseBase::date() const
{
    lazyInit(CommonFieldsOnly);

    if (!m_haveParsedDateHeader)
    	parseDate();

    return m_date;
}

ALWAYS_INLINE double ResourceResponseBase::age() const
{
    lazyInit(CommonFieldsOnly);

    if (!m_haveParsedAgeHeader)
    	parseAge();

    return m_age;
}

ALWAYS_INLINE double ResourceResponseBase::expires() const
{
    lazyInit(CommonFieldsOnly);

    if (!m_haveParsedExpiresHeader)
    	parseExpires();

    return m_expires;
}

ALWAYS_INLINE double ResourceResponseBase::lastModified() const
{
    lazyInit(CommonFieldsOnly);

    if (!m_haveParsedLastModifiedHeader)
    	parseLastModified();

    return m_lastModified;
}

ALWAYS_INLINE bool ResourceResponseBase::wasCached() const
{
    lazyInit(CommonAndUncommonFields);

    return m_wasCached;
}

ALWAYS_INLINE void ResourceResponseBase::setWasCached(bool value)
{
    m_wasCached = value;
}

ALWAYS_INLINE bool ResourceResponseBase::connectionReused() const
{
    lazyInit(CommonAndUncommonFields);

    return m_connectionReused;
}

ALWAYS_INLINE void ResourceResponseBase::setConnectionReused(bool connectionReused)
{
    lazyInit(CommonAndUncommonFields);

    m_connectionReused = connectionReused;
}

ALWAYS_INLINE unsigned ResourceResponseBase::connectionID() const
{
    lazyInit(CommonAndUncommonFields);

    return m_connectionID;
}

ALWAYS_INLINE void ResourceResponseBase::setConnectionID(unsigned connectionID)
{
    lazyInit(CommonAndUncommonFields);

    m_connectionID = connectionID;
}

ALWAYS_INLINE const String& ResourceResponseBase::httpStatusText() const
{
    lazyInit(CommonAndUncommonFields);

    return m_httpStatusText;
}

ALWAYS_INLINE void ResourceResponseBase::setHTTPStatusText(const String& statusText)
{
    lazyInit(CommonAndUncommonFields);

    m_httpStatusText = statusText;
}

ALWAYS_INLINE String ResourceResponseBase::httpHeaderField(const String& name) const
{
    lazyInit(CommonFieldsOnly);

    // If we already have the header, just return it instead of consuming memory by grabing all headers.
    String value = m_httpHeaderFields.get(name);
    if (!value.isEmpty())
        return value;

    lazyInit(CommonAndUncommonFields);

    return m_httpHeaderFields.get(name);
}

ALWAYS_INLINE String ResourceResponseBase::httpHeaderField(const ASCIILiteral& name) const
{
    lazyInit(CommonFieldsOnly);

    // If we already have the header, just return it instead of consuming memory by grabing all headers.
    String value = m_httpHeaderFields.get(name);
    if (!value.isEmpty())
        return value;

    lazyInit(CommonAndUncommonFields);

    return m_httpHeaderFields.get(name);
}

ALWAYS_INLINE void ResourceResponseBase::setHTTPHeaderField(const ASCIILiteral& name, const String& value)
{
	setHTTPHeaderField(String(name), value);
}

} // namespace WebCore

#endif // ResourceResponseBase_h
