#include "CompoundSequentialTransition.hpp"

CompoundSequentialTransition::CompoundSequentialTransition(Chart* pInitialChart) {
  iType = COMPOUND_SEQUENTIAL_TRANSITION;
  bStarted = false;
  this->pInitialChart = pInitialChart;
  pResultChart = pInitialChart;
}

CompoundSequentialTransition::~CompoundSequentialTransition() {
  while (vChildren.size() > 0) {
    std::vector<Transition*>::iterator it = vChildren.begin();

    if (it != vChildren.end()) {
      delete *it;
      vChildren.erase(it);
    }
  }

  while (vToBeDeleted.size() > 0) {
    std::vector<AlterableObject*>::iterator it = vToBeDeleted.begin();

    if (it != vToBeDeleted.end()) {
      delete *it;
      vToBeDeleted.erase(it);
    }
  }
}

void CompoundSequentialTransition::Update() {
  if (vChildren.size() > 0) {
    pInitialChart = GetActiveChart();

    if (!vChildren.at(0)->Complete()) {
      vChildren.at(0)->Update();
    }

    if (vChildren.at(0)->Complete()) {
      CompoundTransition* pTransition = (CompoundTransition*) *vChildren.begin();
      pResultChart = pTransition->GetResultChart();

      delete *vChildren.begin();
      vChildren.erase(vChildren.begin());
    }
  }
}

void CompoundSequentialTransition::Draw(QPainter* pPainter) {
  if (vChildren.size() > 0) {
    ((CompoundTransition*) vChildren.at(0))->Draw(pPainter);
  }
}

bool CompoundSequentialTransition::Complete() {
  for (unsigned int i = 0; i < vChildren.size(); i++) {
    if (!vChildren.at(i)->Complete()) {
      return false;
    }
  }

  return true;
}

Chart* CompoundSequentialTransition::GetActiveChart() {
  if (vChildren.size() > 0) {
    return ((CompoundTransition*) vChildren.at(0))->GetActiveChart();
  }

  return pInitialChart;
}