/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>
#include <QBuffer>
#include <QFile>
#include <QXmlQuery>
#include <QXmlResultItems>

#include "MvQOgcServiceManager.h"

MvQOgcServiceManager::MvQOgcServiceManager(QString configFile)
{
	configFile_=configFile;
	readConfig();
}

MvQOgcServiceManager::~MvQOgcServiceManager()
{	
	writeConfig();
}

void MvQOgcServiceManager::addWms(MvQOgcServer* server)
{
	server_.push_back(server);
}

void MvQOgcServiceManager::clearWms()
{
	foreach(MvQOgcServer* server,server_)
	{
		delete server;
	}
	server_.clear();
}


void MvQOgcServiceManager::writeConfig()
{	
	//Open file for writing
	QFile out(configFile_);
	out.open(QFile::WriteOnly | QFile::Text);

	QString s;

	s="<Service type=\"WMS\">\n";
	out.write(s.toUtf8());

	foreach(MvQOgcServer* server,server_)
	{
		s="\t<Server shortName=\"" + server->shortName() +"\"";
		out.write(s.toUtf8());

		s=" url=\"" + server->url() + "\">\n";
		out.write(s.toUtf8());

		foreach(QString version,server->versions())
		{
			s="\t\t<Version>" + version + "</Version>\n";
			out.write(s.toUtf8());
		}
		s="\t</Server>\n";
		out.write(s.toUtf8());
	}

	s="</Service>\n";
	out.write(s.toUtf8());

	out.close();
}

void MvQOgcServiceManager::readConfig()
{
	QFile file(configFile_);
	if(file.open(QFile::ReadOnly | QFile::Text) == false)
		return;

	QString xmlConf(file.readAll());

	QXmlResultItems result;

	QByteArray ba=xmlConf.toUtf8();
	QBuffer buffer(&ba) ; // This is a QIODevice.
    	buffer.open(QIODevice::ReadOnly);

	QXmlQuery query;
     	query.bindVariable("myDoc", &buffer);
	query.setQuery("doc($myDoc)//Service[@type = \"WMS\"]/Server");
	query.evaluateTo(&result);
	
	QXmlItem item(result.next());
     	while (!item.isNull()) 
	{
         	if (item.isNode()) 
		{		
			QString shortName,url;
			QStringList lst;

			//QXmlQuery query;
			query.setFocus(item);

			//shortName
			query.setQuery("string(./@shortName)");
			query.evaluateTo(&shortName);
			shortName=shortName.simplified();

			//url
			query.setQuery("string(./@url)");
			query.evaluateTo(&url);
			url=url.simplified();
				
			//Name
			QXmlResultItems versionResult;
			query.setQuery("./data(Version)");
			query.evaluateTo(&versionResult);
			getAtomicValues(versionResult,lst);	

			qDebug() << "Versions: " << lst;
			
			server_.push_back(new MvQOgcServer(shortName,url,lst));

                 }
		item = result.next();
        }

	file.close();
}

int MvQOgcServiceManager::findServerByUrl(QString url)
{
	for(unsigned int i=0; i < server_.count(); i++)
	{ 	
		if(server_[i]->url() == url)
		{
			return i;
		}
	}
	return -1;
}

void MvQOgcServiceManager::getAtomicValues(QXmlResultItems &result,QStringList &lst)
{
	QXmlItem item(result.next());
     	while (!item.isNull()) 
	{
        	qDebug() << item.isNode() <<  item.isAtomicValue() << item.toAtomicValue();

		if (item.isAtomicValue()) 
		{
             		QVariant v = item.toAtomicValue();
             		lst << v.toString();
		}
         	item = result.next();
         }
}