//
// C++ Interface: net_httpsocket
//
// Description:
//
//
// Author: Matthias Feistel <hitman_47@users.sourceforge.net>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//


#include "net_httpsocket.h"
#include "config.h"
#include "settings.h"


//--- My_HttpGetSocket is a derivation of HttpGetSocket; in the original class,$
My_HttpGetSocket::My_HttpGetSocket(ISocketHandler& h,const std::string& url_in, const std::string& to_file) : HttpGetSocket(h, url_in)
{
    if (to_file.size())
    {
        SetFilename(to_file);
    }

    if (!Open(GetUrlHost(),GetUrlPort()))
    {
        if (!Connecting())
        {
            Handler().LogError(this, "HttpGetSocket", -1, "connect() failed miserably", LOG_LEVEL_FATAL);
            SetCloseAndDelete();
        }
    }
}


void My_HttpGetSocket::OnConnect()
{
    SetMethod( "GET" );
    AddResponseHeader( "User-agent", PLUGIN_NAME"/"PLUGIN_VERSION );
    AddResponseHeader( "Cookie", cSettings::GetInstance().GetCookie() );
    SendRequest();
}


void My_HttpGetSocket::OnHeader(const std::string& key,const std::string& value)
{
    if ( ( !strcmp(key.c_str(), "Set-Cookie") ) && ( strcmp(value.c_str(), "") )
            && (!value.empty() ) )
    {
        std::string s, previous_cookie;
        char buff[4096];

        previous_cookie = cSettings::GetInstance().GetCookie();
        s = value.substr(0, value.find(";") + 1);

        snprintf(buff, sizeof(buff), "%s %s", s.c_str(), previous_cookie.c_str() );
        cSettings::GetInstance( ).SetCookie( buff );
    }

    HttpGetSocket::OnHeader(key, value);  //original-Funktion aufrufen, um restliche Werte setzen zu lassen
}
