#include "ansprite.h"
#include "mystr.h"
#include "mymath.h"
#include "globals.h"


void AnimatedSprite::Reset() {
  frame=animation_speed=animation_limit=loaded=0;
}


void AnimatedSprite::Load(std::string p) {
  path = p;

  std::string cfg;
  cfg = "Graphics/" + p + "/Animations.cfg";

  if (!al_filename_exists(cfg.c_str())) {
    animation_limit = 1;
    animation_speed = 0;
    raf = 0;
  }
  else {
    ALLEGRO_CONFIG *config;
    config = al_load_config_file(cfg.c_str());

    const char *v;

    v = al_get_config_value(config, "General", "Limit");
    if (v != NULL) animation_limit = ToFloat(ToString(v));
    else animation_limit = 1;

    v = al_get_config_value(config, "General", "Speed");
    if (v != NULL) animation_speed = ToFloat(ToString(v));
    else animation_speed = 0;

    v = al_get_config_value(config, "General", "ReverseAndFront");
    if (v != NULL) raf = 1;
    else raf = 0;

    loop=1;

    v = al_get_config_value(config, "General", "NoLoop");
    if (v != NULL) loop = 0;
    else loop = 1;
  }


  int f;
  bits.clear();
  for (f=0; f!=animation_limit; f+=1) {
    frame = f;
    GenerateActualCharname();

    bits.push_back(load_cache_bitmap(act_charname));
  }

  act= bits[0];

  frame = 0;
  opacity = 1.0;

  frame_dir =1;
}


void AnimatedSprite::GenerateActualCharname() {
  act_charname = "Graphics/" + path + "/SPR" + ToString((int)frame+1) + ".png";
}


void AnimatedSprite::Update() {
  finish = false;
  if (animation_limit == 1) {
    frame = 0;
  }
  else {
    frame += (animation_speed*DeltaTime) * frame_dir;
    if (frame >= animation_limit) {
      finish = true;
      if (raf) {
        frame_dir = -frame_dir;
        frame = animation_limit-1;
      }
      else {
        if (loop) frame = 0;
        else frame=animation_limit-1;
      }
    }
    if (frame <= 0) {
      frame = 0;
      if (raf) frame_dir = -frame_dir;
    }
  }

  ChooseActualBitmap();
}


void AnimatedSprite::Copy(AnimatedSprite *an) {

  path=an->path;
  animation_limit=an->animation_limit;
  animation_speed=an->animation_speed;
  raf=an->raf;
  loop=an->loop;

  bits = an->bits;
  act_charname=an->act_charname;

  act= bits[0];
  frame = 0;
  opacity = 1.0;
  frame_dir =1;
}


void AnimatedSprite::ChooseActualBitmap() {
  if (animation_limit > 0) act= bits[(int)frame];
}


AnimatedSprite::~AnimatedSprite() {
  bits.clear();
}
