
#include <nds.h>

#include "_const.h"
#include "maindef.h"
#include "_console.h"
#include "_consoleWriteLog.h"

#include "../../ipc6.h"

#include "_GlobalTool_DirectPenRead.h"

static bool lastpress;
static u32 mlx,mly;

void DirectPenStart(void)
{
  lastpress=false;
  mlx=0; mly=0;
}

const TDirectPenInfo DirectPenRead(void)
{
  TDirectPenInfo res;
  res.CanRead=false;
  
  u32 ridx=IPC6->PenDatasReadIndex;
  if(ridx==IPC6->PenDatasWriteIndex){
    if(lastpress==false){
      res.CanRead=true;
      res.PenDown=false;
      res.x=0;
      res.y=0;
    }
    return(res);
  }
  
//  _consolePrintf("%2d,%2d,%2d\n",ridx,IPC6->PenDatasWriteIndex,(IPC6->PenDatasWriteIndex-ridx)&(PenDatasCount-1));
  
  res.CanRead=true;
  
  TPenData *ppd=&IPC6->pPenDatas[ridx];
  
  res.PenDown=ppd->Press;
  res.x=ppd->x;
  res.y=ppd->y;
  
  static u32 delay=0;
  if(res.PenDown==false){
    if((mlx!=0)&&(mly!=0)){
      res.PenDown=true;
      res.x=mlx;
      res.y=mly;
      mlx=0; mly=0;
      }else{
      lastpress=false;
    }
    delay=5;
    }else{
    if(delay!=0) delay--;
    static u32 firsty=0;
    if(lastpress==false) firsty=res.y;
    lastpress=true;
    if(((res.y-1)<=firsty)&&(firsty<=(res.y+1))){
      if(delay!=0){
        res.CanRead=false;
        res.PenDown=false;
      }
      }else{
      firsty=0;
    }
    mlx=res.x; mly=res.y;
  }
  
//  _consolePrintf("%d, %3d,%3d, %4d,%4d, %4d.\n",res.PenDown,ppd->x,ppd->y,ppd->z1,ppd->z2,ppd->z1*1000/ppd->z2);
  
  IPC6->PenDatasReadIndex=(ridx+1)&(PenDatasCount-1);
  
  return(res);
}

const TDirectPenInfo DirectPenRead_FromNowPosition(void)
{
  TDirectPenInfo res;
  res.CanRead=false;
  
  u32 ridx=IPC6->PenDatasWriteIndex;
  if(ridx==0){
    ridx=PenDatasCount-1;
    }else{
    ridx--;
  }
  
  res.CanRead=true;
  
  TPenData *ppd=&IPC6->pPenDatas[ridx];
  
  res.PenDown=ppd->Press;
  res.x=ppd->x;
  res.y=ppd->y;
  
  lastpress=res.PenDown;
  mlx=res.x; mly=res.y;
  
  IPC6->PenDatasReadIndex=(ridx+1)&(PenDatasCount-1);
  
  return(res);
}

bool DirectPenRead_isExclusive(void)
{
  u32 widx=IPC6->PenDatasWriteIndex;
  TPenData *ppd=&IPC6->pPenDatas[widx];
  if(ppd->Press==false){
    return(false);
    }else{
    return(true);
  }
}

bool GetPenDown(void)
{
  return(IPC6->AutoUpdate.PenDownFlag);
}

u32 GetKeyInputWithXY(void)
{
  u32 keys=(~REG_KEYINPUT)&0x3ff;
  keys|=IPC6->AutoUpdate.XYButtons;
  return(keys);
}

