//
// URLRequest.cpp
//

#define DBG_LEVEL 0
#include <Raym/Log.h>
#include <Raym/URLRequest.h>

namespace Raym
{

#define RELEASE(P1)         \
    if ((P1) != NULL)       \
    {                       \
        (P1)->release();    \
        (P1) = NULL;        \
    }

URLRequest::URLRequest()
{
    DebugLog2("URLRequest::URLRequest()\n");

    _url         = NULL;
    _HTTPMethod  = NULL;
    _HTTPHeaderFields = NULL;
}

URLRequest::~URLRequest()
{
    DebugLog2("URLRequest::~URLRequest()\n");

    RELEASE(_url);
    RELEASE(_HTTPMethod);
    RELEASE(_HTTPHeaderFields);
}

URLRequest *URLRequest::alloc()
{
    DebugLog2("URLRequest::alloc()\n");

    return new URLRequest();
}

URLRequest *URLRequest::requestWithURL(URL *theURL)
{
    DebugLog2("URLRequest::requestWithURL()\n");

    URLRequest *result = URLRequest::alloc()->initWithURL(theURL);
    if (result != NULL)
    {
        result->autorelease();
    }
    return result;
}

URLRequest *URLRequest::initWithURL(URL *theURL)
{
    DebugLog2("URLRequest::initWithURL()\n");

    if (theURL != NULL)
    {
        _url = theURL;
        _url->retain();
        if (_url->scheme()->isEqualToString("http"))
        {
            _HTTPMethod = String::alloc()->initWithUTF8String("GET");
            _HTTPHeaderFields = Dictionary::alloc()->initWithCapacity(0);
            _HTTPHeaderFields->setString(_url->host(), "Host");
            _HTTPHeaderFields->setString("close", "Connection");
            _HTTPHeaderFields->setString("Mozilla/5.0 AppleWebKit/600.1.1.7", "User-Agent");
            _HTTPHeaderFields->setString("*/*", "Accept");
            if (_url->password() != NULL)
            {
                String *credentials = String::stringWithFormat("%s:%s", ((_url->user() == NULL) ? "" : _url->user()->cString()), _url->password()->cString());
                String *value = String::stringWithFormat("Basic %s", String::base64StringWithBytes(credentials->cString(), credentials->length())->cString());
                _HTTPHeaderFields->setString(value, "Authorization");
            }
        }
    }
    else
    {
        DebugLog0("warnning: theURL is NULL\n");
        return NULL;
    }

    return this;
}

String *URLRequest::HTTPMethod()
{
    return _HTTPMethod;
}

URL *URLRequest::url()
{
    return _url;
}
Dictionary *URLRequest::allHTTPHeaderFields()
{
    return _HTTPHeaderFields;
}

void URLRequest::addValueForHTTPHeaderField(const char *value, const char *field)
{
    if ((value != NULL) && (field != NULL))
    {
        _HTTPHeaderFields->setString(value, field);
    }
}

const char *URLRequest::className()
{
    return "URLRequest";
}

} // Raym
