/***************************************************************************
 *   Copyright (C) 2006 by Bram Biesbrouck                                 *
 *   b@beligum.org                                                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA.             *
 ***************************************************************************/

#include <qpushbutton.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qapplication.h>
#include <qcursor.h>

#include <kurllabel.h>
#include <klineedit.h>
#include <kactivelabel.h>
#include <kprogress.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kcursor.h>

#include <libinstrudeo/isdutils.h>
#include <libinstrudeo/isdwscommunicator.h>
#include <libinstrudeo/isdobject.h>
#include <libinstrudeo/isdrecording.h>

#include "srkmainview.h"
#include "srktransmitrecordingdialog.h"

//----CONSTRUCTORS-----
SRKTransmitRecordingDialog::SRKTransmitRecordingDialog(QString& fileName, SRKMainView* parent,
						       const char* name, bool modal, WFlags fl)
    : SRKTransmitRecordingDialogBase(parent,name, modal,fl),
      recFileName(fileName),
      parent(parent)
{
    //fill the username and password boxes
    KConfig* config = KGlobal::config();
    
    config->setGroup("Network");
    usernameText->setText(config->readEntry("WebserviceUsername", ""));
    passwordText->setText(config->readEntry("WebservicePassword", ""));
}

//-----DESTRUCTOR-----
SRKTransmitRecordingDialog::~SRKTransmitRecordingDialog()
{
}

