///////////////////////////////////////////////////////////////////////////////
//                                                         
// CegoGroupCursor.cc
// -------------------
// Cego order cursor class implementation
//      
// Design and Implementation by Bjoern Lemke
//     
// (C)opyright 2000-20010 Bjoern Lemke
//
// 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, 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; see the file COPYING.  If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// IMPLEMENTATION MODULE
//
// Class: CegoGroupCursor
// 
// Description: A cursor, to trace group space tables
//
// Status: QG-2.6
//
///////////////////////////////////////////////////////////////////////////////

#include "CegoGroupCursor.h"
#include "CegoGroupNode.h"
#include "CegoDefs.h"

CegoGroupCursor::CegoGroupCursor(ListT<CegoField>& schema, AVLTreeT<CegoGroupNode> *pAVL)
{
    int idx=0;
    CegoField *pF = schema.First();
    while ( pF )
    {
	if ( pF->getTableAlias() == Chain(AVG_GROUP) )
	{
	    _avgIdxList.Insert(idx);
	}
	pF = schema.Next();
	idx++;
    }
    _pAVL = pAVL;
}

CegoGroupCursor::~CegoGroupCursor()
{
}

bool CegoGroupCursor::getFirst(ListT<CegoField>& fl)
{
    CegoGroupNode *pN = _pAVL->First();
    
    if ( pN )
    {

	fl = pN->getKey() + pN->getGrouping(); 

	int *pI = _avgIdxList.First();
	while ( pI )
	{
	    CegoFieldValue fv = fl[*pI].getValue();
	    CegoFieldValue countValue = fl[fl.Size() - 1 ].getValue();
	    fv = fv / countValue;
	    fl[*pI].setValue(fv);
	    pI = _avgIdxList.Next();
	}

	return true;
    }
    return false;
}

bool CegoGroupCursor::getNext(ListT<CegoField>& fl)
{

    CegoGroupNode *pN = _pAVL->Next();
    
    if ( pN )
    {

	fl = pN->getKey() + pN->getGrouping(); 

	int *pI = _avgIdxList.First();
	while ( pI )
	{
	    CegoFieldValue fv = fl[*pI].getValue();
	    CegoFieldValue countValue = fl[fl.Size() - 1 ].getValue();
	    fv = fv / countValue;
	    fl[*pI].setValue(fv);
	    pI = _avgIdxList.Next();
	}

	return true;
    }
    return false;

}

void CegoGroupCursor::abort()
{
}
