//
// ArrayTableSerializer.cpp
//
// $Id: //poco/Main/WebWidgets/src/ArrayTableSerializer.cpp#3 $
//
// Library: ExtJS
// Package: Core
// Module:  ArrayTableSerializer
//
// Copyright (c) 2007, 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/WebWidgets/ExtJS/ArrayTableSerializer.h"
#include "Poco/WebWidgets/ExtJS/TableRenderer.h"
#include "Poco/WebWidgets/ExtJS/Utility.h"
#include "Poco/WebWidgets/Table.h"
#include "Poco/WebWidgets/SortedTableModel.h"
#include "Poco/DateTime.h"


namespace Poco {
namespace WebWidgets {
namespace ExtJS {


void ArrayTableSerializer::serialize(std::ostream& ostr, const Table* pTable, std::size_t rowBegin, std::size_t rowCntUser, int sortCol, bool sortAscending )
{
	//[
    //    ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
    //    ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am']
	//]
	// render the row-index as last column
	SortedTableModel::Ptr pSorted;
	if (sortCol >= 0)
		pSorted = pTable->getSortedModel(static_cast<std::size_t>(sortCol), sortAscending);

	const TableModel& tm = (pSorted?*pSorted:pTable->getModel());
	const Table::TableColumns& tc = pTable->getColumns();
	if (rowCntUser == 0 && pTable->getPagingSize() > 0)
		rowCntUser = pTable->getPagingSize();
	poco_assert_dbg (tc.size() == tm.getColumnCount());

	std::size_t colCnt = tm.getColumnCount();
	std::size_t rowCnt = tm.getRowCount();
	if (rowBegin < 0)
		rowBegin = 0;
	if ((rowCntUser > 0) && (rowBegin + rowCntUser < rowCnt))
		rowCnt = rowBegin + rowCntUser;
	ostr << "{\"" << TableRenderer::FIELD_TOTALPROPERTY << "\":\"" << tm.getRowCount() << "\",";
	ostr << "\"" << TableRenderer::FIELD_ROOT << "\":[";
	for (std::size_t row = rowBegin; row < rowCnt; ++row)
	{
		if (row != rowBegin)
			ostr << ",[";
		else
			ostr << "[";
		for (std::size_t col = 0; col < colCnt; ++col)
		{
			if (col != 0)
				ostr << ",";

			// how do we distinguish if we want to write something as text or GUIElement?
			// Example: Checkbutton can be written as text "true"/"false" or as a CheckButton
			// we use the Cell: if we have a Cell set -> complex Type otherwise text
			// -> already handled by the renderer!
			const Poco::Any& aVal = tm.getValue(row, col);
			
			if (aVal.empty())
				ostr << "''";
			else
			{
				//FIXME: we have no type nfo at all, assume string for everything
				bool isString = (typeid(std::string) == aVal.type());
				Cell::Ptr ptrCell = tc[col]->getCell();
				if (isString)
					ostr << "'" << Utility::safe(RefAnyCast<std::string>(aVal)) << "'";
				else if (ptrCell)
				{
					//date must be written as string
					if (typeid(Poco::DateTime) == aVal.type())
						ostr << "'" << tc[col]->getCell()->getFormatter()->format(aVal) << "'";
					else
						ostr  << tc[col]->getCell()->getFormatter()->format(aVal);
				}
				else
					; //FIXME: 
			}
		}
		// the last column contains the rowIndx
		// with a sorted tablemodel we want the original row value
		if (pSorted)
			ostr << "," << pSorted->mapping(row);
		else
			ostr << "," << row;
		ostr << "]";
	}
	ostr << "]}";
}


const std::string& ArrayTableSerializer::contentType()
{
	static const std::string ct("text/javascript");
	return ct;
}



} } } // namespace Poco::WebWidgets::ExtJS
