#include <stdlib.h>
#include <string.h>

#include "main.h"
#include "input.h"
#include "input-config.h"
#include "video.h"
#include "joystick.h"

int DTestButton(ButtConfig *bc, char *KeyState, const uint32 *MouseData)
{
 unsigned int x;

 for(x=0;x<bc->NumC;x++)
 {
  if(bc->ButtType[x]==BUTTC_KEYBOARD)
  {
   if(KeyState[bc->ButtonNum[x]])
    return(1);
  }
  else if(bc->ButtType[x]==BUTTC_JOYSTICK)
  {
   if(DTestButtonJoy(bc))
    return(1);
  }
  else if(bc->ButtType[x] == BUTTC_MOUSE)
  {
   if(bc->ButtonNum[x] & 0x8000)
   {
    if(bc->ButtonNum[x]&1) // Y
    {
     if(bc->ButtonNum[x] & 0x4000)
     {
      if(MouseData[1] < 128)
       return(1);
     }
     else
     {
      if(MouseData[1] >= 128)
       return(1);
     }
    }
    else			// X
    {
     if(bc->ButtonNum[x] & 0x4000)
     {
      if(MouseData[0] < 128)
       return(1);
     }
     else
     {
      if(MouseData[0] >= 128)
       return(1);
     }
    }
    
   }
   else 
   {
    if(MouseData[2] & SDL_BUTTON(bc->ButtonNum[x]))
     return(1);
   }
  }
 }
 return(0);
}

#define ICSS_ALT	1
#define ICSS_SHIFT	2
#define ICSS_CTRL	4

/* Used for command keys */
int DTestButtonCombo(ButtConfig *bc, char *KeyState)
{
 unsigned int x;
 unsigned int ss = 0;

 if(KeyState[MKK(LALT)] || KeyState[MKK(RALT)]) ss |= ICSS_ALT;
 if(KeyState[MKK(LSHIFT)] || KeyState[MKK(RSHIFT)]) ss |= ICSS_SHIFT;
 if(KeyState[MKK(LCTRL)] || KeyState[MKK(RCTRL)]) ss |= ICSS_CTRL;

 for(x=0;x<bc->NumC;x++)
 {
  if(bc->ButtType[x]==BUTTC_KEYBOARD)
  {
   uint32 b = bc->ButtonNum[x];
   
   if(KeyState[b & 0xFFFF] && ((b >> 24) == ss))
    return(1);
  }
  else if(bc->ButtType[x]==BUTTC_JOYSTICK)
  {
   if(DTestButtonJoy(bc))
    return(1);
  }
 }
 return(0);
}



static int bcpv,bcpj;

int ButtonConfigBegin(void)
{
 SDL_Surface *screen;
 SDL_QuitSubSystem(SDL_INIT_VIDEO);
 bcpv=KillVideo(1);
 bcpj=KillJoysticks();

 if(!(SDL_WasInit(SDL_INIT_VIDEO)&SDL_INIT_VIDEO))
  if(SDL_InitSubSystem(SDL_INIT_VIDEO)==-1)
  {
   MDFND_Message(SDL_GetError());
   return(0);
  }

 screen = SDL_SetVideoMode(300, 1, 8, 0);
 SDL_WM_SetCaption("Button Config",0);
 InitJoysticks();

 return(1);
}

void ButtonConfigEnd(void)
{
 extern MDFNGI *CurGame;
 KillJoysticks();
 SDL_QuitSubSystem(SDL_INIT_VIDEO);
 if(bcpv) InitVideo(CurGame);
 if(bcpj) InitJoysticks();
}

static ButtConfig efbc;
static volatile int efbcdone;
static volatile int efck;
static volatile int efwb;
static int32 LastAx[64][64];
static int LastMouseX;
static int LastMouseY;

