
/*---------------------------------------------------------------------------*/
/* http_query_args.cpp                                                       */
/* copyright (c) innovaphone 2016                                            */
/*                                                                           */
/*---------------------------------------------------------------------------*/

#include <platform.h>
#include "../ilib/str.h"


#include "../ilib/http_query_args.h"

NAMESPACE_BEGIN

HttpQueryArg::HttpQueryArg()
{
    this->name = NULL;
    this->value = NULL;
}

HttpQueryArgs::HttpQueryArgs(char * query)
{
    this->query = query;
    this->pos = strchr(this->query, '?');   // find the start of the query arguments
    if (this->pos) {
        this->pos++;                        // jump to the first parameter, which must start after the first ?
        char * hash = strchr(this->pos, '#');
        if (hash) {                         // a hash is the end of query args
            *hash = '\0';
        }
    }
    else {
        this->pos = this->query;
    }
    this->Next();
}

class HttpQueryArg * HttpQueryArgs::Reset()
{
    current.value = NULL;
    current.name = NULL;
    return NULL;
}

class HttpQueryArg * HttpQueryArgs::Current()
{
    if (current.value && current.name) return &current;
    return NULL;
}

class HttpQueryArg * HttpQueryArgs::Next()
{
    if (!pos) return Reset();
    current.name = pos;
    pos = strchr(pos, '=');
    if (!pos) return Reset();
    *pos = '\0';                        // replace '=' with a terminating \0 for name
    current.value = ++pos;
    if (*pos) {                         // value is set
        pos = strchr(pos, '&');         // find next param to terminate value
        if (pos) {
            *pos = '\0';                // replace '&' with a terminating \0 for value
            pos++;
        }
        str::from_url(current.value);
    }
    return &current;
}

NAMESPACE_END
