/*
    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 "stationsregister.h"
#include "moc_stationsregister.cpp"

#include "inputoutputhandler.h"
#include "siweatherclientconfig.h"

#include <siweatherstation.h>

#include <QCoreApplication>

using namespace SiWeather::Library;

StationsRegister::StationsRegister(QObject* parent)
	: QObject(parent)
{
	_ioHandler = new InputOutputHandler(this);
}

void StationsRegister::registerStation()
{
	registerStation(SiWeatherStation());
}

void StationsRegister::webserviceError(SiWeather::Library::SiWebserviceClient::ReplyType replyType, const QString& message)
{
	if(replyType != SiWebserviceClient::StationsRegister)
		return;

	*_ioHandler << "      "+ tr("FAILED") << endl;
	*_ioHandler << "  "+ message << endl;
	
	QString result = getValue(tr("Do you want to change the station and try it again? (Y/n)"), "Y");
	if(result != "Y"){
		*_ioHandler << tr("Aborting!") << endl;
		qApp->quit();
		return;
	}
	registerStation(_lastStation);
}

void StationsRegister::webserviceFinished(bool result, const QUuid& stationUuid, const QString& message)
{
	if(!result){
		*_ioHandler << "      "+ tr("FAILED") << endl;
		*_ioHandler << "  "+ message << endl;
		QString result = getValue(tr("Do you want to change the station and try it again? (Y/n)"), "Y");
		if(result != "Y"){
			*_ioHandler << tr("Aborting!") << endl;
			qApp->quit();
			return;
		}
		registerStation(_lastStation);
		return;
	}
	
	*_ioHandler << "      "+ tr("SUCCESS") << endl;
	*_ioHandler << "  "+ tr("Registered station with uuid %1").arg(stationUuid.toString()) << endl;
	*_ioHandler << "  "+ message << endl;
	qApp->quit();
}

void StationsRegister::registerStation(SiWeatherStation station)
{
	if(!_ioHandler)
		return;

	QUrl baseUrl(QString(WEBSERVICE_BASE_URL));

	*_ioHandler << tr("Please enter some data to describe your station") << endl;
	
	station.setName(getValue(tr("Name"), station.name()));
	station.setCity(getValue(tr("City"), station.city()));
	station.setLatitude(getCoordinate(tr("Latitude"), station.latitude()).toDouble());
	station.setLongitude(getCoordinate(tr("Longitude"), station.longitude()).toDouble());
	
	station.setEMail(getValue(tr("Your E-Mail Address"), station.eMail()));
	QString defaultType = "siweatherstation 1";
	if(!station.type().isEmpty())
		defaultType = station.type();
	station.setType(getValue(tr("Type, describing your station"), defaultType));
	station.setTypeUrl(getValue(tr("Url with information about your type (optional)"), station.typeUrl().toString()));
	
	*_ioHandler << tr("Your station is defined as follows:") << endl;
	_ioHandler->setFieldWidth(20);
	*_ioHandler << endl;
	*_ioHandler << tr("Name:") << station.name() << endl;
	*_ioHandler << tr("City:") << station.city() << endl;
	*_ioHandler << tr("Latitude:") << coordinateToString(station.latitude()) << endl;
	*_ioHandler << tr("Longitude:") << coordinateToString(station.longitude()) << endl;
	*_ioHandler << tr("Type:") << station.type() << endl;
	*_ioHandler << tr("Type Url:") << station.typeUrl().toString() << endl;
	*_ioHandler << tr("E-Mail:") << station.eMail() << endl;
	_ioHandler->setFieldWidth(0);
	*_ioHandler << endl;

	if(!station.isValidForRegister()){
		*_ioHandler << tr("Your station is not valid for register at the webservice.") << endl;
		*_ioHandler << tr("This means, the name, city, e-mail address or type is empty.") << endl;
		QString result = getValue(tr("Do you want to change the station? (Y/n)"), "Y");
		if(result != "Y"){
			*_ioHandler << tr("Aborting!") << endl;
			qApp->quit();
			return;
		}
		registerStation(station);
		return;
	}
	else{
		QString result = getValue(tr("Do you want to register this station at %1? (Y/e/n)").arg(baseUrl.host()), "n");
		if(result != "Y"){
			if(result == "e"){
				registerStation(station);
				return;
			}

			*_ioHandler << tr("Aborting!") << endl;
			qApp->quit();
			return;
		}
		*_ioHandler << tr("Registering station...");
		
		SiWebserviceClient *client = new SiWebserviceClient(baseUrl, this);
		connect(client, SIGNAL(error(SiWeather::Library::SiWebserviceClient::ReplyType, const QString&)),
						this, SLOT(webserviceError(SiWeather::Library::SiWebserviceClient::ReplyType,QString)));
		connect(client, SIGNAL(finishedStationsRegister(bool, const QUuid&, const QString&)),
						this, SLOT(webserviceFinished(bool,QUuid,QString)));
		QString errorMessage;
		if(client->stationsRegister(station, errorMessage) != SiWebserviceClient::StationsRegister){
			*_ioHandler << "      "+ tr("FAILED") << endl;
			*_ioHandler << "  "+ errorMessage << endl;
			qApp->quit();
			return;
		}
		_lastStation = station;
	}
}

QString StationsRegister::getValue(const QString& label, const QString& defaultValue)
{
	if(!_ioHandler)
		return QString();

	QString defaultValueLabel;
	if(!defaultValue.isEmpty())
		defaultValueLabel = QString(" [%1]").arg(defaultValue);
	*_ioHandler << label + defaultValueLabel +": ";
	QString value = _ioHandler->readLine();
	if(value.isEmpty())
		value = defaultValue;
	return value;
}

QString StationsRegister::getCoordinate(const QString& type, double defaultValue)
{
	if(!_ioHandler)
		return QString();

	QString coordinate = getValue(tr("%1 (at least 4 digits, point as separator)").arg(type), coordinateToString(defaultValue));
	if(coordinate.length() - coordinate.indexOf(".") < 5){
		*_ioHandler << tr("Your %1 does not contain 4 digits. Try it again!").arg(type) << endl;
		return getCoordinate(type, defaultValue);
	}
	return coordinate;
}

QString StationsRegister::coordinateToString(double coordinate) const
{
	return QString::number(coordinate, 'f', 4);
}
