/*
 * AXFStateMachineInternal.cpp
 */

#include "AXFStateMachineInternal.hpp"
#include <stdio.h>

using namespace ax;


AXFStateMachineInternal::AXFStateMachineInternal()
    : m_actor(NULL),
      m_state(-1),
      m_stateMax(0),
      m_stateFuncResult(AXFACTOR_SUCCESS) {
}

AXFStateMachineInternal::~AXFStateMachineInternal() {
}

int AXFStateMachineInternal::setStateInfo(AXFActor* obj, int initState,
                                  int maxState) {
  if (obj == NULL) {
    return -1;
  }

  if (initState < 0) {
    return -1;
  }

  int vector_max_size = m_stateTable.max_size();
  if ((maxState <= 0) || (maxState > vector_max_size)) {
    return -1;
  }

  m_actor = obj;
  m_state = initState;
  m_stateMax = maxState;

  m_stateTable.resize(maxState);

  return 0;
}

void AXFStateMachineInternal::setStateTable(
    int registState, const AXFActor::StateTable* stateTable) {

  if (m_actor == NULL) {
    return;
  }

  if ((registState < 0) || (m_stateMax <= registState)) {
    return;
  }

  m_stateTable[registState].stateTable = stateTable;
}

void AXFStateMachineInternal::setNextState(int nextState) {
  if ((0 > nextState) || (m_stateMax <= nextState)) {
    return;
  }

  // 次の状態を設定
  m_state = nextState;
}

actorFuncStatus AXFStateMachineInternal::doHandler(AXFEvent_t eventId,
                                           const void *pParam, int size) {
  // ハンドルの登録をチェックし、未登録か判断する
  if (m_actor == NULL) {
    m_stateFuncResult = AXFACTOR_STATE_ERROR_NOREGIST;
    return m_stateFuncResult;
  }

#if 0 // bbtest
		std::string strFullActNm = m_actor->getNameObject().getFullActorName();
#endif

  if (m_stateTable[m_state].stateTable == NULL) {
    m_stateFuncResult = AXFACTOR_STATE_ERROR_NOFUNCTION;
    return m_stateFuncResult;
  }

  AXFEvent_t doEvent;
  for (int i = 0; (m_stateTable[m_state].stateTable[i].pFunc != NULL) && (i >= 0); i++) {
    doEvent = m_stateTable[m_state].stateTable[i].doEvent;
    if (doEvent == eventId) {
      // メンバ関数の実行
      m_stateFuncResult = (m_actor->*m_stateTable[m_state].stateTable[i].pFunc)(pParam, size);
      return m_stateFuncResult;
    }
  }

  m_stateFuncResult = AXFACTOR_STATE_ERROR_NOFUNCTION;
  return m_stateFuncResult;
}

int AXFStateMachineInternal::getCurrentState() {
  return m_state;
}

ax::actorFuncStatus AXFStateMachineInternal::getExecutionResult() {
  return m_stateFuncResult;
}
