#include "KGF.h"





SpriteAnimation::SpriteAnimation(std::string nm, std::string int_nm, float sp, float lp, float bd) {
  name = nm;
  internal_name  = int_nm;
  speed = sp;
  loop = lp;
  bidirectional = bd;

  std::string spr_name;

  std::vector<std::string> list;
  std::vector<std::string>::iterator it;

  list = ReturnFiles((nm).c_str());

  for (it=list.begin();it!=list.end();it++) {
    bits.push_back(GetBitmap(nm+"/"+(*it)));
  }

  Start();
}



void SpriteAnimation::Update() {
  finished = false;
  if (dir == 0) finished = true;
  frame += (speed*dir) * DeltaTime;
  float l;
  l=(bits.size()-1);

  if (frame > l) {
    if (bidirectional) {
      frame = l;
      dir *= -1;
    }
    else if (loop) {
      frame = 0;
    }
    else {
      dir = 0;
      frame = l;
    }
  }

  if (frame < 0) {
    if (bidirectional) {
      frame = 0;
      if (loop) dir *= -1;
      else dir = 0;
    }
  }
}



AnimatedSprite::AnimatedSprite(std::string name) {
  FILE *fp;
  std::vector<std::string> animation;
  if (FileExists(name + "/animations.txt")) fp = fopen((name + "/animations.txt").c_str(), "r+");
  else Error(name + "/animations.txt doesn't exist.");

  char str[512];
  while (fgets(str, 512, fp) != NULL) {
    animation = GetParameters(ToString(str));
    if (animation.size() >= 4) {
      animations.push_back(new SpriteAnimation(name + "/" + animation[0], animation[0], ToFloat(animation[1]), ToInteger(animation[2]), ToInteger(animation[3])));
    }
    else {
    }
  }
  fclose(fp);

  actual_animation=NULL;
  if (animations.size() > 0) actual_animation = animations[0];
}


void AnimatedSprite::Update() {
  if (actual_animation != NULL) {
    actual_animation->Update();
  }
}
