//
// 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;
  ozz::math::Transform m_root_transform_A;
  ozz::math::Transform m_root_transform_B;

  virtual void Reset() { m_time_current = 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 UpdateSyncTrack() override {
    if (m_is_time_synced) {
      m_sync_track = SyncTrack::Blend(
          m_weight,
          m_input_A->m_sync_track,
          m_input_B->m_sync_track);
    } else {
      assert(false);
    }
  }

  virtual void UpdateTime(float dt) {
    if (m_is_time_synced) {
      float sync_time_old = m_sync_track.CalcSyncFromAbsTime(m_time_current);
      m_time_current = fmodf(m_time_current + dt, m_sync_track.m_duration);
      float sync_time_dt =
          m_sync_track.CalcSyncFromAbsTime(m_time_current) - sync_time_old;

      m_input_A->m_time_current = sync_time_old;
      m_input_B->m_time_current = sync_time_old;
      m_input_A->UpdateTime(sync_time_dt);
      m_input_B->UpdateTime(sync_time_dt);
    } else {
      m_time_current += dt;
      m_input_A->UpdateTime(dt);
      m_input_B->UpdateTime(dt);
    }
  }

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

  virtual void GetInputNodes(
      std::vector<AnimNode*>& input_nodes) const override {
    input_nodes.push_back(m_input_A);
    input_nodes.push_back(m_input_B);
  };

  virtual void DrawDebugUi();
};

#endif  //ANIMTESTBED_BLENDNODE_H
