/***************************** 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 <QApplication>
#include <QBuffer>
#include <QDateTime>
#include <QDebug>
#include <QDomDocument>
#include <QFile>

#include <QAbstractXmlNodeModel>
#include <QAuthenticator>
#include <QNetworkReply>
#include <QXmlFormatter>
#include <QXmlResultItems>

#include "MvQNetworkAccessManager.h"
#include "MvQOgcRequest.h"
#include "MvQXmlQuery.h"

#include "MvQWcsClient.h"

#include "LogHandler.h"

#include "mars.h"

//==============================
//
// Base client
//
//==============================

MvQWcsClientBase::MvQWcsClientBase()
{
    supportedMimeType_ << "image/png"
                       << "image/jpeg"
                       << "image/gif";  // "image/svg+xml";

    supportedCrs_ << "EPSG:4326"
                  << "CRS:84";
}

QString MvQWcsClientBase::getMimeType(QByteArray ba)
{
    qDebug() << "fileType" << ba.mid(0, 8).toHex();

    if (ba.mid(0, 8).toHex() == "89504e470d0a1a0a") {
        return "image/png";
    }
    else if (ba.mid(0, 4).toHex() == "ffd8ffe0") {
        return "image/jpeg";
    }
    else if (ba.mid(0, 6) == "GIF87a" ||
             ba.mid(0, 6) == "GIF89a") {
        return "image/gif";
    }

    return QString("text/plain");
}


QString MvQWcsClientBase::getRequestedMimeType(QString r)
{
    MvQGetCoverageRequest req;
    req.setRequest(r);
    return req.item("FORMAT");
}

//==============================
//
// Download/batch client
//
//==============================

MvQWcsGetClient::MvQWcsGetClient(MvRequest& req) :
    reqInfo_(req)
{
    getCovRunStatus_ = false;

    getCovRequest_ = new MvQGetCoverageRequest;

    const char* mode = (const char*)reqInfo_("_ACTION");
    if (!mode)
        return;


    QStringList timeDimName;
    const char* tdn = (const char*)reqInfo_("TIME_DIMENSIONS");
    if (tdn) {
        QString s(tdn);
        timeDimName = s.split("/");
    }

    getCovRequest_->setRequest(QString((const char*)reqInfo_("REQUEST")));

    //Prepare
    /*if(strcmp(mode,"prepare") == 0)
	{		
		MvRequest ctx=reqInfo_("_CONTEXT");
		ctx.print();
		const char* proj= (const char*)ctx("MAP_PROJECTION");
		//const char* area= (const char*)ctx("AREA");

		const char* area= (const char*)ctx("AREA");

		int cnt = ctx.countValues("AREA");
		double dval; 
	 	QStringList areaL;
		for(int i=0; i< cnt; i++)
	       	{
			ctx.getValue(dval,"AREA",i);
	 		areaL << QString::number(dval);
		}
	 
		if(!proj || areaL.count() != 4)
		{
			return;
		}
		
		if(strcmp(proj,"CYLINDRICAL") == 0)
		{
			if(getCovRequest_->crs() == "CRS:84" || 
			   getCovRequest_->crs() == "EPSG:4326")
			{
				//s,w,n,e
				qDebug() << "area" << areaL;							
				getCovRequest_->setItem("BBOX",
				    areaL[1] +"," + areaL[0] + "," + areaL[3] + "," + areaL[2]);
			}
		}
	}*/


    //Network access
    networkGetCov_ = new MvQNetworkAccessManager(this);
    getCovReply_   = 0;

    connect(networkGetCov_, SIGNAL(replyReadyToProcess(QNetworkReply*)),
            this, SLOT(slotReplyGetCov(QNetworkReply*)));
}

MvQWcsGetClient::~MvQWcsGetClient()
{
    delete networkGetCov_;
}

void MvQWcsGetClient::runGetCov()
{
    outFile_.clear();

    getCovRunStatus_ = false;
    downloadGetCov();
}

void MvQWcsGetClient::downloadGetCov()
{
    getCovReply_ = networkGetCov_->get(QNetworkRequest(QUrl(getCovRequest_->request())));
}

void MvQWcsGetClient::slotReplyGetCov(QNetworkReply* reply)
{
    QNetworkRequest r = reply->request();
    QUrl url          = r.url();

    qDebug() << url.toString();

    QString mimeType = reply->header(QNetworkRequest::ContentTypeHeader).toString();

    //LogItem *log=new LogItem;
    //LogHandler::instance()->add(log);
    //log->description("Load GetCov");

    if (reply->error() != QNetworkReply::NoError) {
        QString ems = "GetCov request failed!\nError: ";
        ems += reply->errorString();
        marslog(LOG_EROR, "GetCov request failed!\nError: %s ", reply->errorString().toStdString().c_str());
        //log->error(reply->errorString().toStdString() + "\n");
        QApplication::exit();
    }
    else {
        // temporary file
        QString outFile;
        outFile = marstmp();

        getCovRequest_->setOutFile(outFile);

        QByteArray ba = reply->readAll();

        if (mimeType.isEmpty())
            mimeType = getMimeType(ba);

        //If exception is returned or mime type is
        //different to what was requested
        if (mimeType.contains("application/vnd.ogc.se_xml") ||
            !mimeType.contains(getRequestedMimeType(url.toString()))) {
            QString eMsg;
            //readException(ba,eMsg);

            QApplication::exit();
        }

        QFile out(outFile);
        out.open(QIODevice::WriteOnly);
        out.write(ba);
        out.close();

        getCovRunStatus_ = true;
        QApplication::exit();
    }

    reply->deleteLater();
    getCovReply_ = 0;
}


//=================================
//
// Client for the user interface
//
//=================================

