/*@@@**************************************************************************
* \file  drawingListHandler
* \author Hernan Badino
* \date  Wed Apr  8 12:59:56 GMT 2009
* \notes 
*******************************************************************************
******************************************************************************/

/* INCLUDES */
#include "operator.h"
#include "drawingListHandler.h"
#include "displayTreeNode.h"
#include "globalDefs.h"
#include "logger.h"

using namespace VIC;

CDrawingListHandler::CDrawingListHandler()
        : m_root_p (                NULL ),
          m_drawingListChanged_b ( false )
{
    //m_root_p = new CDisplayTreeNode ( NULL, NULL );
}

CDrawingListHandler::~CDrawingListHandler()
{
    delete m_root_p;    
}

CDrawingList * 
CDrawingListHandler::getDrawingList ( std::string  f_name_str, 
                                      COperator *  f_op_p )
{
    if (not f_op_p) return NULL;    

    COperator *  ops_p[MAX_OPERATOR_LEVELS];
    int level_i;

    /// Build list of parent operators.
    ops_p[0] = f_op_p;

    for (level_i = 1;
         level_i < MAX_OPERATOR_LEVELS; 
         ++level_i)
    {
        ops_p[level_i] = ops_p[level_i-1] -> getParentOp();
        if ( not ops_p[level_i] )
            break;
    }

    if ( level_i == MAX_OPERATOR_LEVELS )
    {
        char str[256];
        sprintf( str, 
                 "The maximal amount of operator levels of %i has been achieved.",
                 MAX_OPERATOR_LEVELS  );
        logger::warn ( str );
    }

    --level_i;

    if ( not m_root_p )
        m_root_p = new CDisplayOpNode( ops_p[level_i] );
    //else
    //consistency check can be made here.

    CDisplayOpNode * node_p   = m_root_p;
    CDisplayOpNode * parent_p = node_p;

    while ( level_i > 0 )
    {
        /// Consistency check can be made here between node_p->m_data.operator_p and ops_p[level_i]
        --level_i;
        parent_p = node_p;
        node_p   = node_p -> getOpChild ( ops_p[level_i] );
        if ( !node_p ) break;
    }

    if ( !node_p )
    {
        node_p = parent_p;
        while ( level_i >= 0 )
        {
            CDisplayOpNode *  newChild_p = new CDisplayOpNode ( ops_p[level_i--] );
            node_p -> appendChild ( newChild_p );
            node_p = newChild_p;    
        }
    }
    
    /// Search now for display.
    CDisplayNode * child_p = node_p -> getDisplayChild ( f_name_str );

    if (!child_p)
    {
        CDrawingList * drawList_p = (CDrawingList *) new CDrawingList ( f_name_str );
        child_p    = new CDisplayNode ( drawList_p );
        node_p -> appendChild ( child_p );
        return drawList_p;
    }

    return child_p -> getDrawingList();
}


/* ////////////  Version History ///////////////
 *  $Log: drawingListHandler.cpp,v $
 *  Revision 1.2  2009/11/18 15:50:15  badino
 *  badino: global changes.
 *
 *//////////////////////////////////////////////