static int EventFilter(const SDL_Event *event)
{
 if(efbcdone)
  return(1);
  switch(event->type)
  {
   case SDL_KEYDOWN:    if(!efck || (event->key.keysym.sym != MKK(LALT) && event->key.keysym.sym != MKK(RALT) &&
                         event->key.keysym.sym != MKK(LSHIFT) && event->key.keysym.sym != MKK(RSHIFT)))
                        {
                                efbc.ButtType[efwb]=BUTTC_KEYBOARD;
                                efbc.DeviceNum[efwb]=0;
                                efbc.ButtonNum[efwb]=event->key.keysym.sym;
                                if(efck)
                                        efbc.ButtonNum[efwb] |= ((event->key.keysym.mod & KMOD_ALT) ? (ICSS_ALT<<24):0) | ((event->key.keysym.mod & KMOD_SHIFT) ? (ICSS_SHIFT<<24):0);
				efbcdone = 1;
                                return(1);
                        }
                        break;
   case SDL_MOUSEBUTTONDOWN:efbc.ButtType[efwb] = BUTTC_MOUSE;
				efbc.DeviceNum[efwb] = 0;
				efbc.ButtonNum[efwb] = event->button.button;
				efbcdone = 1;
				return(1);
/*
   case SDL_MOUSEMOTION:
			 printf("%d %d\n", event->motion.x, LastMouseX);
			 if(abs((int)event->motion.x - LastMouseX) > 100)
			 {
			  efbc.ButtType[efwb] = BUTTC_MOUSE;
			  efbc.DeviceNum[efwb] = 0;
			  efbc.ButtonNum[efwb] = 0x8000 | ((((int)event->motion.x - LastMouseX) < 0)?0x4000:0);
			  efbcdone = 1;
			  return(1);
			 }
			 else if(abs((int)event->motion.y - LastMouseY) > 100)
			 {
                          efbc.ButtType[efwb] = BUTTC_MOUSE;
                          efbc.DeviceNum[efwb] = 0;
                          efbc.ButtonNum[efwb] = 0x8001 | ((((int)event->motion.y - LastMouseY) < 0)?0x4000:0);
			  efbcdone = 1;
			  return(1);
			 }
			 break; 
*/
  case SDL_JOYBUTTONDOWN:efbc.ButtType[efwb]=BUTTC_JOYSTICK;
                          efbc.DeviceNum[efwb]=event->jbutton.which;
                          efbc.ButtonNum[efwb]=event->jbutton.button;
			  efbc.DeviceID[efwb] = GetJoystickUniqueID(event->jbutton.which);
			  efbcdone = 1;
                          return(1);
   case SDL_JOYHATMOTION:                         
			//printf("Raw: %d\n", SDL_JoystickGetHat(Joysticks[event->jhat.which], 0xFF)); //(bc->ButtonNum[x]>>8)&0x1F) & (bc->ButtonNum[x]&0xFF)));
			if(event->jhat.value != SDL_HAT_CENTERED && event->jhat.value != SDL_HAT_RIGHTUP && event->jhat.value != SDL_HAT_RIGHTDOWN &&
				event->jhat.value != SDL_HAT_LEFTUP && event->jhat.value != SDL_HAT_LEFTDOWN)
                         {
				//printf("Real: %d\n",event->jhat.value);
				//break;
                          efbc.ButtType[efwb]=BUTTC_JOYSTICK;
                          efbc.DeviceNum[efwb]=event->jhat.which;
                          efbc.ButtonNum[efwb]=0x2000|((event->jhat.hat&0x1F)<<8)|event->jhat.value;
			  efbc.DeviceID[efwb] = GetJoystickUniqueID(event->jhat.which);
			  efbcdone = 1;
                          return(1);
                         }
                         break;
   case SDL_JOYAXISMOTION:
	//printf("%d %d %d\n", event->jaxis.which, event->jaxis.axis, event->jaxis.value);
        if(LastAx[event->jaxis.which][event->jaxis.axis]==0x100000)
        {
         if(abs(event->jaxis.value)<1000)
          LastAx[event->jaxis.which][event->jaxis.axis]=event->jaxis.value;
        }
        else
        {
         if(abs(LastAx[event->jaxis.which][event->jaxis.axis]-event->jaxis.value)>=24000)
         {
          efbc.ButtType[efwb]=BUTTC_JOYSTICK;
          efbc.DeviceNum[efwb]=event->jaxis.which;
          efbc.ButtonNum[efwb]=0x8000|(event->jaxis.axis)|((event->jaxis.value<0)?0x4000:0);
	  efbc.DeviceID[efwb] = GetJoystickUniqueID(event->jaxis.which);
	  efbcdone = 1;

	  //puts("axis");
	  return(1);
         }
        }
        break;
  }

 return(1);
}


int DWaitButton(const char *text, ButtConfig *bc, int wb, int commandkey)
{
 int x,y;

 SDL_WM_SetCaption((char *)text,0);
 puts((char *)text);

 for(x=0;x<64;x++)
  for(y=0;y<64;y++)
   LastAx[x][y]=0x100000;

 memcpy(&efbc, bc, sizeof(ButtConfig));
 efck = commandkey;
 efwb = wb;
 efbcdone = 0;

 SDL_SetEventFilter(EventFilter);
 while(!efbcdone)
 {
  SDL_PumpEvents();
  SDL_Delay(1);
 }
 SDL_SetEventFilter(NULL);

 memcpy(bc, &efbc, sizeof(ButtConfig));
 return(1);
}

int DTryButtonBegin(ButtConfig *bc, int wb, int commandkey)
{

 //for(int x=0;x<64;x++)
 // for(int y=0;y<64;y++)
 //  LastAx[x][y]=0x100000;

 memcpy(&efbc, bc, sizeof(ButtConfig));
 efck = commandkey;
 efwb = wb;
 efbcdone = 0;

 //SDL_MDFN_ShowCursor(1);
 SDL_GetMouseState(&LastMouseX, &LastMouseY);

 MainSetEventHook(EventFilter);
 //SDL_SetEventFilter(EventFilter);
 return(1);
}

int DTryButton(void)
{
 return(efbcdone);
}

int DTryButtonEnd(ButtConfig *bc)
{
 MainSetEventHook(EventFilter);
 //SDL_MDFN_ShowCursor(0);
 //SDL_SetEventFilter(NULL);
 memcpy(bc, &efbc, sizeof(ButtConfig));

 return(1);
}