MvQWcsUiClient::MvQWcsUiClient(string& iconFile, MvRequest& req) :
    iconFile_(QString::fromStdString(iconFile)),
    reqInfo_(req)
{
    getCovRequest_     = new MvQGetCoverageRequest;
    lastGetCovRequest_ = new MvQGetCoverageRequest;

    // Initialize elements from Metview request
    url_     = QString((const char*)reqInfo_("SERVER"));
    version_ = (const char*)reqInfo_("VERSION");

    QStringList timeDimName;

    const char* tdn = (const char*)reqInfo_("TIME_DIMENSIONS");
    if (tdn) {
        QString s(tdn);
        timeDimName = s.split("/");
    }

    getCovRequest_->setRequest(QString((const char*)reqInfo_("REQUEST")));

    clientMode_ = BasicMode;
    if ((const char*)reqInfo_("MODE") != 0) {
        QString m(reqInfo_("MODE"));
        if (m == "EXPERT")
            clientMode_ = BasicMode;
        else
            clientMode_ = AdvancedMode;
    }


    if ((const char*)reqInfo_("EXTRA_GETCAP_PAR") != 0) {
        extraGetCapPar_ = QString(reqInfo_("EXTRA_GETCAP_PAR"));
    }

    if ((const char*)reqInfo_("EXTRA_GETMAP_PAR") != 0) {
        extraGetCovPar_ = QString(reqInfo_("EXTRA_GETMAP_PAR"));
    }

    if ((const char*)reqInfo_("HTTP_USER") != 0) {
        httpUser_ = QString(reqInfo_("HTTP_USER"));
    }

    if ((const char*)reqInfo_("HTTP_PASSWORD") != 0) {
        httpPassword_ = QString(reqInfo_("HTTP_PASSWORD"));
    }


    qDebug() << "Init:" << url_ << version_ << getCovRequest_;

    //Width
    width_      = new MvQOgcIntValue(1024, "WIDTH", "Width:");
    QString val = getCovRequest_->item(width_->requestName());
    if (!val.isEmpty())
        width_->setValue(val.toInt());

    //Height
    height_ = new MvQOgcIntValue(512, "HEIGHT", "Height:");
    val     = getCovRequest_->item(height_->requestName());
    if (!val.isEmpty())
        height_->setValue(val.toInt());

    //Format
    format_ = new MvQOgcList("FORMAT", "Format:");

    //Transparent
    transparent_ = new MvQOgcList("TRANSPARENT", "Transparent:");
    transparent_->setValues(QStringList() << "TRUE"
                                          << "FALSE");
    transparent_->setDisplayValues(QStringList() << "True"
                                                 << "False");
    val = getCovRequest_->item(transparent_->requestName());

    //If it is a new request we set transparency to TRUE by default
    if (val.isEmpty() && getCovRequest_->request().isEmpty()) {
        transparent_->setCurrentValue("TRUE");
    }
    else {
        transparent_->setCurrentValue(val);
    }

    //BgColour
    bgColour_ = new MvQOgcColourValue("#FFFFFF", "BGCOLOUR", "Bg colour:");

    //Layer
    layer_ = new MvQOgcTree("LAYERS", "Layer:");

    //CRS/SRS
    crs_ = new MvQOgcCrsList("CRS", "CRS:");

    //Style
    style_ = new MvQOgcStyleList("STYLES", "Style:");

    //BoundingBox
    requestBbox_    = new MvQOgcBoundingBox("BBOX", "");
    geographicBbox_ = 0;

    //Dimension

    //Network access
    networkGetCap_      = new MvQNetworkAccessManager(this);
    networkDescribeCov_ = new MvQNetworkAccessManager(this);
    networkGetCov_      = new MvQNetworkAccessManager(this);
    getCapReply_        = 0;
    describeCovReply_   = 0;
    getCovReply_        = 0;

    connect(networkGetCap_, SIGNAL(replyReadyToProcess(QNetworkReply*)),
            this, SLOT(slotReplyGetCap(QNetworkReply*)));

    connect(networkDescribeCov_, SIGNAL(replyReadyToProcess(QNetworkReply*)),
            this, SLOT(slotReplyDescribeCov(QNetworkReply*)));

    connect(networkGetCov_, SIGNAL(replyReadyToProcess(QNetworkReply*)),
            this, SLOT(slotReplyGetCov(QNetworkReply*)));

    connect(networkGetCap_, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
            this, SLOT(slotAuthentication(QNetworkReply*, QAuthenticator*)));

    connect(networkDescribeCov_, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
            this, SLOT(slotAuthentication(QNetworkReply*, QAuthenticator*)));

    connect(networkGetCov_, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
            this, SLOT(slotAuthentication(QNetworkReply*, QAuthenticator*)));


    previewFile_ = marstmp();
    legendFile_  = marstmp();

    //xml namspace
    xlinkNsDeclaration_ = "declare namespace xlink = \"http://www.w3.org/1999/xlink\";";
}

MvQWcsUiClient::~MvQWcsUiClient()
{
    delete width_;
    delete height_;
    delete format_;
    delete transparent_;
    delete bgColour_;
    delete layer_;
    delete crs_;
    delete style_;
    delete requestBbox_;
    delete networkGetCap_;
    delete networkDescribeCov_;
    delete networkGetCov_;

    clearDimension();
    clearBoundingBox();

    clearPreview();
    clearLegend();
}
void MvQWcsUiClient::setClientMode(ClientMode mode)
{
    clientMode_ = mode;
}

void MvQWcsUiClient::clearServerDependentData()
{
    capability_.clear();
    getCovRequest_->clear();
    format_->clear();
    layer_->clear();
    clearLayerDependentData();
    serviceMeta_.clear();
}

void MvQWcsUiClient::clearLayerDependentData()
{
    crs_->clear();
    style_->clear();
    clearDimension();
    clearBoundingBox();
}

void MvQWcsUiClient::clearDimension()
{
    foreach (MvQOgcDimension* item, dimension_) {
        delete item;
    }
    dimension_.clear();
}

void MvQWcsUiClient::clearBoundingBox()
{
    foreach (MvQOgcBoundingBox* item, bbox_) {
        delete item;
    }
    bbox_.clear();

    if (geographicBbox_) {
        delete geographicBbox_;
        geographicBbox_ = 0;
    }
}

void MvQWcsUiClient::setUrl(const QString& url, const QString version)
{
    if (url_ != url) {
        url_     = url;
        version_ = version;
        clearServerDependentData();
    }
}

void MvQWcsUiClient::setVersion(const QString& version)
{
    if (version_ != version) {
        version_ = version;
        //clearServerDependentData();
    }
}

