/***************************************************************************
 *   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 "gui/athletelogtree.h"

#include "gui/athletelogmodel.h"

#include "gui/delegates/doublespinboxdelegate.h"
#include "gui/delegates/spinboxdelegate.h"
#include "gui/delegates/timeeditdelegate.h"
#include "gui/delegates/bloodpressuredelegate.h"
#include "gui/delegates/dateeditdelegate.h"

#include "core/athletelog.h"
#include "core/profile.h"

#include "veneer/settings.h"
#include "veneer/datetime.h"
#include "veneer/locale.h"

#include "util/unit.h"

#include <QSortFilterProxyModel>
#include <QDebug>

AthleteLogTree::AthleteLogTree(QWidget* parent)
	: QTreeView(parent)
{
	AthleteLogModel* activityModel = new AthleteLogModel(this);

	QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this);
	proxyModel->setSortRole(AthleteLogModel::sortingRole);
	proxyModel->setDynamicSortFilter(true);
	proxyModel->setSourceModel(activityModel);

	setModel(proxyModel);
	connect(selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), SLOT(onSelectionChanged(const QItemSelection&, const QItemSelection&)));
	connect(model(), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), SLOT(onDataChanged(const QModelIndex&, const QModelIndex&)));

	setItemDelegateForColumn(dateCol, new DateEditDelegate(this));
	setItemDelegateForColumn(weightCol, new DoubleSpinBoxDelegate(this, 0, 400, 1, 0.5, QString(), QString(" %1").arg(Unit::weightUnit())));
	setItemDelegateForColumn(bodyFatPercentCol, new SpinBoxDelegate(this, 0, 100, 1, QString(), QString("%")));
	setItemDelegateForColumn(restingHRCol, new SpinBoxDelegate(this, 0, 300, 1, QString(), QString(" bpm")));
	setItemDelegateForColumn(maxHRCol, new SpinBoxDelegate(this, 0, 300, 1, QString(), QString(" bpm")));
	setItemDelegateForColumn(bloodPressureCol, new BloodPressureDelegate(this));
	setItemDelegateForColumn(energyConsCol, new SpinBoxDelegate(this, 0, 40000, 50, QString(), QString(" %1").arg(Unit::energyUnit())));
	setItemDelegateForColumn(sleepDurationCol, new TimeEditDelegate(this));
}

void AthleteLogTree::setProfile(const Profile* profile)
{
	sourceModel()->setProfile(profile);
}

void AthleteLogTree::onSelectionChanged(const QItemSelection&, const QItemSelection&)
{
	emit selectedAthleteLogChanged();
}

void AthleteLogTree::onDataChanged(const QModelIndex& from, const QModelIndex& idx)
{
	emit athleteLogChanged(sourceModel()->athleteLog(from), idx.column());
}

void AthleteLogTree::add(AthleteLog* a)
{
	sourceModel()->add(a);
}

void AthleteLogTree::remove(AthleteLog* a)
{
	sourceModel()->remove(a);
}

void AthleteLogTree::clear()
{
	sourceModel()->clear();
}

void AthleteLogTree::updateEntry(AthleteLog* a)
{
	sourceModel()->updateEntry(a);
}

AthleteLogs AthleteLogTree::selectedAthleteLogs()
{
	AthleteLogs rval;

	foreach(const QModelIndex& idx, selectionModel()->selectedRows(0))
	{
		const QModelIndex mappedIdx = static_cast<QSortFilterProxyModel*>(model())->mapToSource(idx);
		rval.append(sourceModel()->athleteLog(mappedIdx));
	}

	return rval;
}

void AthleteLogTree::setCurrentAthleteLog(AthleteLog* athleteLog)
{
	QModelIndex index = sourceModel()->find(athleteLog);

	index = static_cast<QSortFilterProxyModel*>(model())->mapFromSource(index);

	if (index.isValid())
	{
		setCurrentIndex(index);
		scrollTo(index);
	}
}

void AthleteLogTree::selectFirstAthleteLog()
{
	QModelIndex index = static_cast<QSortFilterProxyModel*>(model())->mapFromSource(sourceModel()->first());

	if (index.isValid())
	{
		setCurrentIndex(index);
		scrollTo(index);
	}
}

AthleteLogModel* AthleteLogTree::sourceModel()
{
	QAbstractProxyModel* proxyModel = static_cast<QAbstractProxyModel*>(model());
	return static_cast<AthleteLogModel*>(proxyModel->sourceModel());
}

const AthleteLogModel* AthleteLogTree::sourceModel() const
{
	const QAbstractProxyModel* proxyModel = static_cast<const QAbstractProxyModel*>(model());
	return static_cast<const AthleteLogModel*>(proxyModel->sourceModel());
}

// FIXME: Workaround for http://bugreports.qt.nokia.com/browse/QTBUG-1871
bool AthleteLogTree::isEditing(const QModelIndex& index) const
{
	return state() & QAbstractItemView::EditingState && currentIndex() == index;
}