//-----PROTECTED SLOTS-----
void SRKTransmitRecordingDialog::editMetaInformation()
{
    parent->editMetaInfo();

    //save the new information
    parent->saveRecording(recFileName);
}
void SRKTransmitRecordingDialog::disclaimerDisagreeToggled(bool b)
{
    //if disagree is clicked (default), no sending is possible
    loginGrp->setEnabled(!b);
    sendButton->setEnabled(!b);
    loginInfoLbl->setEnabled(!b);
    loginInfoUrl->setEnabled(!b);
}
void SRKTransmitRecordingDialog::disclaimerAgreeToggled(bool b)
{
    loginGrp->setEnabled(b);
    sendButton->setEnabled(b);
    loginInfoLbl->setEnabled(b);
    loginInfoUrl->setEnabled(b);
}
void SRKTransmitRecordingDialog::reject()
{
    QDialog::reject();
}
void SRKTransmitRecordingDialog::accept()
{
    ISDObject::ISDErrorCode retVal, uploadDoneError;

    /*
     * At lease the title, question and description must be set.
     * Note: the method takes care of notifying the user.
     */
    if (!parent->applyTransmitFilter()) {
	//don't close the dialog
	return;
    }

    /*
     * Fetch the FTP path from the webservice.
     */
    KConfig* config = KGlobal::config();
    config->setGroup("Network");
    string serviceEndpoint = config->readEntry("WebserviceUrl", DEFAULT_SERVICE_ENDPOINT).ascii();
    ISDWSCommunicator wsComm(serviceEndpoint);
    
    setCursor(KCursor::waitCursor());

    string username = usernameText->text();
    string password = passwordText->text();
    int ftpSessionId;
    string ftpPath;
    string errorString;
    if (wsComm.getFtpPath(username, password, ftpPath, ftpSessionId, errorString) != ISDObject::ISD_SUCCESS) {
	setCursor(KCursor::arrowCursor());
	webserviceError(errorString);
	//don't close the dialog
    }
    //all OK
    else {
	setCursor(KCursor::arrowCursor());
	
	//init the progress dialog
	KProgressDialog progress(NULL, 0, i18n("Uploading file"), i18n("Please wait while uploading file..."), true);
	progress.setAllowCancel(true);
	progress.setModal(true);
	progress.setAutoClose(true);
	progress.setMinimumDuration(0);
	//we're showing percentages
	progress.progressBar()->setTotalSteps(100);
	
	SRKFtpProgressCallback callback(&progress);
	string fileName = recFileName.ascii();
	/*
	 * After we logged in successfully with the username and password,
	 * replace the username with the sessionId.
	 * This way, the server knows what to do with the ftp-request.
	 */
	string sessionIdStr = ISDUtils::getInstance()->intToString(ftpSessionId);
	retVal = wsComm.transmitRecording(fileName, ftpPath,
					  sessionIdStr, password,
					  &callback);

	progress.close();
	qApp->processEvents();

	/*
	 * We must always notice the webservice we are done, so it can do any cleanup or processing.
	 * This must be called at all times, since we start a new session by calling its getFtpPath() method.
	 */
	bool aborted = retVal!=ISDObject::ISD_SUCCESS;
	uploadDoneError = wsComm.setUploadDone(ftpSessionId, aborted, errorString);

	/*
	 * It is unlikely this will return an error, since everything went well so far,
	 * but it's still possible. We don't use the default webserviceError() here,
	 * because this is pretty serious and can lead to a lot of unfinished sessions
	 * on the server-side.
	 */
	if (uploadDoneError != ISDObject::ISD_SUCCESS) {
	    KMessageBox::error(this, i18n("Error while closing the webservice-session.\
                                           This is pretty serious and is probably a server-side error.\
                                           Please wait some time and try to send the recording again."), i18n("Error"));
	    QDialog::accept();
	    return;
	}

	switch (retVal) {
	case ISDObject::ISD_SUCCESS:
	    KMessageBox::information(this, i18n("Recording uploaded successfully."), i18n("Information"));
	    QDialog::accept();
	    break;
	case ISDObject::ISD_FTP_CANCELLED_ERROR:
	    KMessageBox::error(this, i18n("Recording upload cancelled."), i18n("Error"));
	    QDialog::accept();
	    break;
	case ISDObject::ISD_FTP_CONNECT_ERROR:
	    KMessageBox::error(this, i18n("Error while connecting to Instrudeo webservice.\n\
                                           See the console for details."), i18n("Error"));
	    QDialog::accept();
	    break;
	case ISDObject::ISD_FTP_FILE_ERROR:
	    KMessageBox::error(this, i18n("File-error while contacting Instrudeo webservice.\n\
                                           See the console for details."), i18n("Error"));
	    QDialog::accept();
	    break;
	case ISDObject::ISD_FTP_LOGIN_ERROR:
	    KMessageBox::error(this, i18n("Authentication error, check your username and password."), i18n("Error"));
	    //don't close the dialog
	    break;
	default:
	    KMessageBox::error(this, i18n("General error occurred while contacting Instrudeo webservice.\n\
                                           See the console for details."), i18n("Error"));
	    QDialog::accept();
	    break;
	}
    }
}

//-----PROTECTED CHILD CLASS-----
SRKTransmitRecordingDialog::SRKFtpProgressCallback::SRKFtpProgressCallback(KProgressDialog* progressDialog)
    : progressDialog(progressDialog)
{
}
SRKTransmitRecordingDialog::SRKFtpProgressCallback::~SRKFtpProgressCallback()
{
}
void SRKTransmitRecordingDialog::SRKFtpProgressCallback::procentDone(float procent)
{
    progressDialog->progressBar()->setProgress((int)procent);
    qApp->processEvents();
}
bool SRKTransmitRecordingDialog::SRKFtpProgressCallback::wasCancelled()
{
    return progressDialog->wasCancelled();
}

//-----PROTECTED METHODS-----
void SRKTransmitRecordingDialog::webserviceError(string errorString)
{
    QString errorMessage = i18n("Error while contacting Instrudeo webservice. (no Internet connection?).");
    if (errorString!="") {
	errorMessage += i18n("\nWebservice returned: ") + errorString;
    }
    KMessageBox::error(this, errorMessage, i18n("Error"));
}

#include "srktransmitrecordingdialog.moc"
