#include <httpsocket.h>

int getIntParam(const std::string& s, const std::string& key)
{
    int p = s.find(key);
    if (p < 0)
        return 0;
    else
    {
        std::string sval = s.substr(p + key.length());
        int p = sval.find("\r\n");
        sval = sval.substr(0, p);
        
        return atoi(sval.c_str());
    }
}

std::string getStringParam(const std::string& s, const std::string& key)
{
    std::string param("");
    
    int p = s.find(key);
    if (p >= 0)
    {
        param = s.substr(p + key.length());
        int p = param.find("\r\n");
        param = param.substr(0, p);
    }
    
    return param;
}

int HttpSocket::get(const char *path, const char *referer, const char *cookie)
{
    std::string request = "GET " + std::string(path) + " HTTP/1.0\n";
    if (referer)
        request += "Referer: " + std::string(referer) + "\n";
    request += "Connection: Keep-Alive\n";
    request += "User-Agent: Mozilla [en] (Linux)\n";
    request += "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*\n";
    request += "Accept-Language: en\n";
    request += "Accept-Charset: iso-8859-1,*,utf-8\n";
    if (cookie)
        request += "Cookie:" + std::string(cookie) + "\n";
    
    request += "\n";

  return write(request.c_str(), request.length());
}

int HttpSocket::post(const char* host, const char *topage, const char *referer, const char *cookie, 
    const char *content)
{
    return -1;
}

std::string HttpSocket::readResponse()
{
    // read until the header is complete; get content length
    char buff[1024];
    std::string header = "";
    std::string content = "";
    int contentLength;
    
    for (;;)
    {
        int bytesRead = read(buff, sizeof(buff) - 1);
        if (bytesRead >= 0)
        {
            buff[bytesRead] = 0;
            header += buff;
            int p = header.find("\r\n\r\n");
            if (p > 0)
            {
                content = header.substr(p + 4);
                header = header.substr(0, p);
                break;
            } 
        }
        else
            break;
    }
    
    //printf("\n---Header---\n%s\n------------\n", header.c_str());
    
    std::string te = getStringParam(header, "Transfer-Encoding: ");
    contentLength = getIntParam(header, "Content-Length: ");
    /*if (!contentLength) 
    {
        fprintf(stderr, "Cannot determine content length\n");
        content.clear();
        return content;
    }*/
    
    // read the content
    while (content.length() < contentLength || contentLength == 0)
    {
        int bytesRead = read(buff, sizeof(buff) - 1);
        if (bytesRead >= 0)
        {
            buff[bytesRead] = 0;
            content += buff;
            if (bytesRead == 0)
                break;
        }
        else
        {
            //fprintf(stderr, "Error reading page content\n");
            content.clear();
            break;
        }
            
    }
    
    return content;
}