void MvQWcsUiClient::slotRunGetCap()
{
    lastGetCovRequest_->setRequest(getCovRequest_->request());
    clearServerDependentData();

    QString r = url_;

    r += "?SERVICE=WCS&";
    if (version_ != "Default") {
        r += "VERSION=" + version_ + "&";
    }
    r += "REQUEST=GetCapabilities";
    if (!extraGetCapPar_.isEmpty()) {
        r += "&" + extraGetCapPar_;
    }

    qDebug() << "GetCapabilities request: " << r;

    LogItem* log = new LogItem;
    LogHandler::instance()->add(log);

    log->description("Load GetCapabalitites");
    log->setRequest(r.toStdString());
    log->setStatus("In progress");
    emit logUpdated();

    emit statusMessage(tr("Load GetCapabilitites ..."));

    getCapReply_ = networkGetCap_->get(QNetworkRequest(QUrl(r)));
}

void MvQWcsUiClient::slotRunDescribeCov()
{
    //lastGetCovRequest_->setRequest(getCovRequest_->request());
    //clearServerDependentData();

    QString r = url_;

    r += "?SERVICE=WCS&";
    if (repliedVersion_ != "Default") {
        r += "VERSION=" + repliedVersion_ + "&";
    }
    r += "REQUEST=DescribeCoverage&";

    //r+="IDENTIFIERS=F162009.v4b_web.stable_lights.avg_vis.lzw.tif";
    r += "COVERAGE=u";

    //if(!extraDescribeCovPar_.isEmpty())
    //{
    //	r+="&" + extraDescribeCovPar_;
    //}

    qDebug() << "DescribeCoverage request: " << r;

    LogItem* log = new LogItem;
    LogHandler::instance()->add(log);

    log->description("Load DescribeCoverage");
    log->setRequest(r.toStdString());
    log->setStatus("In progress");
    emit logUpdated();

    emit statusMessage(tr("Load  DescribeCoverage..."));

    describeCovReply_ = networkDescribeCov_->get(QNetworkRequest(QUrl(r)));
}


void MvQWcsUiClient::downloadPreview()
{
    /*MvQGetCoverageRequest req;
	req.setRequest(getCovRequest_->requestStep(0));
	req.setItem("WIDTH","512");
	req.setItem("HEIGHT","256");

	LogItem *log=new LogItem;
	LogHandler::instance()->add(log);
	log->description("Load preview");
	log->request(req.request().toStdString());
	log->status("In progress");
	emit logUpdated();

	emit statusMessage(tr("Load preview ..."));

	QNetworkRequest netReq(QUrl(req.request()));
	netReq.setOriginatingObject(this);
	previewReply_=networkPreview_->get(netReq);*/
}

void MvQWcsUiClient::downloadLegend()
{
    /*if(!style_->currentLegend().isEmpty())	
	{
		LogItem *log=new LogItem;
		LogHandler::instance()->add(log);
		log->description("Load legend");
		log->request(style_->currentLegend().toStdString());
		log->status("In progress");
		emit logUpdated();

		emit statusMessage(tr("Load legend ..."));

		QNetworkRequest netReq(QUrl(style_->currentLegend()));
		netReq.setOriginatingObject(this);
		legendReply_=networkLegend_->get(netReq);
	}
	else
	{
		emit legendLoaded(QString());
	}*/
}

void MvQWcsUiClient::setGetCovRequest(QString r)
{
    if (clientMode_ == BasicMode) {
        //getCovRequest_->editRequest(r);
        emit getCovRequestChanged(getCovRequest_->request());
    }
}

void MvQWcsUiClient::slotSaveInfo()
{
    // Get info
    MvRequest r("WCSCLIENT");

    r("SERVER")          = url_.toStdString().c_str();
    r("VERSION")         = version_.toStdString().c_str();
    r("REQUEST")         = getCovRequest_->request().toStdString().c_str();
    r("TIME_DIMENSIONS") = timeDimName().join("/").toStdString().c_str();

    //	reqInfo_("SERVICE") = 1;
    if (clientMode_ == BasicMode) {
        r("MODE") = "EXPERT";
    }
    else {
        r("MODE") = "INTERACTIVE";
    }

    r("EXTRA_GETCAP_PAR") = extraGetCapPar_.toStdString().c_str();
    r("EXTRA_GETMAP_PAR") = extraGetCovPar_.toStdString().c_str();

    r("HTTP_USER")     = httpUser_.toStdString().c_str();
    r("HTTP_PASSWORD") = httpPassword_.toStdString().c_str();

    r("LAYER_DESCRIPTION") = layerAbstract_.toStdString().c_str();
    //r("SERVICE_TITLE") =  serviceTitle_.toStdString().c_str();


    qDebug() << version_;
    qDebug() << url_;

    r.print();

    // Save info request
    r.save(iconFile_.toStdString().c_str());
}


void MvQWcsUiClient::slotAuthentication(QNetworkReply* reply, QAuthenticator* auth)
{
    auth->setUser("reading");
    auth->setPassword("metview");

    //auth->setUser(httpUser_);
    //auth->setPassword(httpPassword_);
}

void MvQWcsUiClient::slotReplyGetCap(QNetworkReply* reply)
{
    QNetworkRequest r = reply->request();
    QUrl url          = r.url();

    qDebug() << url.toString();

    QString mimeType = reply->header(QNetworkRequest::ContentTypeHeader).toString();

    LogItem* log = new LogItem;
    LogHandler::instance()->add(log);
    log->description("Load GetCapabilities");

    if (reply->error() != QNetworkReply::NoError) {
        log->error(reply->errorString().toStdString() + "\n");
        emit getCapLoaded();
        emit logUpdated();
        emit statusMessage(tr("Load GetCapabilities <font color=red>(FAILED)</font>"));
        //QApplication::exit();
    }
    else {
        QByteArray ba = reply->readAll();

        QString eMsg;
        if (!mimeType.contains("application/vnd.ogc.wcs_xml"))
        //&& mimeType == "application/vnd.ogc.se_xml")
        {
            readException(ba, eMsg);
        }

        if (!eMsg.isEmpty()) {
            capability_.clear();
            log->error(eMsg.toStdString() + "\n");
            emit getCapLoaded();
            emit logUpdated();
            emit statusMessage(tr("Load GetCapabilities <font color=red>(FAILED)</font>"));
        }

        capability_     = QString(ba);
        repliedVersion_ = readVersion();
        readService();
        readContents();
        //readCoverageOfferingBrief();
        //readFormat();
        //readLayer();

        updateAfterGetCapLoaded();

        emit getCapLoaded();
        emit logUpdated();
        emit statusMessage(tr("Load GetCapabilities <font color=green>(OK)</font>"));
    }

    reply->deleteLater();
    getCapReply_ = 0;
}

