/***************************************************************************
 *   Copyright (C) 2010 by Volker Lanz <vl@fidra.de>                       *
 *                                                                         *
 *   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 explied 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 Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "fileexport/exporter.h"
#include "fileexport/exporterinterface.h"
#include "fileexport/gpxexporter.h"
#include "fileexport/garmintrainingcenterexporter.h"
#include "fileexport/kmlexporter.h"

#include "veneer/url.h"

#include <QXmlStreamReader>
#include <QFile>
#include <QStringList>
#include <QFileInfo>
#include <QDebug>

static ExporterInterfaces exporters()
{
	ExporterInterfaces rval;

	rval.append(new GpxExporter());
	rval.append(new GarminTrainingCenterExporter());
	rval.append(new KmlExporter());

	return rval;
}

Exporter::Exporter(const Veneer::Url& targetUrl_, QFile* file_, const Activities& a) :
	m_TargetUrl(targetUrl_),
	m_File(file_),
	m_Activities(a),
	m_Exporters(exporters()),
	m_Status(Unknown)
{
	Q_ASSERT(m_File);

	foreach(ExporterInterface* exp, m_Exporters)
		connect(exp, SIGNAL(progress(int)), SIGNAL(progress(int)));
}

Exporter::~Exporter()
{
	qDeleteAll(m_Exporters);
	delete m_File;
}

QStringList Exporter::supportedFileFormats()
{
	QStringList rval;
	ExporterInterfaces exps = exporters();

	foreach(ExporterInterface* exp, exps)
		rval += exp->fileFormat();

	qDeleteAll(exps);

	return rval;
}

void Exporter::run()
{
	bool ok = false;
	const QString suffix = QFileInfo(m_TargetUrl.fileName()).suffix();

	QXmlStreamWriter xml(m_File);
	xml.setAutoFormatting(true);

	foreach(ExporterInterface* e, m_Exporters)
		if (e->canExport(suffix, m_Activities))
		{
			ok = e->run(xml, m_Activities);
			break;
		}

	m_File->close();

	m_Status = ok ? Success : Error;
}
