//
// Created by martin on 12.11.21.
//

#ifndef ANIMTESTBED_BLENDNODE_H
#define ANIMTESTBED_BLENDNODE_H

#include "../AnimNode.h"

struct BlendNode : public AnimNode {
  BlendNode(AnimationController* animation_controller);

  virtual ~BlendNode() {}

  AnimNode* m_input_A;
  AnimNode* m_input_B;
  float m_weight;
  bool m_sync_inputs;

  ozz::vector<ozz::math::SoaTransform> m_local_matrices_A;
  ozz::vector<ozz::math::SoaTransform> m_local_matrices_B;

  virtual void Reset() {
    m_current_time = 0.f;
  }

  virtual void UpdateIsSynced(bool is_synced) override {
    m_is_time_synced = is_synced;

    if (m_sync_inputs) {
      m_is_time_synced = true;
    }

    m_input_B->UpdateIsSynced(m_is_time_synced);
    m_input_A->UpdateIsSynced(m_is_time_synced);
  }

  virtual void EvalAnimDuration() override {
    if (m_is_time_synced) {
      m_anim_duration = (1.0f - m_weight) * m_input_A->m_anim_duration + m_weight * m_input_B->m_anim_duration;
    } else {
      assert (false);
    }
  }

  virtual void UpdateTime(float dt) {
    if (m_is_time_synced) {
      float current_time_absolute = m_current_time * m_anim_duration + dt;
      m_current_time = fmodf(current_time_absolute / m_anim_duration, 1.0);

      m_input_A->UpdateTime(m_current_time - m_input_A->m_current_time);
      m_input_B->UpdateTime(m_current_time - m_input_B->m_current_time);
    } else {
      m_current_time += dt;
      m_input_A->UpdateTime(dt);
      m_input_B->UpdateTime(dt);
    }
  }

  virtual void Evaluate(
      ozz::vector<ozz::math::SoaTransform>* local_matrices) override;

  virtual void CollectNodeOrdering (std::vector<AnimNode*>& anim_nodes) override {
    anim_nodes.push_back(this);
    m_input_A->CollectNodeOrdering(anim_nodes);
    m_input_B->CollectNodeOrdering(anim_nodes);
  }

  virtual void DrawDebugUi();
};

#endif  //ANIMTESTBED_BLENDNODE_H