void MvQWcsUiClient::updateAfterGetCapLoaded()
{
    QString val;

    if (lastGetCovRequest_->request().isEmpty()) {
        return;
    }

    val = lastGetCovRequest_->item(width_->requestName());
    width_->setValue(val.toInt());

    val = lastGetCovRequest_->item(height_->requestName());
    height_->setValue(val.toInt());

    val = lastGetCovRequest_->item(transparent_->requestName());
    transparent_->setCurrentValue(val);

    val = lastGetCovRequest_->item(format_->requestName());
    format_->setCurrentValue(val);

    val = lastGetCovRequest_->item(layer_->requestName());
    layer_->setCurrentValue(val);

    updateAfterLayerLoaded();
}

void MvQWcsUiClient::updateAfterLayerLoaded()
{
    //lastGetCovRequest_->setRequest(getCovRequest_->request());

    QString val;

    //readLayerAbstract();
    readStyle();
    readCrs();
    readBoundingBox();
    readGeographicBoundingBox();
    readDimension();

    val = lastGetCovRequest_->item(style_->requestName());
    style_->setCurrentValue(val);

    val = lastGetCovRequest_->item(crs_->requestName());
    crs_->setCurrentValue(val);

    updatRequestBoundingBox();

    foreach (MvQOgcDimension* dim, dimension_) {
        val = lastGetCovRequest_->item(dim->requestName());
        dim->setCurrentValues(val);
    }

    buildGetCovRequest();

    qDebug() << lastGetCovRequest_->request() << "\n"
             << getCovRequest_->request();
}

void MvQWcsUiClient::slotReplyDescribeCov(QNetworkReply* reply)
{
    QNetworkRequest r = reply->request();
    QUrl url          = r.url();

    qDebug() << url.toString();

    LogItem* log = new LogItem;
    LogHandler::instance()->add(log);
    log->description("Load DescribeCoverage");

    QString mimeType = reply->header(QNetworkRequest::ContentTypeHeader).toString();

    if (reply->error() != QNetworkReply::NoError) {
        log->error(reply->errorString().toStdString() + "\n");
        //emit previewLoaded(QString());
        emit statusMessage(tr("Load DescribeCoverage <font color=red>(FAILED)</font>"));
    }
    else {
        QByteArray ba = reply->readAll();

        QString eMsg;
        if (!mimeType.contains("application/vnd.ogc.wcs_xml"))
        //&& mimeType == "application/vnd.ogc.se_xml")
        {
            readException(ba, eMsg);
        }

        if (!eMsg.isEmpty()) {
            //capability_.clear();
            log->error(eMsg.toStdString() + "\n");
            //emit getCapLoaded();
            emit logUpdated();
            emit statusMessage(tr("Load DescribeCoverage <font color=red>(FAILED)</font>"));
        }

        QString s(ba);
        qDebug() << s;

        describeCov_ = QString(ba);
        //repliedVersion_=readVersion();
        //readService();
        readCoverageOfferings();
        //readCoverageOfferingBrief();
        //readFormat();
        //readLayer();

        //updateAfterGetCapLoaded();

        emit describeCovLoaded();
        emit logUpdated();
        emit statusMessage(tr("Load DescribeCoverage <font color=green>(OK)</font>"));
    }

    emit logUpdated();

    reply->deleteLater();
    describeCovReply_ = 0;
}

void MvQWcsUiClient::slotReplyGetCov(QNetworkReply* reply)
{
    /*	QNetworkRequest r=reply->request();
	QUrl url=r.url();

	qDebug() << url.toString();

	QString mimeType=reply->header(QNetworkRequest::ContentTypeHeader).toString();

	LogItem *log=new LogItem;
	LogHandler::instance()->add(log);
	log->description("Load legend");

	if(reply->error() != QNetworkReply::NoError)
	{
		log->error(reply->errorString().toStdString() + "\n");	
		emit legendLoaded(QString());
		emit statusMessage(tr("Load legend <font color=red>(FAILED)</font>"));				
	}
	else
	{	
		QString outFile=legendFile_;
		QByteArray ba=reply->readAll();

		if(mimeType.isEmpty())
			mimeType=getMimeType(ba);

		qDebug() << "mime" << mimeType << getRequestedMimeType(url.toString());

		//If exception is returned ot mime type is 
		//different ot what was requested
		if(mimeType.contains("application/vnd.ogc.se_xml")) //||
		//   mimeType != getRequestedMimeType(url.toString()))		
		{
			QString eMsg;
			readException(ba,eMsg);

			log->error(eMsg.toStdString() + "\n");
			emit legendLoaded(QString());
			emit statusMessage(tr("Load legend <font color=red>(FAILED)</font>"));
		}
		else
		{
			QFile out(outFile);
			out.open(QIODevice::WriteOnly);
			out.write(ba);
			out.close();

			emit legendLoaded(outFile);
			emit statusMessage(tr("Load legend <font color=green>(OK)</font>"));
		}
	}

	emit logUpdated();

	reply->deleteLater();
	legendReply_=0;*/
}


void MvQWcsUiClient::slotAbortDownloadProcess()
{
    if (getCapReply_ && getCapReply_->isRunning()) {
        LogItem* log = new LogItem;
        LogHandler::instance()->add(log);
        log->description("Load GetCapabalitites");
        log->error("Interrupted\n");

        emit statusMessage(tr("Load GetCapabilitites <font color=red>(Interrupted)</font>"));

        getCapReply_->deleteLater();
        getCapReply_ = 0;
        emit getCapLoaded();
        emit logUpdated();
    }
    /*else if(previewReply_ && previewReply_->isRunning())
	{
		LogItem *log=new LogItem;
		LogHandler::instance()->add(log);
		log->description("Load Preview");
		log->error("Interrupted\n");

		emit statusMessage(tr("Load preview <font color=red>(Interrupted)</font>"));

		previewReply_->deleteLater();
		previewReply_=0;
		clearPreview();
		emit previewLoaded(previewFile_);
		emit logUpdated();
	}
	else if(legendReply_ && legendReply_->isRunning())
	{
		LogItem *log=new LogItem;
		LogHandler::instance()->add(log);
		log->description("Load Legend");
		log->error("Interrupted\n");

		emit statusMessage(tr("Load legend <font color=red>(Interrupted)</font>"));

		legendReply_->deleteLater();
		legendReply_=0;
		clearLegend();
		emit legendLoaded(legendFile_);
		emit logUpdated();
	}*/
}

