///////////////////////////////////////////////////////////////////////////////
//                                                         
// CegoProcWhileStmt.cc  
// --------------------
// Cego procedure while look statement implementation
//               
// Design and Implementation by Bjoern Lemke
//                                   
// (C)opyright 2000-2025 Bjoern Lemke
//
// IMPLEMENTATION MODULE
//
// Class: CegoProcWhileStmt
//
// Description: This class implements the while statement for cego stored procedures.
//              The condition and block information is stored stored for later execution  
//
// Status: CLEAN
//
///////////////////////////////////////////////////////////////////////////////

// base includes 
#include <lfcbase/ListT.h>

// cego includes
#include "CegoProcWhileStmt.h"
#include "CegoDatabaseFormater.h"

CegoProcWhileStmt::CegoProcWhileStmt(CegoTableManager *pTabMng,
				     CegoPredicate *pPred,
				     CegoProcBlock *pBlock,
				     CegoProcBlock *pParentBlock) : CegoProcStmt(pParentBlock)
{
    _pTabMng = pTabMng;
    _pPred = pPred;
    _pBlock = pBlock;
    _pParentBlock = pParentBlock;
}

CegoProcWhileStmt::~CegoProcWhileStmt()  
{
    if ( _pBlock )
	delete _pBlock;
    if ( _pPred )
	delete _pPred;
}

void CegoProcWhileStmt::setBlock(CegoProcBlock * pBlock)
{
    _pBlock = pBlock;
}

CegoException CegoProcWhileStmt::execute()
{
    try
    {
	while ( _pPred->eval(0,0,0,0,_pBlock) )
	{
	    CegoException result;
	    result =  _pBlock->execute();
	    if ( result != NONE_EXCEP )
		return result;
	    if ( _pTabMng->isAborted() ) 
	    { 
		_pParentBlock->setExceptionMsg(Chain("Procedure aborted")); 
		return ABORT_EXCEP; 
	    } 
	}
    }
    catch ( Exception e)
    {
	Chain excepMsg = e.getBaseMsg();
	_pParentBlock->setExceptionMsg(excepMsg);
	return COREOP_EXCEP;	    
    }
    return NONE_EXCEP;
}

void CegoProcWhileStmt::cleanUp()
{
    if ( _pBlock )
	_pBlock->cleanUp();
    if ( _pPred )
	_pPred->cleanUp();
}
    
Chain CegoProcWhileStmt::toChain(unsigned defTabSetId, const Chain& indent) const
{
    Chain s;
    s = indent + Chain("while ") + _pPred->toChain(defTabSetId) + Chain("\n") + indent + Chain("begin\n");
    s += _pBlock->toChain(defTabSetId, indent + Chain(DEFAULTINDENT));
    s += indent + Chain("end");
    return s;
}

Chain CegoProcWhileStmt::dbFormat(CegoDatabaseFormater *pForm) const
{
    return pForm->formatProcWhileStmt(_pPred, _pBlock);
}

bool CegoProcWhileStmt::isStatic() const
{
    return _pBlock->isStatic();
}
