///////////////////////////////////////////////////////////////////////////////
//                                                         
// CegoGroupCursor.cc
// ------------------
// Cego order cursor class implementation
//      
// Design and Implementation by Bjoern Lemke
//     
// (C)opyright 2000-2025 Bjoern Lemke
//
// IMPLEMENTATION MODULE
//
// Class: CegoGroupCursor
// 
// Description: A cursor, to trace group space tables
//
// Status: CLEAN
//
///////////////////////////////////////////////////////////////////////////////

// CEGO INCLUDES
#include "CegoGroupCursor.h"
#include "CegoGroupNode.h"
#include "CegoDefs.h"

CegoGroupCursor::CegoGroupCursor(ListT<CegoField>& schema, AVLTreeT<CegoGroupNode> *pAVL)
{
    unsigned 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(); 

	unsigned *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(); 

	unsigned *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()
{
}
