#include "weapon.h"
#include "pilot.h"
#include "spfx.h"
#include "pause.h"

// Main thing with pausing is to allow things based on time to
// work properly when the toolkit opens a window.

int paused = 0; // Are we paused.

// From pilot.c
extern Pilot** pilot_stack;
extern int pilots;
// From space.c
extern unsigned int spawn_timer;
// From main.c
extern unsigned int gtime;

static void pilots_pause(void);
static void pilots_unpause(void);
static void pilots_delay(unsigned int delay);

// Pause the game.
void pause(void) {
  if(paused) return; // Well well.. We are paused already.

  pilots_pause();
  weapons_pause();
  spfx_pause();
  spawn_timer -= SDL_GetTicks();

  paused = 1; // We should unpause it.
}

void unpause(void) {
  if(!paused) return; // We are unpaused already.

  pilots_unpause();
  weapons_unpause();
  spfx_unpause();
  spawn_timer += SDL_GetTicks();

  paused = 0;
}

// Set the timers back.
void pause_delay(unsigned int delay) {
  pilots_delay(delay);
  weapons_delay(delay);
  spfx_delay(delay);
}

static void pilots_pause(void) {
  int i, j;
  unsigned int t = SDL_GetTicks();
  for(i = 0; i < pilots; i++) {
    pilot_stack[i]->ptimer -= t;

    pilot_stack[i]->tcontrol -= t;
    for(j = 0; j < MAX_AI_TIMERS; j++)
      pilot_stack[i]->timer[j] -= t;
  }
}

static void pilots_unpause(void) {
  int i, j;
  unsigned int t = SDL_GetTicks();
  for(i = 0; i < pilots; i++) {
    pilot_stack[i]->ptimer += t;

    pilot_stack[i]->tcontrol += t;
    for(j = 0; j < MAX_AI_TIMERS; j++)
      pilot_stack[i]->timer[j] += t;
  }
}

static void pilots_delay(unsigned int delay) {
  int i, j;
  for(i = 0; i < pilots; i++) {
    pilot_stack[i]->ptimer += delay;

    pilot_stack[i]->tcontrol += delay;
    for(j = 0; j < MAX_AI_TIMERS; j++)
      pilot_stack[i]->timer[j] += delay;
  }
}