// $Id: b_context.cpp,v 1.4 2003/03/16 14:50:58 fukasawa Exp $

//=============================================================================
/**
 *  @file    b_context.cpp
 *
 *  @author Fukasawa Mitsuo
 *
 *
 *    Copyright (C) 1998-2003 BEE Co.,Ltd. All rights reserved.
 *
 * 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
 * of the License, 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; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
//=============================================================================

#define BEE_BUILD_DLL

#include "state/b_trigger.h"
#include "state/b_state.h"
#include "state/b_transition.h"
#include "state/b_context.h"

RootState b_context::Root(_TX("/"));

//------------------------------------------------------------------------------
// Constructor/Destructor
//------------------------------------------------------------------------------
b_context::b_context(const string& name) : m_name(name)
{
}

//------------------------------------------------------------------------------
// Update the current state
//------------------------------------------------------------------------------
int b_context::update(b_state * current)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::update");
    ACE_UNUSED_ARG(current);
    return 0;
}

//------------------------------------------------------------------------------
// Append sub state
//------------------------------------------------------------------------------
int b_context::append(b_state * state, string& trigger,
                      b_transition * trans)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::append");

    if ((state->isConditional() || state->isHistorical() || state->isFixed()) &&
        (trigger.size() > 0))
    {   // Marking trigger/transition in node
        state->m_trigger = true;
        state->m_transitions.push_back(trans);
    }
    else
    {
        b_transition * curTrans = m_table[state->name()][trigger];
        if (curTrans == NULL)
        {
            m_table[state->name()][trigger] = trans;
        }
        else
        {   // The taransition has already registered.
        }
    }
    m_states[state->name()] = state;

    int trigid = m_triggers.size() + 1;
    m_triggers.insert(TriggerPair(trigger, trigid));

    return 0;
}

//-----------------------------------------------------------------------------
// Enty transition table
//-----------------------------------------------------------------------------
int b_context::makeStateTable()
{
    TRACE_FUNCTION(TRL_LOW, "b_context::makeStateTable");

    // Making tree od state
    vector<string> names;
    StateDictionary::iterator iter = m_states.begin();
    for ( ; iter != m_states.end(); iter++)
    {
        names.push_back((*iter).first);
    }
    std::sort(names.begin(), names.end());
    b_state * stp = this->state(names[0]);
    if (! stp->isRoot())
    {
        TRACE_ERROR((_TX("First node is not root!\n")));
        return -1;
    }
    m_root = reinterpret_cast<b_rootnode *>(stp);   // set root state
    for (size_t i = 0; i < names.size(); i++)
    {
        b_state * curState = this->state(names[i]);
        if (curState->isEdge())
        {   // not node state
            continue;
        }
        for (size_t j = i+1; j < names.size(); j++)
        {
            if (curState->isChild(names[j]))
            {
                b_state * childState = this->state(names[j]);
                ((b_statenode *)curState)->append(childState);
                childState->parent(curState);
            }
        }
        if (curState->m_trigger)
        {   // Set trigger to edge state, trigger was defined anscestral node.
            for (size_t l = i+1; l < names.size(); l++)
            {
                b_state * descendState = this->state(names[l]);
                if (curState->isDescendant(names[l]) && descendState->isEdge())
                {
                    for (size_t m = 0; m < curState->m_transitions.size(); m++)
                    {
                        b_transition * trans = curState->m_transitions[m];
                        b_transition * genTrans = trans->generate(descendState->m_base);
                        b_transition * curTrans = m_table[curState->name()][trans->trigger()];
                        if (curTrans == NULL)
                        {
                            m_table[descendState->name()][trans->trigger()] = genTrans;
                        }
                        else
                        {   // The taransition has already registered.
                        }
                    }
                }
            }
        }
    }

    return 0;
}

//------------------------------------------------------------------------------
// Change current state
//------------------------------------------------------------------------------
int b_context::change(const string& stateName)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::change");

    b_state * stp = m_states[stateName];
    if (stp != NULL)
    {   // entry the state
        m_root->change(stp);
        return BEE_SUCCESS;
    }
    else
    {
        return BEE_ERROR;
    }
}

//------------------------------------------------------------------------------
// Check to be enable triger or not
//------------------------------------------------------------------------------
int b_context::enable(const string& trigName)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::enable");

    TriggerMap::iterator iter = m_triggers.find(trigName);
    if (iter == m_triggers.end())
    {
        return -1;
    }

    int stateq = m_root->size();
    for (int i = 0; i < stateq; i++)
    {
        b_state * curState = this->currentState(i);
        b_transition * trans = m_table[curState->name()][trigName];
        if (trans != NULL)
        {
            return 0;
        }
        else
        {   // Retrieve parent node
            b_state * par = curState->parent();
            while (par != NULL && (! par->isRoot()))
            {
                trans = m_table[par->name()][trigName];
                if (trans != NULL)
                {   // Found state and trigger
                    return 0;
                }
                par = par->parent();              // Set upper node
            }
        }
    }
    return -2;
}

//------------------------------------------------------------------------------
// Accept Trigger
//------------------------------------------------------------------------------
int b_context::accept(b_trigger * trigger)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::accept");

    int stateq = m_root->size();
    int i;
    for (i = 0; i < stateq; i++)
    {
        b_state * curState = this->currentState(i);

        b_transition * trans = m_table[curState->name()][trigger->name()];
        if (trans == NULL)
        {   // Retrieve parent node
            b_state * par = curState->parent();
            while (par != NULL && (! par->isRoot()))
            {
                trans = m_table[par->name()][trigger->name()];
                if (trans != NULL)
                {   // Found state and trigger
                    break;
                }
                par = par->parent();              // Set upper node
            }
            if (trans == NULL)
            {   // goto root node
                continue;
            }
        }
        //
        // Accept trigger
        const BCHAR * newName = trans->act(this, trigger);
        if ((newName != NULL) /* && (curState->name() != newName) */ )
        {   // Change new state or Reenter current stare
            b_state * newState = this->state(newName);
            if (newState != NULL)
            {
                this->acceptNext(curState, newState, trigger);
            }
        }
        break;
    }
    if (i == stateq)
    {   // Unexpected trigger
        return this->unexpect(trigger);
    }

    return BEE_SUCCESS;
}