QString MvQWcsUiClient::readVersion()
{
    QString result;

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

    defaultNsDeclaration_ = "declare default element namespace \"http://www.opengis.net/wcs\";";

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//WCS_Capabilities/data(@version)");
    query.evaluateTo(&result);

    if (result.simplified().isEmpty()) {
        query.setQuery("doc($myDoc)//WMT_MS_Capabilities/data(@version)");
        query.evaluateTo(&result);
        defaultNsDeclaration_.clear();
    }

#if 0
	defaultNsDeclaration_="declare default element namespace \"http://www.opengis.net/wcs/1.1\"; declare namespace ows=\"http://www.opengis.net/ows/1.1\";";


	MvQXmlQuery query;
     	query.bindVariable("myDoc", &buffer);
	query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Capabilities/data(@version)");
	query.evaluateTo(&result);
	result.simplified();
#endif

    buffer.close();

    qDebug() << "Version ---> ";
    qDebug() << "\t" << result;

    //Remove linebreak!!

    return result.simplified();
}

void MvQWcsUiClient::readService()
{
    serviceMeta_.clear();

    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    //query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Service/data(Title)");
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Service");
    query.evaluateTo(&result);

    //serviceTitle_=result.simplified();

    QXmlItem item(result.next());
    while (!item.isNull()) {
        if (item.isNode()) {
            query.setFocus(item);

            QString str;


            QStringList tags;
            tags << "name"
                 << "description"
                 << "label"
                 << "fees"
                 << "accessConstraints";

            foreach (QString t, tags) {
                str.clear();
                QString q = defaultNsDeclaration_ + ".//data(" + t + ")";
                query.setQuery(q);
                query.evaluateTo(&str);
                serviceMeta_[t] = str.simplified();
            }

            break;
        }
        item = result.next();
    }

    buffer.close();

    qDebug() << "readService -->" << serviceMeta_;
    //Remove linebreak!!
}

void MvQWcsUiClient::readContents()
{
    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Contents/CoverageSummary");
    query.evaluateTo(&result);

    QXmlItem item(result.next());
    QStringList nameLst, titleLst, abstractLst, legendLst;
    while (!item.isNull()) {
        if (item.isNode()) {
            QString txt, name, title, abstract, legend;

            MvQOgcElem* elem = new MvQOgcElem;

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

            //Name
            query.setQuery(defaultNsDeclaration_ + "./data(ows:Title)");
            query.evaluateTo(&txt);
            elem->addAttribute("Title", txt.simplified());
            qDebug() << "Title" << txt;
            txt.clear();

            //label
            query.setQuery(defaultNsDeclaration_ + "./data(Abstract)");
            query.evaluateTo(&txt);
            elem->addAttribute("Abstract", txt.simplified());
            txt.clear();

            //desc
            query.setQuery(defaultNsDeclaration_ + "./data(Identifier)");
            query.evaluateTo(&txt);
            elem->addAttribute("Identifier", txt.simplified());
            txt.clear();

            covOffer_ << elem;
        }
        item = result.next();
    }

    buffer.close();

    qDebug() << "Style ---> ";
    qDebug() << "\t" << titleLst;
}


void MvQWcsUiClient::readCoverageOfferingBrief()
{
    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//ContentMetadata/CoverageOfferingBrief");
    query.evaluateTo(&result);

    QXmlItem item(result.next());
    QStringList nameLst, titleLst, abstractLst, legendLst;
    while (!item.isNull()) {
        if (item.isNode()) {
            QString txt, name, title, abstract, legend;

            MvQOgcElem* elem = new MvQOgcElem;

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

            //Name
            query.setQuery(defaultNsDeclaration_ + xlinkNsDeclaration_ + "./data(name)");
            query.evaluateTo(&txt);
            elem->addAttribute("name", txt.simplified());
            txt.clear();

            //label
            query.setQuery(defaultNsDeclaration_ + "./data(label)");
            query.evaluateTo(&txt);
            elem->addAttribute("label", txt.simplified());
            txt.clear();

            //desc
            query.setQuery(defaultNsDeclaration_ + "./data(description)");
            query.evaluateTo(&txt);
            elem->addAttribute("description", txt.simplified());
            txt.clear();

            covOffer_ << elem;
        }
        item = result.next();
    }

    buffer.close();

    qDebug() << "Style ---> ";
    qDebug() << "\t" << titleLst;
}

void MvQWcsUiClient::readCoverageOfferings()
{
    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//CoverageDescription/CoverageOffering");
    query.evaluateTo(&result);

    QXmlItem item(result.next());
    QStringList nameLst, titleLst, abstractLst, legendLst;
    while (!item.isNull()) {
        if (item.isNode()) {
            QString txt, name, title, abstract, legend;

            MvQOgcElem* elem = new MvQOgcElem;

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

            //Name
            query.setQuery(defaultNsDeclaration_ + xlinkNsDeclaration_ + "./data(name)");
            query.evaluateTo(&txt);
            elem->addAttribute("name", txt.simplified());

            qDebug() << "coverageOffer name" << txt;

            txt.clear();

            //label
            query.setQuery(defaultNsDeclaration_ + "./data(label)");
            query.evaluateTo(&txt);
            elem->addAttribute("label", txt.simplified());
            txt.clear();

            //desc
            query.setQuery(defaultNsDeclaration_ + "./data(description)");
            query.evaluateTo(&txt);
            elem->addAttribute("description", txt.simplified());
            txt.clear();

            //covOffer_ << elem;
        }
        item = result.next();
    }

    buffer.close();

    qDebug() << "Style ---> ";
    qDebug() << "\t" << titleLst;
}


void MvQWcsUiClient::readFormat()
{
    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);

    if (repliedVersion_ > "1.0") {
        query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//CoverageCapability/Request/GetCov/data(Format)");
    }
    else {
        query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Capability/Request/Map/data(Format)");
    }

    query.evaluateTo(&result);

    QStringList lst;
    query.getAtomicValues(result, lst);
    lst.sort();
    format_->setValues(lst);
    format_->setDisplayValues(lst);

    buffer.close();

    qDebug() << "Formats ---> ";
    qDebug() << "\t" << lst;
}

