//
// RecordSet.cpp
//
// $Id: //poco/Main/Data/src/RecordSet.cpp#2 $
//
// Library: Data
// Package: DataCore
// Module:  RecordSet
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
// 
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//


#include "Poco/Data/RecordSet.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/RowFilter.h"
#include "Poco/Data/Date.h"
#include "Poco/Data/Time.h"
#include "Poco/Data/DataException.h"
#include "Poco/DateTime.h"


using namespace Poco::Data::Keywords;
using Poco::DateTime;


namespace Poco {
namespace Data {


RecordSet::RecordSet(const Statement& rStatement): 
	Statement(rStatement),
	_currentRow(0),
	_pBegin(new RowIterator(this, 0 == rowsExtracted())),
	_pEnd(new RowIterator(this, true)),
	_pFilter(0)
{
}


RecordSet::RecordSet(Session& rSession, 
	const std::string& query, 
	RowFormatter* pRowFormatter): 
	Statement((rSession << query, now)),
	_currentRow(0),
	_pBegin(new RowIterator(this, 0 == rowsExtracted())),
	_pEnd(new RowIterator(this, true)),
	_pFilter(0)
{
	if (pRowFormatter) setRowFormatter(pRowFormatter);
}


RecordSet::RecordSet(const RecordSet& other):
	Statement(other.impl().duplicate()),
	_currentRow(other._currentRow),
	_pBegin(new RowIterator(this, 0 == rowsExtracted())),
	_pEnd(new RowIterator(this, true)),
	_pFilter(other._pFilter)
{
}


RecordSet::~RecordSet()
{
	delete _pBegin;
	delete _pEnd;
	if(_pFilter) _pFilter->release();

	RowMap::iterator it = _rowMap.begin();
	RowMap::iterator end = _rowMap.end();
	for (; it != end; ++it) delete it->second;
}


Poco::Dynamic::Var RecordSet::value(std::size_t col, std::size_t row, bool useFilter) const
{
	if (useFilter && isFiltered() && !isAllowed(row))
		throw InvalidAccessException("Row not allowed");

	if (isNull(col, row)) return Poco::Dynamic::Var();

	switch (columnType(col))
	{
		case MetaColumn::FDT_BOOL:      return value<bool>(col, row, useFilter);
		case MetaColumn::FDT_INT8:      return value<Int8>(col, row, useFilter);
		case MetaColumn::FDT_UINT8:     return value<UInt8>(col, row, useFilter);
		case MetaColumn::FDT_INT16:     return value<Int16>(col, row, useFilter);
		case MetaColumn::FDT_UINT16:    return value<UInt16>(col, row, useFilter);
		case MetaColumn::FDT_INT32:	    return value<Int32>(col, row, useFilter);
		case MetaColumn::FDT_UINT32:    return value<UInt32>(col, row, useFilter);
		case MetaColumn::FDT_INT64:     return value<Int64>(col, row, useFilter);
		case MetaColumn::FDT_UINT64:    return value<UInt64>(col, row, useFilter);
		case MetaColumn::FDT_FLOAT:     return value<float>(col, row, useFilter);
		case MetaColumn::FDT_DOUBLE:    return value<double>(col, row, useFilter);
		case MetaColumn::FDT_STRING:    return value<std::string>(col, row, useFilter);
		case MetaColumn::FDT_BLOB:      return value<BLOB>(col, row, useFilter);
		case MetaColumn::FDT_CLOB:      return value<CLOB>(col, row, useFilter);
		case MetaColumn::FDT_DATE:      return value<Date>(col, row, useFilter);
		case MetaColumn::FDT_TIME:      return value<Time>(col, row, useFilter);
		case MetaColumn::FDT_TIMESTAMP: return value<DateTime>(col, row);
		default:
			throw UnknownTypeException("Data type not supported.");
	}
}


Poco::Dynamic::Var RecordSet::value(const std::string& name, std::size_t row, bool useFilter) const
{
	if (useFilter && isFiltered() && !isAllowed(row))
		throw InvalidAccessException("Row not allowed");

	if (isNull(metaColumn(name).position(), row)) return Poco::Dynamic::Var();

	switch (columnType(name))
	{
		case MetaColumn::FDT_BOOL:      return value<bool>(name, row, useFilter);
		case MetaColumn::FDT_INT8:      return value<Int8>(name, row, useFilter);
		case MetaColumn::FDT_UINT8:     return value<UInt8>(name, row, useFilter);
		case MetaColumn::FDT_INT16:     return value<Int16>(name, row, useFilter);
		case MetaColumn::FDT_UINT16:    return value<UInt16>(name, row, useFilter);
		case MetaColumn::FDT_INT32:	    return value<Int32>(name, row, useFilter);
		case MetaColumn::FDT_UINT32:    return value<UInt32>(name, row, useFilter);
		case MetaColumn::FDT_INT64:     return value<Int64>(name, row, useFilter);
		case MetaColumn::FDT_UINT64:    return value<UInt64>(name, row, useFilter);
		case MetaColumn::FDT_FLOAT:     return value<float>(name, row, useFilter);
		case MetaColumn::FDT_DOUBLE:    return value<double>(name, row, useFilter);
		case MetaColumn::FDT_STRING:    return value<std::string>(name, row, useFilter);
		case MetaColumn::FDT_BLOB:      return value<BLOB>(name, row, useFilter);
		case MetaColumn::FDT_DATE:      return value<Date>(name, row, useFilter);
		case MetaColumn::FDT_TIME:      return value<Time>(name, row, useFilter);
		case MetaColumn::FDT_TIMESTAMP: return value<DateTime>(name, row, useFilter);
		default:
			throw UnknownTypeException("Data type not supported.");
	}
}


Row& RecordSet::row(std::size_t pos)
{
	std::size_t rowCnt = rowCount();
	if (0 == rowCnt || pos > rowCnt - 1)
		throw RangeException("Invalid recordset row requested.");

	RowMap::const_iterator it = _rowMap.find(pos);
	Row* pRow = 0;
	std::size_t columns = columnCount();
	if (it == _rowMap.end())
	{
		if (_rowMap.size())
		{
			//reuse first row column names and sorting fields to save some memory 
			pRow = new Row(_rowMap.begin()->second->names(),
				_rowMap.begin()->second->getSortMap(),
				getRowFormatter());

			for (std::size_t col = 0; col < columns; ++col)
				pRow->set(col, value(col, pos));
		}
		else 
		{
			pRow = new Row;
			pRow->setFormatter(getRowFormatter());
			for (std::size_t col = 0; col < columns; ++col)
				pRow->append(metaColumn(static_cast<UInt32>(col)).name(), value(col, pos));
		}

		_rowMap.insert(RowMap::value_type(pos, pRow));
	}
	else 
	{
		pRow = it->second;
		poco_check_ptr (pRow);
	}

	return *pRow;
}


std::size_t RecordSet::rowCount() const
{
	poco_assert (extractions().size());
	std::size_t rc = totalRowCount();
	if (!isFiltered()) return rc;

	std::size_t counter = 0;
	for (int row = 0; row < rc; ++row)
	{
		if (isAllowed(row)) ++counter;
	}

	return counter;
}


bool RecordSet::isAllowed(std::size_t row) const
{
	if (!isFiltered()) return true;
	return _pFilter->isAllowed(row);
}


bool RecordSet::moveFirst()
{
	if (totalRowCount() > 0)
	{
		if (!isFiltered())
		{
			_currentRow = 0;
			return true;
		}

		std::size_t currentRow = _currentRow;
		currentRow = 0;
		while (!isAllowed(currentRow))
		{
			if (currentRow >= totalRowCount() - 1) return false;
			++currentRow;
		}

		_currentRow = currentRow;
		return true;
	}
	else return false;
}


bool RecordSet::moveNext()
{
	std::size_t currentRow = _currentRow;
	do
	{
		if (currentRow >= totalRowCount() - 1) return false;
		++currentRow;
	} while (isFiltered() && !isAllowed(currentRow));

	_currentRow = currentRow;
	return true;
}


bool RecordSet::movePrevious()
{
	std::size_t currentRow = _currentRow;
	do
	{
		if (currentRow <= 0) return false;
		--currentRow;
	} while (isFiltered() && !isAllowed(currentRow));

	_currentRow = currentRow;
	return true;
}


bool RecordSet::moveLast()
{
	if (totalRowCount() > 0)
	{
		std::size_t currentRow = _currentRow;
		currentRow = totalRowCount() - 1;
		if (!isFiltered())
		{
			_currentRow = currentRow;
			return true;
		}

		while (!isAllowed(currentRow))
		{
			if (currentRow <= 0) return false;
			--currentRow;
		}

		_currentRow = currentRow;
		return true;
	}
	else return false;
}


std::ostream& RecordSet::copyValues(std::ostream& os, std::size_t offset, std::size_t length) const
{
	if (length == RowIterator::POSITION_END) 
	{
		if (0 != offset) throw RangeException("Invalid range.");
		length = rowCount();
	}

	RowIterator itBegin = *_pBegin + offset;
	RowIterator itEnd = itBegin + length;
	std::copy(itBegin, itEnd, std::ostream_iterator<Row>(os));
	return os;
}


std::ostream& RecordSet::copy(std::ostream& os) const
{
	const RowFormatter& ri = (*_pBegin)->getFormatter();
	os << ri.prefix();
	copyNames(os);
	copyValues(os);
	os << ri.postfix();
	return os;
}


void RecordSet::filter(RowFilter* pFilter)
{
	if (_pFilter) _pFilter->release();
	_pFilter = pFilter;
	if(_pFilter) _pFilter->duplicate();
}


bool RecordSet::isFiltered() const
{
	return _pFilter && !_pFilter->isEmpty();
}


} } // namespace Poco::Data
