/* Animation Rendering Logics */

int frameCount = 0;
char previousAnicode = 'a';

//Handle animation rendering
void handleAnimationRendering(char anicode) {
  if (previousAnicode != anicode){
    previousAnicode = anicode;
    frameCount = 0;
  }
  //Check if the target animation frame is static
  String targetFrame = "/" + String(anicode) + ".bin";
  if (SD.exists(targetFrame)) {
    //This is a static frame. Load and render it
    loadFrameAndRender(targetFrame);
    delay(getFrameDuration(anicode,0));
    return;
  }

  //It is not a static frame. Check if x0.bin exists
  targetFrame = "/" + String(anicode) + String(frameCount) + ".bin";
  if (SD.exists(targetFrame)) {
    loadFrameAndRender(targetFrame);
    frameCount++;
    delay(getFrameDuration(anicode,frameCount));
    return;
  } else {
    //Not found.
    if (frameCount != 0) {
      loadFrameAndRender("/" + String(anicode) + "0.bin");
      delay(getFrameDuration(anicode,0));
      frameCount = 1;
      return;
    } else {
      //frameCount = 0. x0.bin not exists. Report error
      Serial.println("Target frame buffer not found: " + String(anicode) + ".bin");
      setAnimationCode('a');
      return;
    }
  }
}

//Get how long the frame shd last. 
//Default 500 unless specially programmed
int getFrameDuration(char anicode, int framecount){
  if ((anicode == 'a' || anicode == 'b') && framecount == 0){
    return 2500;
  }
  return 500;
}
