#include "animation.hpp"

namespace components {
  void Animation::play() {
    if(!playing) {
      current = 0;
      subframe = 0.0f;
      playing = true;
    }
  }

  float Animation::twitching() {
    float tick = ease::sine(float(frames) / subframe * ease_rate);

    switch(easing) {
      case ease::NONE:
        return 0.0;
      case ease::SINE:
        return tick;
      case ease::OUT_CIRC:
        return ease::out_circ(tick);
      case ease::OUT_BOUNCE:
        return ease::sine(ease::out_bounce(tick));
      case ease::IN_OUT_BACK:
        return ease::sine(ease::in_out_back(tick));
      default:
        dbc::sentinel(
            fmt::format("Invalid easing {} given to animation",
              int(easing)));
    }
  }

  void Animation::step(sf::Vector2f& scale_out, sf::Vector2f& pos_out, sf::IntRect& rect_out) {
    if(playing && current < frames) {
      float tick = twitching();
      scale_out.x = std::lerp(scale_out.x, scale_out.x + scale, tick);
      scale_out.y = std::lerp(scale_out.y, scale_out.y + scale, tick);

      if(stationary) {
        pos_out.y = pos_out.y - (pos_out.y * scale_out.y - pos_out.y);
      }

      if(!simple) {
        rect_out.position.x += current * frame_width;
      }

      subframe += speed;
      current = int(subframe);
    } else if(!looped) {
      playing = false;
      current = frames - 1;
      subframe = float(frames - 1);

      if(!simple) {
        rect_out.position.x += current * frame_width;
      }
    } else {
      playing = false;
      current = 0;
      subframe = 0.0f;
    }
  }
}


namespace animation {
  using namespace components;
  using namespace textures;

  static AnimationManager MGR;
  static bool initialized = false;

  bool apply(Animation& anim, sf::Sprite& sprite) {
    sf::IntRect rect{{0,0}, {anim.frame_width, anim.frame_height}};
    sf::Vector2f scale{anim.scale, anim.scale};
    sf::Vector2f pos{0, 0};

    anim.step(scale, pos, rect);

    sprite.setTextureRect(rect);
    sprite.setPosition(pos);
    sprite.setScale(scale);

    return anim.playing;
  }

  void rotate(sf::Sprite& target, float degrees) {
    target.rotate(sf::degrees(degrees));
  }

  void center(sf::Sprite& target, sf::Vector2f pos) {
    auto bounds = target.getLocalBounds();
    target.setPosition({pos.x + bounds.size.x / 2,
        pos.y + bounds.size.y / 2});
    target.setOrigin({bounds.size.x / 2, bounds.size.y / 2});
  }

  void init() {
    if(!initialized) {
      auto animations = settings::get("animations");
      auto config = settings::get("config");
      auto& sprites = config["sprites"];

      for(auto& [name, data] : animations.json().items()) {
        try {
          auto anim = components::convert<Animation>(data);

          dbc::check(sprites.contains(name),
              fmt::format("animation '{}' doesn't have sprite, spelled wrong in config.json?", name));

          auto& sprite_config = sprites[name];

          anim.frame_width = sprite_config["frame_width"];
          anim.frame_height = sprite_config["frame_height"];

          dbc::check(anim.frame_width > 0 && anim.frame_height > 0,
              fmt::format("invalid frame width/height for animation: {}",
                name));

          MGR.animations.insert_or_assign(name, anim);
        } catch(...) {
          dbc::log(fmt::format("error in sprite config: {}", name));
          throw;
        }
      }

      initialized = true;
    }
  }

  bool has(const std::string& name) {
    return MGR.animations.contains(name);
  }

  Animation load(const std::string& name) {
    dbc::check(initialized, "You forgot to initialize animation.");
    return MGR.animations.at(name);
  }

  void configure(DinkyECS::World& world, DinkyECS::Entity entity) {
    auto sprite = world.get_if<Sprite>(entity);
    if(sprite != nullptr && animation::has(sprite->name)) {
      world.set<Animation>(entity, animation::load(sprite->name));
  }
}

  void step_animation(DinkyECS::World& world, DinkyECS::Entity entity, sf::Vector2f& scale_out, sf::Vector2f& pos_out, sf::IntRect& rect_out) {
    if(auto animation = world.get_if<components::Animation>(entity)) {
      if(animation->playing) animation->step(scale_out, pos_out, rect_out);
    }
  }

  void animate_entity(DinkyECS::World &world, DinkyECS::Entity entity) {
    if(world.has<Animation>(entity)) {
      auto& animation = world.get<Animation>(entity);
      animation.play();
    }
  }

}
