/***************************************************************************
 *   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 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 Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "devicesync/garminedgesync.h"

#include "fileimport/importer.h"
#include "fileimport/garmintrainingcenterimporter.h"

#include "veneer/device.h"

#include "util/xml.h"

#include <QFile>
#include <QDomDocument>
#include <QDomNode>
#include <QDomElement>
#include <QDir>
#include <QXmlStreamReader>
#include <QDebug>

GarminEdgeSync::GarminEdgeSync() :
	SyncInterface()
{
}

bool GarminEdgeSync::parseGarminDeviceXml(const QString& path, QString& tcxPath, QString& tcxExtension)
{
	QFile file(path + "/Garmin/GarminDevice.xml");

	if (!file.open(QIODevice::ReadOnly))
	{
		qWarning() << "could not open " << file.fileName();
		return false;
	}

	QDomDocument document;

	if (!document.setContent(&file))
	{
		qWarning() << "could not read garmin device file " << file.fileName();
		return false;
	}

	QDomNodeList nodes = document.elementsByTagName("DataType");

	for (int i = 0; i < nodes.size(); i++)
	{
		if (nodes.at(i).firstChildElement("Name").text() == "FitnessHistory")
		{
			QDomNodeList locations = nodes.at(i).toElement().elementsByTagName("Location");

			if (locations.size() != 1)
			{
				qWarning() << "<Location> not found, size is " << locations.size();
				return false;
			}

			QDomElement location = locations.at(0).toElement();
			tcxPath = location.firstChildElement("Path").text();
			tcxExtension = location.firstChildElement("FileExtension").text();
			return true;
		}
	}

	return false;
}

Sync::SyncStatus GarminEdgeSync::run(const QString& path, Activities& activities)
{
	QString tcxPath;
	QString tcxExtension;

	if (!parseGarminDeviceXml(path, tcxPath, tcxExtension))
		return Sync::ReadError;

	const QDir dir(QString("%1/%2").arg(path).arg(tcxPath));
	const QStringList fileNames = dir.entryList(QStringList() << QString("*.%1").arg(tcxExtension));

	emit totalSteps(fileNames.size() - 1);

	int count = 0;

	bool ok = false;

	GarminTrainingCenterImporter tcxImporter;
	foreach (const QString& fileName, fileNames)
	{
		QFile file(dir.absoluteFilePath(fileName));

		ok = false;

		if (file.open(QIODevice::ReadOnly))
		{
			QXmlStreamReader xml(&file);

			if (xmlReadNextStartElement(xml))
			{
				if (tcxImporter.canImport(xml.name().toString()))
					ok = tcxImporter.run(xml, activities);
			}
		}

		if (!ok)
			m_ErrorNames << fileName;

		emit progress(count++);
	}

	return Sync::Success;
}

bool GarminEdgeSync::canSync(const Veneer::Device& device)
{
	// TODO: better check if Garmin/GarminDevice.xml exists on the device.
	if (device.product().toLower().indexOf("garmin") != -1 || device.vendor().toLower().indexOf("garmin") != -1)
		return true;

	return false;
}
