//-----------------------------------------------------------------------------
//  Copyright (C) 2002-2017 Thomas S. Ullrich
//
//  This file is part of "xyscan".
//
//  This file may be used under the terms of the GNU General Public License.
//  This project is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License.
//  
//  Author: Thomas S. Ullrich
//  Last update: October 12, 2017
//-----------------------------------------------------------------------------
#include "xyscanUpdater.h"
#include <QMessageBox>
#include <QXmlStreamReader>
#include <QNetworkReply>
#include <QCoreApplication>
#include <QNetworkProxy>

#define PR(x) cout << #x << " = " << (x) << endl;

using namespace std;

xyscanUpdater::xyscanUpdater()
{
    mNextCheckIsSilent = false;
    connect(&mManager, SIGNAL(finished(QNetworkReply*)),
                       SLOT(downloadFinished(QNetworkReply*)));
    mCurrentDownload = 0;
}

void xyscanUpdater::checkForNewVersion(const QUrl& url)
{   
    //
    // Send request to download the file.
    // Allow only one request at a atime.
    //
    if (mCurrentDownload == 0) {
        QNetworkRequest request(url);
        mCurrentDownload = mManager.get(request);
    }
}

void xyscanUpdater::downloadFinished(QNetworkReply *reply)
{
    QUrl url = reply->url();
    
    if (reply->error()) {
        if (!mNextCheckIsSilent) {
            QMessageBox::warning(0, tr("xyscan"),
                                 tr("Cannot check for latest version.\n(%1).\n\n"
                                    "Make sure you are connected to a network and try again.")
                                 .arg(qPrintable(reply->errorString())));
        }
    }
    else {
        //
        // Got the xmf file content,
        // decode it and compare version numbers.
        //
        QString latestVersion, wwwLocation;

        QByteArray content = reply->readAll(); 
        QXmlStreamReader reader(content);        
        while (!reader.atEnd()) {
            reader.readNext();
            if (reader.isStartElement() && reader.attributes().hasAttribute("version")) {
                latestVersion = reader.attributes().value("version").toString();
                reader.readNext();
                if(reader.isCharacters()) {
                    wwwLocation = reader.text().toString();
                }
            }
        }

        if (reader.error() && !mNextCheckIsSilent) {
            QMessageBox::warning(0, tr("xyscan"),
                                 tr("Parsing of xml file failed. "
                                    "Cannot check for newer version. Try again later."));
        }

        if(!latestVersion.isEmpty() && !reader.error()) {
            if( latestVersion > qApp->applicationVersion() ) {
                QMessageBox::information( 0, "xyscan", 
                                         tr("<html>A new version of xyscan (%1) is available.<br>"
                                            "To download go to:<br>"
                                            "<a href=\"%2\">%2</a></html>").arg(latestVersion).arg(wwwLocation));
                emit userReminded();
            }           
            else if( latestVersion == qApp->applicationVersion()  && !mNextCheckIsSilent) {
                QMessageBox::information( 0, "xyscan", 
                                         tr("You are running the latest version of xyscan (%1).").arg(qApp->applicationVersion()));   
            }
            else {
                if (!mNextCheckIsSilent) {
                    QMessageBox::information( 0, "xyscan",
                                         tr("Strange, you are running a newer version (%1) than the latest version available on the web (%2).").arg(qApp->applicationVersion()).arg(latestVersion));
                }
            }
        }
    }
    
    reply->deleteLater();  // mark for deletion
    mCurrentDownload = 0;  // done with this request
    mNextCheckIsSilent = false;
}
