/******************************************************************************/
/* Mednafen NEC PC-FX Emulation Module                                        */
/******************************************************************************/
/* mouse.cpp:
**  Copyright (C) 2007-2016 Mednafen Team
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "../pcfx.h"
#include "../input.h"
#include "mouse.h"

namespace MDFN_IEN_PCFX
{

class PCFX_Input_Mouse : public PCFX_Input_Device
{
 public:
 PCFX_Input_Mouse(int which)
 {
  x = 0;
  y = 0;
  button = 0;
 }

 virtual ~PCFX_Input_Mouse() override
 {

 }

 virtual uint32 ReadTransferTime(void) override
 {
  return(1536);
 }

 virtual uint32 WriteTransferTime(void) override
 {
  return(1536);
 }

 virtual uint32 Read(void) override
 {
  uint32 moo = FX_SIG_MOUSE << 28;
  int32 rel_x = (int32)(x);
  int32 rel_y = (int32)(y);

  if(rel_x < -127) rel_x = -127;
  if(rel_x > 127) rel_x = 127;
  if(rel_y < -127) rel_y = -127;
  if(rel_y > 127) rel_y = 127;

  moo |= ((rel_x & 0xFF) << 8) | ((rel_y & 0xFF) << 0);

  x += (int32)(0 - rel_x);
  y += (int32)(0 - rel_y);

  moo |= button << 16;

  return(moo);
 }

 virtual void Write(uint32 data) override
 {

 }


 virtual void Power(void) override
 {
  button = 0;
  x = 0;
  y = 0;
 }

 virtual void Frame(const void *data) override
 {
  x += (int16)MDFN_de16lsb((uint8 *)data + 0);
  y += (int16)MDFN_de16lsb((uint8 *)data + 2);
  button = *(uint8 *)((uint8 *)data + 4);
 }

 virtual void StateAction(StateMem *sm, const unsigned load, const bool data_only, const char *section_name) override
 {
  SFORMAT StateRegs[] =
  {
   SFVAR(x),
   SFVAR(y),
   SFVAR(button),
   SFEND
  };

  if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, section_name, true) && load)
   Power();
 }

 private:


 int32 x, y;
 uint8 button;
};

PCFX_Input_Device *PCFXINPUT_MakeMouse(int which)
{
 return(new PCFX_Input_Mouse(which));
}

const IDIISG PCFX_MouseIDII =
{
 IDIIS_AxisRel("motion", "Motion",/**/ "left", "Left",/**/ "right", "Right", 0),
 IDIIS_AxisRel("motion", "Motion",/**/ "up", "Up",/**/ "down", "Down", 1),
 IDIIS_Button("left", "Left Button", 2),
 IDIIS_Button("right", "Right Button", 3),
};

}