void MvQWcsUiClient::readLayer()
{
    //Dom
    QDomDocument doc("mydocument");

    if (!doc.setContent(capability_)) {
        return;
    }

    QDomElement docElem = doc.documentElement();
    readLayer(docElem, layer_->root());

    qDebug() << "Layers ---> ";
}

void MvQWcsUiClient::readLayer(QDomElement& docElem, MvQOgcNode* parent)
{
    QDomNode dNode = docElem.firstChild();
    while (!dNode.isNull()) {
        QDomElement dElem = dNode.toElement();
        if (!dElem.isNull()) {
            if (dElem.tagName() == "Layer") {
                MvQOgcNode* layer = new MvQOgcNode;

                QDomNode title = dNode.namedItem("Title");
                if (!title.isNull()) {
                    qDebug() << title.toElement().text();
                    layer->setDisplayValue(title.toElement().text());
                }

                QDomNode name = dNode.namedItem("Name");
                if (!name.isNull()) {
                    layer->setValue(name.toElement().text());
                }

                QDomNode desc = dNode.namedItem("Abstract");
                if (!desc.isNull()) {
                    layer->setDescription(desc.toElement().text());
                }

                parent->addChild(layer);
                readLayer(dElem, layer);
            }
            else {
                readLayer(dElem, parent);
            }
        }

        dNode = dNode.nextSibling();
    }
}


void MvQWcsUiClient::readStyle()
{
    if (layer_->currentValue().isEmpty())
        return;

    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.bindVariable("myLayer", QVariant(layer_->currentValue()));
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/Style");
    query.evaluateTo(&result);

    QXmlItem item(result.next());
    QStringList nameLst, titleLst, abstractLst, legendLst;
    while (!item.isNull()) {
        if (item.isNode()) {
            QString name, title, abstract, legend;

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

            //Name
            query.setQuery(defaultNsDeclaration_ + "./data(Name)");
            query.evaluateTo(&name);
            nameLst << name.simplified();

            //Title
            query.setQuery(defaultNsDeclaration_ + "./data(Title)");
            query.evaluateTo(&title);
            titleLst << title.simplified();

            //Abstract
            query.setQuery(defaultNsDeclaration_ + "./data(Abstract)");
            query.evaluateTo(&abstract);
            abstractLst << abstract.simplified();

            //Legend url
            query.setQuery(defaultNsDeclaration_ + xlinkNsDeclaration_ + "string(./LegendURL/OnlineResource/@xlink:href)");
            query.evaluateTo(&legend);
            legendLst << legend.simplified();

            style_->setValues(nameLst);
            style_->setDisplayValues(titleLst);
            style_->setDescriptions(abstractLst);
            style_->setLegends(legendLst);
        }
        item = result.next();
    }

    buffer.close();

    qDebug() << "Style ---> ";
    qDebug() << "\t" << titleLst;
}

void MvQWcsUiClient::readCrs()
{
    if (layer_->currentValue().isEmpty())
        return;

    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.bindVariable("myLayer", QVariant(layer_->currentValue()));
    //query.bindVariable("myCrsName", QVariant(crsRequestName()));
    if (crsRequestName() == "SRS") {
        query.setQuery("doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/data(SRS)");
    }
    else {
        query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/data(CRS)");
    }

    query.evaluateTo(&result);

    QStringList lst;
    query.getAtomicValues(result, lst);
    lst.removeDuplicates();
    lst.sort();
    crs_->setValues(lst);
    crs_->setRequestName(crsRequestName());
    crs_->setDisplayName(crsDisplayName());

    buffer.close();

    qDebug() << "CRS ---> ";
    qDebug() << "\t" << lst;
}

void MvQWcsUiClient::readBoundingBox()
{
    if (layer_->currentValue().isEmpty())
        return;

    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.bindVariable("myLayer", QVariant(layer_->currentValue()));
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/BoundingBox");
    query.evaluateTo(&result);

    QXmlItem item(result.next());
    while (!item.isNull()) {
        if (item.isNode()) {
            QMap<QString, QString> att;
            query.getAttributes(item, att);

            MvQOgcBoundingBox* bb = new MvQOgcBoundingBox(att);
            bbox_.push_back(bb);
        }
        item = result.next();
    }

    buffer.close();
}


void MvQWcsUiClient::readGeographicBoundingBox()
{
    if (layer_->currentValue().isEmpty())
        return;

    QStringList str;
    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.bindVariable("myLayer", QVariant(layer_->currentValue()));

    if (repliedVersion_ >= "1.3.0") {
        query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/EX_GeographicBoundingBox");
    }
    else {
        query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/LatLonBoundingBox");
    }

    query.evaluateTo(&result);

    QXmlItem item(result.next());
    while (!item.isNull()) {
        if (item.isNode()) {
            QMap<QString, QString> att;
            query.getAttributes(item, att);

            if (geographicBbox_) {
                delete geographicBbox_;
            }
            geographicBbox_ = new MvQOgcGeoBoundingBox(att);  //new MvQXmlElementNode(query,item);
            break;
        }
        item = result.next();
    }
}

void MvQWcsUiClient::readDimension()
{
    if (layer_->currentValue().isEmpty())
        return;

    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    query.bindVariable("myLayer", QVariant(layer_->currentValue()));
    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/Dimension");
    query.evaluateTo(&result);

    QXmlItem item(result.next());
    while (!item.isNull()) {
        if (item.isNode()) {
            QMap<QString, QString> att;
            QString value;

            query.getAttributes(item, att);
            query.getAtomicValue(item, value);

            MvQOgcDimension* dim = new MvQOgcDimension(att, value);

            if (dim->name().compare("time", Qt::CaseInsensitive) == 0) {
                dim->setRequestName("TIME");
                dim->setDisplayName("Time:");
            }
            else if (dim->name().compare("elevation", Qt::CaseInsensitive) == 0) {
                dim->setRequestName("ELEVATION");
                dim->setDisplayName("Elevation:");
            }
            else {
                QString dname = dim->name();
                dname         = dname.toUpper();
                dname         = "DIM_" + dname;
                dim->setRequestName(dname);
                dname += " :";
                dim->setDisplayName(dname);
            }

            dimension_.push_back(dim);
        }
        item = result.next();
    }

    if (repliedVersion_ >= "1.3.0")
        return;

    query.setQuery(defaultNsDeclaration_ + "doc($myDoc)//Layer[Name = $myLayer]/ancestor-or-self::*/Extent");
    query.evaluateTo(&result);

    item = result.next();
    while (!item.isNull()) {
        if (item.isNode()) {
            QMap<QString, QString> att;
            QString value;

            query.getAttributes(item, att);
            query.getAtomicValue(item, value);

            //MvQXmlElementNode *elem=new MvQXmlElementNode(query,item);
            foreach (MvQOgcDimension* dim, dimension_) {
                if (dim->name() == att["name"]) {
                    dim->setAttributes(att);
                    dim->setValues(value);
                    break;
                }
            }
        }
        item = result.next();
    }
}

