#include "pqhttpformdata.h"
#include <QNetworkReply>

namespace PQ {

PQHttpFormData::PQHttpFormData(QObject *parent) : QHttpMultiPart(QHttpMultiPart::FormDataType,parent)
{

}

void PQHttpFormData::set(const QString & key,const QString & v)
{
    QHttpPart textPart;
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"").arg(key));
    textPart.setBody(v.toUtf8());
    this->append(textPart);
}

void PQHttpFormData::set(const QMap<QString,QString> & v)
{
    for(auto begin = v.begin(); begin != v.end(); ++begin){
        set(begin.key(),begin.value());
    }
}

void PQHttpFormData::set(const QHash<QString,QString> & v)
{
    for(auto begin = v.begin(); begin != v.end(); ++begin){
        set(begin.key(),begin.value());
    }
}

QString PQHttpFormData::contentType()
{
    return QString("multipart/form-data;boundary=%1").arg(QString(this->boundary()));
}

QNetworkReply * PQHttpFormData::postThis(QNetworkAccessManager * manger,QNetworkRequest & request)
{
    request.setHeader(QNetworkRequest::ContentTypeHeader,contentType());
    auto rep = manger->post(request,this);
    this->setParent(rep);
    return rep;
}

QNetworkReply * PQHttpFormData::putThis(QNetworkAccessManager * manger,QNetworkRequest & request)
{
    request.setHeader(QNetworkRequest::ContentTypeHeader,contentType());
    auto rep = manger->put(request,this);
    this->setParent(rep);
    return rep;
}

}
