#include <stdlib.h>
#include "intro.h"

#define FONT_SIZE 36

void display_loading(void) {
  int window_width = GetRenderWidth(); 
  int window_height = GetRenderHeight(); 
  int loading_width = MeasureText("Loading...", FONT_SIZE);
  BeginDrawing();
  DrawText("Loading...", window_width - loading_width, window_height - FONT_SIZE, FONT_SIZE, RAYWHITE);
  EndDrawing();
}

Intro *load_intro(void) {
  Intro *i = malloc(sizeof(Intro));
  i->textures = malloc(sizeof(Texture) * 3);

  Image bgb = LoadImage("img/made_by_bgb.png");
  i->textures[0] = LoadTextureFromImage(bgb);
  UnloadImage(bgb);

  Image ray = LoadImage("img/made_w_raylib.png");
  i->textures[1] = LoadTextureFromImage(ray);
  UnloadImage(ray);

  Image title = LoadImage("img/title.png");
  i->textures[2] = LoadTextureFromImage(title);
  UnloadImage(title);

  i->texture_count = 3;
  i->timer = 0.;
  return i;
}

#define SLIDE_TIME 3.0
#define FADE_IN_TIME 0.5
#define FADE_OUT_TIME 0.5
void intro_display(Intro *intro) {
  float frame_time, elapsed_time, alpha;
  for (int i = 0; i < intro->texture_count; i++) {
    intro->timer = GetTime() + SLIDE_TIME;
    while((frame_time = GetTime()) < intro->timer) {
      elapsed_time = SLIDE_TIME - (intro->timer - frame_time);
      if (elapsed_time < FADE_IN_TIME)
	alpha = ((FADE_IN_TIME - elapsed_time) / FADE_IN_TIME) * 255.;
      else if (elapsed_time > SLIDE_TIME - FADE_OUT_TIME)
	alpha = ((elapsed_time - (SLIDE_TIME - FADE_OUT_TIME)) / FADE_OUT_TIME) * 255.;
      else
	alpha = 0;

      BeginDrawing();
      DrawTexture(intro->textures[i], 0, 0, WHITE);
      DrawRectangle(0, 0, 800, 450, (Color) { 0, 0, 0, alpha });
      EndDrawing();
    }
  }
}
