/* input.c
 *
 * Receives input from the user.
 *
 * (c) 2006, Joseph Curtis
 */

#include "input.h"
#include "display.h"
#include "world.h"

#ifndef x86
#include <pspdebug.h>
//#define printf pspDebugScreenPrintf
#endif

extern struct display *default_display;
extern struct world *default_world;

int input_loop() {
  int i;

  printf("input_loop: ");

#ifndef x86
  SceCtrlData pad;

  update(default_display, default_world);

  while (1) {
    sceCtrlReadBufferPositive(&pad, 1);
    if (pad.Buttons & PSP_CTRL_LEFT) {
      ctrl_left();
      update(default_display, default_world);
    } else if (pad.Buttons & PSP_CTRL_RIGHT) {
      ctrl_right();
      update(default_display, default_world);
    } else if (pad.Buttons & PSP_CTRL_UP) {
      ctrl_up();
      update(default_display, default_world);
    } else if (pad.Buttons & PSP_CTRL_DOWN) {
      ctrl_down();
      update(default_display, default_world);
    } else if (pad.Buttons & PSP_CTRL_LTRIGGER) {
      ctrl_ltrigger();
      update(default_display, default_world);
    } else if (pad.Buttons & PSP_CTRL_RTRIGGER) {
      ctrl_rtrigger();
      update(default_display, default_world);
    } else if ((pad.Lx < 96 || pad.Lx > 160) || (pad.Ly < 96 || pad.Ly > 160)) {
      /* Analogue stick, converted to signed char */
      crtl_analogue((pad.Lx - 128), (pad.Ly - 128));
      update(default_display, default_world);
    }

    if (pad.Buttons)
      for (i=0;i<15;i++)
	sceDisplayWaitVblankStart();

  }
#endif

  update(default_display, default_world);

}

void ctrl_left() {
  if(default_world->armies[0].a[0].x > 0)
    default_world->armies[0].a[0].x--;
}

void ctrl_right() {
  if (default_world->armies[0].a[0].x < (default_world->width - 1))
    default_world->armies[0].a[0].x++;
}

void ctrl_up() {
  if(default_world->armies[0].a[0].y > 0)
    default_world->armies[0].a[0].y--;
}

void ctrl_down() {
  if (default_world->armies[0].a[0].y < (default_world->height - 1))
    default_world->armies[0].a[0].y++;
}

void ctrl_ltrigger() {
  if (default_display->current_view>0)
    default_display->current_view--;
}

void ctrl_rtrigger() {
  if (default_display->current_view<(default_display->num_views-1))
    default_display->current_view++;
}

void crtl_analogue(char x, char y) {
  struct world *w = default_world;
  
  switch (default_display->current_view) {
  case VIEW_MENU:

    break;

  case VIEW_MAIN:
    w->vis_x += x / 12;
    if(!(w->vis_x >=0 && w->vis_x < (w->width * CELL_WIDTH) - (VIS_WIDTH * CELL_WIDTH)))
      w->vis_x -= x / 12;    
    w->vis_y += y / 12;
    if(!(w->vis_y >=0 && w->vis_y < (w->height * CELL_HEIGHT) - (VIS_HEIGHT * CELL_HEIGHT)))
      w->vis_y -= y / 12;
    break;

  case VIEW_MAP:

    break;
  }
}

