/*
    Copyright (C) 2015 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301  USA.
*/

#include "siwebserviceclient.h"
#include "moc_siwebserviceclient.cpp"

#include "silibconfig.h"
#include "silibrary.h"
#include "siweatherstation.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonDocument>

using namespace SiWeather::Library;

SiWebserviceClient::SiWebserviceClient(QUrl baseUrl, QObject* parent)
	: QObject(parent)
{
	_baseUrl = baseUrl;
	_networkManager = new QNetworkAccessManager(this);
}

QString SiWebserviceClient::apiVersion()
{
	return QString(WEBSERVICE_API_VERSION);
}

SiWebserviceClient::ReplyType SiWebserviceClient::stationsRegister(const SiWeatherStation &station, QString &error)
{
	if(!_networkManager)
		return Error;

	if(station.name().isEmpty() || station.city().isEmpty() || station.eMail().isEmpty() || station.type().isEmpty()){
		error = tr("Station has empty name, city or eMail address. All of these are needed!");
		return Error;
	}
	
	QJsonObject jsonStation;
	jsonStation["name"] = station.name();
	jsonStation["city"] = station.city();
	jsonStation["longitude"] = Library::geoCoordinateToString(station.longitude());
	jsonStation["latitude"] = Library::geoCoordinateToString(station.latitude());
	jsonStation["email"] = station.eMail();
	jsonStation["type"] = station.type();
	jsonStation["typeUrl"] = station.typeUrl().toString();
	QJsonDocument jsonDocument(jsonStation);

	QNetworkRequest request;
	request.setUrl(QString("%1%2").arg(_baseUrl.toString()).arg("index.php/stations/register"));
	request.setRawHeader("User-Agent", QString("SiWeather Library %1").arg(Library::version()).toUtf8());
	request.setHeader(QNetworkRequest::ContentTypeHeader, 
    "application/json");
	QNetworkReply *reply = _networkManager->post(request, jsonDocument.toJson(QJsonDocument::Indented));
	connect(reply, SIGNAL(finished()),
					this, SLOT(replyStationsRegister()));
	return StationsRegister;
}

void SiWebserviceClient::replyStationsRegister()
{
	QNetworkReply *reply = getNetworkReply(sender(), StationsRegister);
	if(!reply)
		return;
	
	QByteArray data = reply->readAll();
	reply->deleteLater();

	QJsonDocument jsonDocument = QJsonDocument::fromJson(data);
	QJsonObject json = jsonDocument.object();
	if(!json.contains("result")){
		emit finishedStationsRegister(false, "", tr("No result in response found"));
		emit finished(StationsRegister, false, data);
		return;
	}
	if(json["result"].toString() != "success"){
		emit finishedStationsRegister(false, "", tr("Operation failed for reason: %1").arg(json["message"].toString()));
		emit finished(StationsRegister, false, data);
		return;
	}
	if(!json.contains("uuid")){
		emit finishedStationsRegister(false, "", tr("No uuid in response found"));
		emit finished(StationsRegister, false, data);
		return;
	}
	emit finishedStationsRegister(true, QUuid(json["uuid"].toString()), json["message"].toString());
	emit finished(StationsRegister, false, data);
}

QNetworkReply* SiWebserviceClient::getNetworkReply(QObject* sender, ReplyType type) const
{
	if(!sender){
		emit error(Error, tr("No sender object found"));
		return NULL;
	}
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender);
	if(!reply){
		emit error(Error, tr("No reply found"));
		return NULL;
	}

	if(reply->error() != QNetworkReply::NoError){
		emit error(type, reply->errorString());
		reply->deleteLater();
		return NULL;
	}

	return reply;
}