//------------------------------------------------------------------------------
// Accept Event (chage new state)
//------------------------------------------------------------------------------
int b_context::acceptNext(b_state * curState, b_state * newState,
                          b_trigger * trigger)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::acceptNext");

    string transName = _TX("");
    b_state * transState;

    ACE_DEBUG((LM_DEBUG, _TX("%s::acceptNext :%s < %s > %s\n"),
                         this->m_name.c_str(), curState->charName(),
                         trigger->charName(), newState->charName()));

    // Exit current state
    curState->end(trigger);               // call exit current state

    b_state * prevState = curState;
    int relate = curState->relationship(newState, transName);
                             // if trans_name is "", maybe goto null ("/")
    while (relate != b_state::SAME_STATE && transName != _TX(""))
    {
        if (relate == b_state::OTHER_STATE)
        {
            TRACE_ERROR((_TX("Illegal transition state: %s \n"),
                         transName.c_str()));
            return BEE_ERROR;
        }
        transState = this->state(transName);
        BEEAssert(transState != NULL);
//
        if (transState->isHistorical() &&
            transState->isChild(prevState->name()))
        {
            transState->pass();
        }
//
        transState->transit(prevState, newState);
        relate = transState->relationship(newState, transName);
        prevState = transState;
    }

    if (newState->isConditional() || newState->isFixed() ||
        newState->isHistorical())
    {   // Conditional Node
        b_state * childState;
        const BCHAR * child = newState->next(trigger);
        while (child != NULL)
        {
            string childName = child;
            childState = this->state(childName);
            if (! (childState->isConditional() || childState->isFixed() ||
                   childState->isHistorical()))
                break;
            child = childState->next(trigger);
        }
        if (child == NULL)
        {
            TRACE_ERROR((_TX("Return null state: %s \n"),
                         newState->charName()));
            return BEE_ERROR;
        }
        newState = childState;
        this->update(newState);
        newState->begin(curState, trigger);  // Enter new state
    }
    else
    {   // Terminate or History state
        this->update(newState);
        newState->begin(curState, trigger);  // Enter new state
    }

    // Update new state in root
    this->m_root->change(newState);

    // TRACE_DEBUG((_TX("Teminate state: %s \n"), newState->charName()));

    return BEE_SUCCESS;
}

//------------------------------------------------------------------------------
// Undefined State/Event
//------------------------------------------------------------------------------
int b_context::unexpect(b_trigger * trigger)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::unexpect");

    for (int i = 0; i < m_root->size(); i++)
    {
        ACE_ERROR((LM_ERROR, _TX("%s::unexpected: state(%s) <- trigger(%s)\n"),
                             m_name.c_str(), this->current(i).c_str(),
                             trigger->charName()));
    }

    return BEE_ERROR;
}

//-----------------------------------------------------------------------------
// Start .
//-----------------------------------------------------------------------------
int b_context::start()
{
    TRACE_FUNCTION(TRL_LOW, "b_context::start");
    b_trigger trigger(TRIGGER_START);
    return this->put(&trigger);
}

//-----------------------------------------------------------------------------
// Put trigger to service thread.
//-----------------------------------------------------------------------------
int b_context::put(b_trigger * trigger)
{
    TRACE_FUNCTION(TRL_LOW, "b_context::put");

    return this->accept(trigger);
}

//------------------------------------------------------------------------------
// Dump
//------------------------------------------------------------------------------
void b_context::dump() const
{
    ACE_DEBUG((LM_DEBUG, ACE_TEXT("%s root state \n"), m_name.c_str()));
    for (int i = 0; i < m_root->size(); i++)
    {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("current state is %s.\n"),
                             m_root->current(i).c_str()));
    }
    b_matrix<b_transition *>::const_iterator iter;
    for (iter = m_table.begin(); iter != m_table.end(); ++iter)
    {
        b_transition * trans = m_table.value(iter);
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("transition (%s): %s : %s.\n"),
                             trans->charName(),
                             trans->stateName().c_str(),
                             trans->trigger().c_str()));
    }
}

