/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>

#include "MvGeoPointsModel.h"
#include "MvGeoPoints.h"


MvQGeoPointsDataModel::MvQGeoPointsDataModel()
{
	data_=0;
}

void MvQGeoPointsDataModel::dataIsAboutToChange()
{
	beginResetModel();
}

void MvQGeoPointsDataModel::setData(MvGeoPoints* data)
{		
	data_=data;

	//Reset the model (views will be notified)
	endResetModel();
}

int MvQGeoPointsDataModel::columnCount( const QModelIndex& ) const
{
	if (data_ != 0)
		return data_->ncols() + 1;

	return 0;
}

int MvQGeoPointsDataModel::rowCount( const QModelIndex& parent) const
{
	//Non-root
	if(parent.isValid() )
		return 0;

	//Root
	if (data_ != 0)
		return data_->count();

	return 0;	
}

QVariant MvQGeoPointsDataModel::data( const QModelIndex& index, int role ) const
{
	if( !index.isValid() || role != Qt::DisplayRole)		
		return QVariant();

	if(index.column() < 0 || index.column() >= data_->ncols()+1)
		return QVariant();

	if(index.column() == 0)
		return index.row()+1;

	// Get an specific row and column element
	int type;
	QString val = QString::fromStdString(data_->value(index.row(),index.column(),type));
	if ( type == eGeoVDouble )
		return val.toDouble();
	else if ( type == eGeoVLong )
		return val.toInt();

	return val;
}

QVariant MvQGeoPointsDataModel::headerData( const int section, const Qt::Orientation orient , const int role ) const
{
	if ( orient != Qt::Horizontal || role != Qt::DisplayRole)
		return QAbstractItemModel::headerData( section, orient, role );

 	if(section < 0 || (data_ && section >= data_->ncols()+1))
		return QVariant();
	
	if (section == 0)
		return QString(tr("Index"));

	// Get an specific column name
	return QString::fromStdString(data_->scol(section-1));
}

QModelIndex MvQGeoPointsDataModel::index( int row, int column, const QModelIndex& ) const
{
	if(data_ == 0 || data_->count() <= 0 || column < 0)
		return QModelIndex();
	
	return createIndex(row, column, (void*)0); 
}


QModelIndex MvQGeoPointsDataModel::parent( const QModelIndex& ) const
{			
	return QModelIndex();
}