void MvQWcsUiClient::readException(QByteArray ba, QString& msg)
{
    //if(xmlMsg.isEmpty())
    //	return;

    QXmlResultItems result;

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

    MvQXmlQuery query;
    query.bindVariable("myDoc", &buffer);
    //query.bindVariable("myLayer", QVariant(layer_->currentValue()));
    query.setQuery("doc($myDoc)//ServiceExceptionReport/ServiceException");

    query.evaluateTo(&result);

    QXmlItem item(result.next());
    while (!item.isNull()) {
        if (item.isNode()) {
            msg += "Exception: ";

            QMap<QString, QString> att;
            QString value;

            query.getAttributes(item, att);
            query.getAtomicValue(item, value);
            msg += att["code"].simplified() + "\n";

            if (!value.isEmpty()) {
                msg += value;
                msg += '\n';
            }
        }
        item = result.next();
    }

    buffer.close();
}

void MvQWcsUiClient::buildGetCovRequest()
{
    if (layer_->currentValue().isEmpty())
        return;

    getCovRequest_->clear();

    QString s;
    QString str = url_;
    str += "?SERVICE=WCS";

    //Version
    /*if(version_ != "Default")
	{
		str+="&VERSION=";
		str+=version_;
	}*/

    str += "&VERSION=";
    str += repliedVersion_;

    //Request
    str += "&REQUEST=GetMap";

    //Layers
    str += "&" + layer_->requestName() + "=" + layer_->currentValue();

    //Style
    str += "&" + style_->requestName() + "=" + style_->currentValue();

    //srs or crs
    str += "&" + crs_->requestName() + "=" + crs_->currentValue();

    //bbox
    str += "&BBOX=" +
           requestBbox_->minX() + "," +
           requestBbox_->minY() + "," +
           requestBbox_->maxX() + "," +
           requestBbox_->maxY();

    //width
    str += "&WIDTH=" + QString::number(width_->value());
    str += "&HEIGHT=" + QString::number(height_->value());

    //Format
    str += "&" + format_->requestName() + "=" + format_->currentValue();

    //Transparent
    str += "&" + transparent_->requestName() + "=" + transparent_->currentValue();

    //Dimensions (except time)
    MvQOgcDimension* dimTime = 0;
    foreach (MvQOgcDimension* dim, dimension_) {
        //if(dim->requestName() != "TIME")
        //{
        str += "&";
        str += dim->requestName();
        str += "=";
        str += dim->currentValues();
        //}
        //else
        //{
        //	dimTime=dim;
        //}
    }

    //Time dimension
    /*if(dimTime)
	{
		str+="&TIME=";
		foreach(QString s, dimTime->currentValues())
		{
			str+=s + "/";
		}
		//remove the last ","
		str=str.remove(str.size()-1,1);
		
	}*/
    qDebug() << str;

    if (!extraGetCovPar_.isEmpty()) {
        str += "&" + extraGetCovPar_;
    }

    //!!!!!!!!!
    getCovRequest_->setRequest(str);

    currentGetCovRequest_ = getCovRequest_;

    //qDebug() << getMapRequest_->requestStep();

    //str+="&stream=false";

    //getMapRequest_=str;

    //saveGetMapRequest(currentGetMapRequest_);

    emit getCovRequestChanged(getCovRequest_->request());
}


//===========================================
//
// Get/Set methods
//
//===========================================

//Format
QStringList MvQWcsUiClient::formatDisplayValues() const
{
    return format_->displayValues();
}

QString MvQWcsUiClient::formatCurrentDisplayValue() const
{
    return format_->currentDisplayValue();
}

void MvQWcsUiClient::slotSetFormatFromDpy(QString value)
{
    if (format_->currentDisplayValue() != value) {
        format_->setCurrentDisplayValue(value);
        buildGetCovRequest();
    }
}

//Transparent
QStringList MvQWcsUiClient::transparentDisplayValues() const
{
    return transparent_->displayValues();
}

QString MvQWcsUiClient::transparentCurrentDisplayValue() const
{
    return transparent_->currentDisplayValue();
}

void MvQWcsUiClient::setTransparentCurrentDisplayValue(QString value)
{
    if (transparent_->currentDisplayValue() != value) {
        transparent_->setCurrentDisplayValue(value);
        buildGetCovRequest();
    }
}

//Width
QString MvQWcsUiClient::width() const
{
    return QString::number(width_->value());
}

void MvQWcsUiClient::setWidth(QString value)
{
    if (width_->value() != value.toInt()) {
        width_->setValue(value.toInt());
        buildGetCovRequest();
    }
}

//Height
QString MvQWcsUiClient::height() const
{
    return QString::number(height_->value());
}

void MvQWcsUiClient::setHeight(QString value)
{
    if (height_->value() != value.toInt()) {
        height_->setValue(value.toInt());
        buildGetCovRequest();
    }
}

//Extra par
void MvQWcsUiClient::setExtraGetCapPar(QString value)
{
    if (extraGetCapPar_ != value) {
        extraGetCapPar_ = value;
    }
}

void MvQWcsUiClient::setExtraGetCovPar(QString value)
{
    if (extraGetCovPar_ != value) {
        extraGetCovPar_ = value;
        buildGetCovRequest();
    }
}

//Style
QStringList MvQWcsUiClient::styleDisplayValues() const
{
    return style_->displayValues();
}

QStringList MvQWcsUiClient::styleDescriptions() const
{
    return style_->descriptions();
}

