#include "MorphTransition.hpp"

MorphTransition::MorphTransition(MorphElement* pInitialMorphElement,
  MorphElement* pResultMorphElement, int iTotalSteps) {
  iType = MORPH_TRANSITION;
  bStarted = false;
  this->pInitialMorphElement = pInitialMorphElement;
  this->pResultMorphElement = pResultMorphElement;
  this->iTotalSteps = iTotalSteps;
  vMorphSteps = NULL;

  iStepsDone = 0;
}

MorphTransition::~MorphTransition() {
  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);
    }
  }

  if (vMorphSteps != NULL) {
    delete vMorphSteps;
  }
}

void MorphTransition::Update() {
  if (!bStarted) {
    Start();

    //as the vertices might have changed since the creation of the transition,
    //they are only read when needed
    glm::vec4* vInitialVertices = pInitialMorphElement->GetAllPoints();
    glm::vec4* vResultVertices = pResultMorphElement->GetAllPoints();

    int iInitialVertexCount = pInitialMorphElement->GetVertexCount();
    int iResultVertexCount = pResultMorphElement->GetVertexCount();

    if (iInitialVertexCount == iResultVertexCount) {
      vMorphSteps = new glm::vec2[iInitialVertexCount];

      for (int i = 0; i < iInitialVertexCount; i++) {
        glm::vec4 vInitialVertex = vInitialVertices[i];
        glm::vec4 vResultVertex = vResultVertices[i];

        vMorphSteps[i] = glm::vec2((vResultVertex.x - vInitialVertex.x) / (float) iTotalSteps,
          (vResultVertex.y - vInitialVertex.y) / (float) iTotalSteps);
      }
    }
  }

  pInitialMorphElement->Morph(vMorphSteps);
  iStepsDone++;
}

bool MorphTransition::Complete() {
  if ((bStarted) && (iStepsDone >= iTotalSteps)) {
    return true;
  }
  else {
    return false;
  }
}