#include <assert.h>
#include "guru_meditation.h"
#include "mood_item.h"
#include "rockdodger_globals.h"
#include "random_gen.h"
#include "datafun.h"
#if DEBUG > 0
#include <stdio.h>
#endif

#define MOOD_ITEM_SPEED 0.04
#define MOOD_ITEM_TIME_GAP 30000

static sdl_surfaces_t* mood_item_surfaces;
static SDL_Surface *current_item_surface = NULL; //NULL means none active
static float mood_item_x;
static float mood_item_y;
static Uint32 mood_item_last_ticks = 0;

void *init_mood_item(void) {
  if((mood_item_surfaces = load_images_ck("mood_item.%02hx.png", 0, 255, 0)) == NULL) {
    guru_meditation(GM_FLAGS_DEADEND, GM_SS_Graphics | GM_GE_IOError | GURU_SEC_mood_item, &init_mood_item);
  }
  return mood_item_surfaces;
}

void draw_mood_item(SDL_Surface *target) {
  SDL_Rect dest;

  if(!current_item_surface && (rnd() < 1e-3) && (last_ticks - mood_item_last_ticks > MOOD_ITEM_TIME_GAP)) {
    current_item_surface = mood_item_surfaces->surfaces[(int)(mood_item_surfaces->num_surfaces * rnd())];
    mood_item_x = xsize;
    mood_item_y = rnd() * (ysize - current_item_surface->h);
  } else if(current_item_surface) { /* We still need to check if an item is active. */
    dest.x = mood_item_x;
    dest.y = mood_item_y;
    dest.w = current_item_surface->w;
    dest.h = current_item_surface->h;
    SDL_BlitSurface(current_item_surface, NULL, target, &dest);
    mood_item_x -= MOOD_ITEM_SPEED;
    if(mood_item_x < -current_item_surface->w) {
      current_item_surface = NULL;
      mood_item_last_ticks = last_ticks;
    }
  }
}