int MvQWcsUiClient::styleCurrentIndex() const
{
    return style_->currentIndex();
}

void MvQWcsUiClient::setStyleCurrentIndex(int index)
{
    if (style_->currentIndex() != index) {
        style_->setCurrentIndex(index);
        buildGetCovRequest();
    }
}


//CRS
QStringList MvQWcsUiClient::crsDisplayValues() const
{
    return crs_->displayValues();
}

QString MvQWcsUiClient::crsCurrentDisplayValue() const
{
    return crs_->currentDisplayValue();
}

void MvQWcsUiClient::setCrsCurrentDisplayValue(QString value)
{
    if (crs_->currentDisplayValue() != value) {
        crs_->setCurrentDisplayValue(value);
        updatRequestBoundingBox();
        buildGetCovRequest();
    }
}

//Layer
int MvQWcsUiClient::layerCurrentIndex()
{
    return 0;
    //return layer_->values().indexOf(layer_->currentValue());
}

QStringList MvQWcsUiClient::layerDisplayValues() const
{
    return QStringList();
    //return layer_->displayValues();
}

QStringList MvQWcsUiClient::layerDescriptions() const
{
    return QStringList();
    //qDebug() << layer_->descriptions();
    //return layer_->descriptions();
}

void MvQWcsUiClient::setLayerFromDpy(MvQOgcNode* node)
{
    clearLayerDependentData();

    layer_->setCurrentNode(node);

    lastGetCovRequest_->setRequest(getCovRequest_->request());

    updateAfterLayerLoaded();
}


//BBOX
void MvQWcsUiClient::setBoundingBoxFromDpy(QString minX, QString maxX, QString minY, QString maxY)
{
    requestBbox_->setArea(minX, maxX, minY, maxY);
    buildGetCovRequest();
}

MvQOgcBoundingBox MvQWcsUiClient::lastBoundingBox() const
{
    QString lastValue = lastGetCovRequest_->item("BBOX");
    QStringList lst   = lastValue.split(",");
    MvQOgcBoundingBox bb;
    if (lst.count() == 4) {
        bb.setArea(lst[0], lst[2], lst[1], lst[3]);
    }
    return bb;
}

MvQOgcBoundingBox* MvQWcsUiClient::currentBoundingBox() const
{
    qDebug() << crs_->currentValue();

    for (int i = bbox_.count() - 1; i >= 0; i--) {
        if (bbox_[i]->crs() == crs_->currentValue()) {
            return bbox_[i];
        }
    }

    return 0;
}

//Dimensions
QStringList MvQWcsUiClient::dimensionNameToDpy() const
{
    QStringList lst;
    /*foreach(MvQOgcDimensionList *dim,dimension_)
	{
	    lst << dim->displayName();
	}*/

    return lst;
}

QStringList MvQWcsUiClient::dimensionToDpy(QString dimDpyName) const
{
    /*foreach(MvQOgcDimensionList *dim,dimension_)
	{
	    if(dim->displayName() == dimDpyName)
	    {
		return dim->displayValues();
	    }
	}*/

    return QStringList();
}

void MvQWcsUiClient::setDimensionFromDpy(QString dimDpyName, QString val)
{
    foreach (MvQOgcDimension* dim, dimension_) {
        if (dim->displayName() == dimDpyName) {
            //dim->setCurrentDisplayValue(val);
            dim->setCurrentValues(val);
            buildGetCovRequest();
            return;
        }
    }
}

void MvQWcsUiClient::setDimensionFromDpy(QString dimDpyName, QStringList val)
{
    /*foreach(MvQOgcDimensionList *dim,dimension_)
	{
	    if(dim->displayName() == dimDpyName)
	    {
		//dim->setCurrentDisplayValues(val);
		setCurrentValues(val);
		buildGetMapRequest();
		return;
	    }
	}*/
}

QString MvQWcsUiClient::crsQueryName()
{
    if (repliedVersion_ < QString("1.3.0")) {
        return QString("SRS");
    }
    else {
        return QString("CRS");
    }
}

QString MvQWcsUiClient::crsRequestName()
{
    if (repliedVersion_ < QString("1.3.0")) {
        return QString("SRS");
    }
    else {
        return QString("CRS");
    }
}

QString MvQWcsUiClient::crsDisplayName()
{
    if (repliedVersion_ < QString("1.3.0")) {
        return QString("SRS:");
    }
    else {
        return QString("CRS:");
    }
}

QStringList MvQWcsUiClient::timeDimName()
{
    QStringList timeDimName;

    foreach (MvQOgcDimension* dim, dimension_) {
        if (dim->isTime()) {
            timeDimName << dim->requestName();
        }
    }
    return timeDimName;
}

void MvQWcsUiClient::clearPreview()
{
    //if(previewFile_ != emptyFileNameString_)
    //{
    QFile f(previewFile_);

    if (!f.remove()) {
        //qDebug() << "MvQZoomStackLevel::clearPreview() ---> Preview file" << imgFileName_ << "could not be deleted!";
    }
    //previewFile_ = emptyFileNameString_;
    //}
}

void MvQWcsUiClient::clearLegend()
{
    //if(previewFile_ != emptyFileNameString_)
    //{
    QFile f(legendFile_);

    if (!f.remove()) {
        //qDebug() << "MvQZoomStackLevel::clearPreview() ---> Preview file" << imgFileName_ << "could not be deleted!";
    }
    //previewFile_ = emptyFileNameString_;
    //}
}

void MvQWcsUiClient::updatRequestBoundingBox()
{
    requestBbox_->clear();
    bool foundBb = false;

    //Check if bbox is available for the current crs.
    //It is obligatory from 1.3.0 !!!
    foreach (MvQOgcBoundingBox* bb, bbox_) {
        if (bb->crs() == crs_->currentValue()) {
            foundBb = true;
            requestBbox_->setArea(bb->minX(), bb->maxX(), bb->minY(), bb->maxY());
            break;
        }
    }

    //Else for older versions lat-lon we try to use the geographic bounding box
    if (!foundBb && repliedVersion_ < "1.3.0" &&
        crs_->currentValue() == "EPSG:4326" && geographicBbox_ != 0) {
        requestBbox_->setArea(geographicBbox_->minX(),
                              geographicBbox_->maxX(),
                              geographicBbox_->minY(),
                              geographicBbox_->maxY());
    }
}
