#include "la_5.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <linux/joystick.h>

extern LA MAIN;

STRUCTURE(laJoystickEvent){
  unsigned int time;
  short value;
  unsigned char type;
  unsigned char number;
};

#define LA_JS_EVENT_BUTTON 0x01 // button pressed/released
#define LA_JS_EVENT_AXIS   0x02 // joystick moved
#define LA_JS_EVENT_INIT   0x80 // initial state of device

#define LA_JS_TYPE_X56_THROTTLE 1
#define LA_JS_TYPE_X56_STICK 2

int la_IdentifyControllerInternalType(char* name){
    if(strstr(name, "X-56") && strstr(name, "Throttle")){ return LA_JS_TYPE_X56_THROTTLE; }
    if(strstr(name, "X-56") && strstr(name, "Stick")){ return LA_JS_TYPE_X56_STICK; }
    return 0;
}

laController* la_NewController(char* name, char* path, int device, int NumAxes, int NumButtons){
    laController* c=memAcquire(sizeof(laController));
    logPrint("Found controller %s\n    at %s\n    with %d axes, %d buttons\n", name, path, NumAxes, NumButtons);
    strSafeSet(&c->Name, name); strSafeSet(&c->Path, path); c->fd=device;
    c->NumAxes = NumAxes; c->NumButtons=NumButtons;
    c->InternalType = la_IdentifyControllerInternalType(name);
    lstAppendItem(&MAIN.Controllers,c);
    return c;
}
void la_DestroyController(laController* c){
    free(c->ButtonValues); strSafeDestroy(&c->Name); strSafeDestroy(&c->Path);
    memFree(c);
}

void la_InitControllers(){
    char path[32]="/dev/input/js";
    char name[128]={0};
    int numpos=strlen(path);
    for(int i=0;i<16;i++){
        int fd;
        int version; uint8_t axes, buttons;
	    int btnmapok = 1;
        sprintf(&path[numpos],"%d",i);
        if ((fd=open(path, O_RDONLY|O_NONBLOCK))<0) { continue; }

        ioctl(fd, JSIOCGVERSION, &version);
        ioctl(fd, JSIOCGAXES, &axes);
        ioctl(fd, JSIOCGBUTTONS, &buttons);
        ioctl(fd, JSIOCGNAME(128), name);

        laController* c=la_NewController(name, path, fd, axes, buttons);
    }
}

void la_UpdateControllerStatus(){
    laJoystickEvent event; int HasEvent=0;
    for(laController* c=MAIN.Controllers.pFirst;c;c=c->Item.pNext){
        while(read(c->fd, &event, sizeof(laJoystickEvent))>0){
            if(event.type&LA_JS_EVENT_BUTTON){
                if(event.number>=c->NumButtons) continue;
                c->ButtonValues[event.number]=event.value; HasEvent=1;
                printf("b %d %d\n", event.number, event.value);
            }
            if(event.type&LA_JS_EVENT_AXIS){
                if(event.number>=c->NumAxes) continue;
                c->AxisValues[event.number]=event.value;
                printf("a %d %d\n", event.number, event.value); HasEvent=1;
            }
        }
    }
    if(HasEvent) laNotifyUsers("la.controllers");
}

void la_AddButtonProp(laPropContainer* pc, char* id, char* name, char* desc, int i, int array_len, char* array_prefix){
    laProp* p=laAddEnumProperty(pc, id, name, desc, LA_WIDGET_ENUM_HIGHLIGHT,
        array_prefix,0,0,0,offsetof(laController, ButtonValues[i]),0,0,array_len,0,0,0,0,0,0,LA_READ_ONLY);
    laAddEnumItemAs(p,"IDLE", "Idle", "Button is not pressed", 0, 0);
    laAddEnumItemAs(p,"ACTIVE", "Active", "Button is pressed", 1, 0);
    p->ElementBytes=1;
}
void la_AddAxisProp(laPropContainer* pc, char* id, char* name, char* desc, int i, int array_len, char* array_prefix){
    laProp* p=laAddIntProperty(pc,id,name,desc,array_len>1?LA_WIDGET_INT_METER_2D:LA_WIDGET_INT_METER,
        array_prefix,0,32768,-32767,1,0,0,offsetof(laController, AxisValues[i]),0,0,array_len,0,0,0,0,0,0,0,LA_READ_ONLY);
}
void la_AddGenericButtonProps(laPropContainer* pc){
    char id[16]=""; char name[16]=""; char Description[16]=""; laProp* p;
    for(int i=0;i<LA_JS_MAX_BUTTONS;i++){
        sprintf(id,"b%d",i); sprintf(name ,"%d",i); sprintf(Description ,"Button %d",i);
        la_AddButtonProp(pc,id,name,Description,i,0,0);
    }
}
void la_AddGenericAxisProps(laPropContainer* pc){
    char id[4]=""; char name[4]=""; char Description[16]=""; laProp* p;
    for(int i=0;i<LA_JS_MAX_AXES;i++){
        sprintf(id,"a%d",i); sprintf(name ,"%d",i); sprintf(Description ,"Axis %d",i);
        la_AddAxisProp(pc,id,name,Description,i,0,0);
    }
}

void laui_X56Throttle(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context);
void laui_X56Stick(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context);

laPropContainer* LA_PC_JS_GENERIC;
laPropContainer* LA_PC_JS_X56_THROTTLE;
laPropContainer* LA_PC_JS_X56_STICK;

laPropContainer* laget_ControllerType(laController* c){
    switch(c->InternalType){
    default: case 0: return LA_PC_JS_GENERIC;
    case LA_JS_TYPE_X56_THROTTLE: return LA_PC_JS_X56_THROTTLE;
    case LA_JS_TYPE_X56_STICK:    return LA_PC_JS_X56_STICK;
    }
}

void la_RegisterControllerProps(){
    laPropContainer* pc; laProp* p;

    pc=laAddPropertyContainer("la_controller", "Controller", "A joystick/gamepad controller", L'🕹', 0, sizeof(laController), 0,0,1);
    LA_PC_JS_GENERIC = pc;
    laAddStringProperty(pc,"name","Name","Name of the controller", LA_WIDGET_STRING_PLAIN,0,0,0,1,offsetof(laController,Name),0,0,0,0,LA_READ_ONLY|LA_AS_IDENTIFIER);
    laAddStringProperty(pc,"path","Path","Device path to the controller", LA_WIDGET_STRING_PLAIN,0,0,0,1,offsetof(laController,Path),0,0,0,0,LA_READ_ONLY);
    la_AddGenericButtonProps(pc);
    la_AddGenericAxisProps(pc);

    pc=laAddPropertyContainer("la_controller_x56_throttle", "X56 Throttle", "X56 Throttle", 0,laui_X56Throttle,sizeof(laController),0,0,1);
    LA_PC_JS_X56_THROTTLE = pc;
    laAddStringProperty(pc,"name","Name","Name of the controller", LA_WIDGET_STRING_PLAIN,0,0,0,1,offsetof(laController,Name),0,0,0,0,LA_READ_ONLY|LA_AS_IDENTIFIER);
    laAddSubGroup(pc,"base","Base","Generic controller status", "la_controller",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    la_AddAxisProp(pc,"thr1","THR1","Throttle 1",0,0,0);
    la_AddAxisProp(pc,"thr2","THR2","Throttle 1",1,0,0);
    la_AddAxisProp(pc,"wf","WF","Wheel F (big wheel)",2,0,0);
    la_AddAxisProp(pc,"ball","Ball","Thumb ball",3,2,"Left/Right,Up/Down");
    la_AddAxisProp(pc,"wg","WG","Wheel G (smaller wheel)",5,0,0);
    la_AddAxisProp(pc,"r4","RTY4","Rotary 4",6,0,0);
    la_AddAxisProp(pc,"r3","RTY3","Rotary 3",7,0,0);
    la_AddButtonProp(pc,"be","E","Button E (thumb flat switch)", 0,0,0);
    la_AddButtonProp(pc,"bf","F","Button F (big push down switch)", 1,0,0);
    la_AddButtonProp(pc,"bg","G","Button G (smaller up-side-down switch)", 2,0,0);
    la_AddButtonProp(pc,"bi","I","Button I (left reverser)", 3,0,0);
    la_AddButtonProp(pc,"bh","H","Button H (right reverser)", 4,0,0);
    la_AddButtonProp(pc,"sw1","SW1","Switch 1", 5,0,0);
    la_AddButtonProp(pc,"sw2","SW2","Switch 2", 6,0,0);
    la_AddButtonProp(pc,"sw3","SW3","Switch 3", 7,0,0);
    la_AddButtonProp(pc,"sw4","SW4","Switch 4", 8,0,0);
    la_AddButtonProp(pc,"sw5","SW5","Switch 5", 9,0,0);
    la_AddButtonProp(pc,"sw6","SW6","Switch 6", 10,0,0);
    la_AddButtonProp(pc,"t1_up","T1+","Toggle 1+", 11,0,0);
    la_AddButtonProp(pc,"t1_dn","T1-","Toggle 1-", 12,0,0);
    la_AddButtonProp(pc,"t2_up","T2+","Toggle 2+", 13,0,0);
    la_AddButtonProp(pc,"t2_dn","T2-","Toggle 2-", 14,0,0);
    la_AddButtonProp(pc,"t3_up","T3+","Toggle 3+", 15,0,0);
    la_AddButtonProp(pc,"t3_dn","T3-","Toggle 3-", 16,0,0);
    la_AddButtonProp(pc,"t4_up","T4+","Toggle 4+", 17,0,0);
    la_AddButtonProp(pc,"t4_dn","T4-","Toggle 4-", 18,0,0);
    la_AddButtonProp(pc,"h3","H3","Hat 3 (Upper round hat)", 19,4,"N,E,S,W");
    la_AddButtonProp(pc,"h4","H4","Hat 4 (lower jagged hat)", 23,4,"N,E,S,W");
    la_AddButtonProp(pc,"pinky_up","P+","Pinky up", 27,0,0);
    la_AddButtonProp(pc,"pinky_dn","P-","Pinky down", 28,0,0);
    la_AddButtonProp(pc,"dial_fwd","D+","Dial forward", 29,0,0);
    la_AddButtonProp(pc,"dial_back","D-","Dial backward", 30,0,0);
    la_AddButtonProp(pc,"bball","BP","Ball push", 31,0,0);
    la_AddButtonProp(pc,"slider","SLD","Slider", 32,0,0);
    la_AddButtonProp(pc,"mode","Mode","Mode switch", 33,3,"M1,M2,S1");


    pc=laAddPropertyContainer("la_controller_x56_stick", "X56 Stick", "X56 Stick", 0,laui_X56Stick,sizeof(laController),0,0,1);
    LA_PC_JS_X56_STICK = pc;
    laAddStringProperty(pc,"name","Name","Name of the controller", LA_WIDGET_STRING_PLAIN,0,0,0,1,offsetof(laController,Name),0,0,0,0,LA_READ_ONLY|LA_AS_IDENTIFIER);
    laAddSubGroup(pc,"base","Base","Generic controller status", "la_controller",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    la_AddAxisProp(pc,"stick","Stick","Main stick",0,2,"Left/Right,Up/Down");
    la_AddAxisProp(pc,"ball","Ball","Ball stick",2,2,"Left/Right,Up/Down");
    la_AddAxisProp(pc,"rudder","Rudder","Ruder twist",4,0,0);
    la_AddAxisProp(pc,"pov","POV","POV hat",5,2,"Left/Right,Up/Down");
    la_AddButtonProp(pc,"trigger","Trigger","Trigger", 0,0,0);
    la_AddButtonProp(pc,"ba","A","Button A", 1,0,0);
    la_AddButtonProp(pc,"bb","B","Button B (Side of stick)", 2,0,0);
    la_AddButtonProp(pc,"bball","BP","Ball push", 3,0,0);  la_AddButtonProp(pc,"bc","BC","Button C (ball push)", 3,0,0);
    la_AddButtonProp(pc,"pinky","PK","Pinky small button", 4,0,0); la_AddButtonProp(pc,"bd","BD","Button D pinky small button", 4,0,0);
    la_AddButtonProp(pc,"pinkyl","PKL","Pinky lever", 5,0,0);
    la_AddButtonProp(pc,"h1","H1","Hat 1 (Upper round hat)", 6,4,"N,E,S,W");
    la_AddButtonProp(pc,"h2","H2","Hat 2 (lower jagged hat)", 10,4,"N,E,S,W");
    //button 14-16 not sure where it is....
}


void laui_X56Throttle(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil),*cl, *cr, *crl,*crr, *rc, *vc, *rcl,*rcr;
    laSplitColumn(uil,c,0.17); cl=laLeftColumn(c,0); cr=laRightColumn(c,0);
    laSplitColumn(uil,cr,0.4); crl=laLeftColumn(cr,0); crr=laRightColumn(cr,0);
    laSplitColumn(uil,crr,0.6); rc=laLeftColumn(crr,10); vc=laRightColumn(crr,0);
    laSplitColumn(uil,rc,0.4); rcl=laLeftColumn(rc,2); rcr=laRightColumn(rc,0);
    laUiItem* b,*ui,*g; laUiList*gu;

    laShowItem(uil,c,This,"base.name")->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,c,This,"base.path")->Flags|=LA_TEXT_ALIGN_CENTER;

    laShowItem(uil,cl,This,"pinky_up");
    laShowItem(uil,cl,This,"pinky_dn");
    laShowSeparator(uil,cl);
    laShowItem(uil,cl,This,"dial_fwd");
    laShowItem(uil,cl,This,"dial_back");

    b=laBeginRow(uil,crl,0,0);
    ui=laShowItem(uil,crl,This,"bi");ui->Expand=1;
    ui=laShowItem(uil,crl,This,"bh");ui->Expand=1;
    laEndRow(uil,b);
    b=laBeginRow(uil,crl,0,0);
    ui=laShowItem(uil,crl,This,"thr1");ui->Expand=1;ui->Extra->HeightCoeff=10;ui->Flags|=LA_UI_FLAGS_TRANSPOSE;
    ui=laShowItem(uil,crl,This,"thr2");ui->Expand=1;ui->Extra->HeightCoeff=10;ui->Flags|=LA_UI_FLAGS_TRANSPOSE;
    laEndRow(uil,b);

    laShowItem(uil,rcl,This,"bf");
    laShowItem(uil,rcr,This,"wf");
    laShowItem(uil,rcl,This,"bg");
    laShowItem(uil,rcr,This,"wg");
    laShowSeparator(uil,cl);
    laShowItem(uil,rcl,This,"slider");
    laShowSeparator(uil,rcl);
    laShowItem(uil,rcl,This,"be");
    laShowItem(uil,rcl,This,"bball");
    laShowItem(uil,rcr,This,"ball");

    laShowItem(uil,rc,This,"h3")->Flags|=LA_UI_FLAGS_TRANSPOSE;
    laShowItem(uil,rc,This,"h4")->Flags|=LA_UI_FLAGS_TRANSPOSE;
    
    laShowItem(uil,vc,This,"t4_up");
    laShowItem(uil,vc,This,"t4_dn"); laShowSeparator(uil,vc);
    laShowItem(uil,vc,This,"t3_up");
    laShowItem(uil,vc,This,"t3_dn"); laShowSeparator(uil,vc);
    laShowItem(uil,vc,This,"t2_up");
    laShowItem(uil,vc,This,"t2_dn"); laShowSeparator(uil,vc);
    laShowItem(uil,vc,This,"t1_up");
    laShowItem(uil,vc,This,"t1_dn"); laShowSeparator(uil,vc);

    laShowItem(uil,vc,This,"r3");
    laShowItem(uil,vc,This,"r4");

    laShowSeparator(uil,c);

    laShowLabel(uil,cl,"Mode",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cl,This,"mode");

    laShowLabel(uil,cr,"Switches",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;

    b=laBeginRow(uil,cr,0,0);
    laShowItem(uil,cr,This,"sw1")->Expand=1;
    laShowItem(uil,cr,This,"sw3")->Expand=1;
    laShowItem(uil,cr,This,"sw5")->Expand=1;
    laEndRow(uil,b);
    b=laBeginRow(uil,cr,0,0);
    laShowItem(uil,cr,This,"sw2")->Expand=1;
    laShowItem(uil,cr,This,"sw4")->Expand=1;
    laShowItem(uil,cr,This,"sw6")->Expand=1;
    laEndRow(uil,b);
    

}
void laui_X56Stick(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil),*cl, *cc, *cr;
    laSplitColumn(uil,c,0.2); cl=laLeftColumn(c,10); cr=laRightColumn(c,0);
    laSplitColumn(uil,cr,0.8); cc=laLeftColumn(cr,0); cr=laRightColumn(cr,10);
    
    laShowItem(uil,c,This,"base.name")->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,c,This,"base.path")->Flags|=LA_TEXT_ALIGN_CENTER;

    laShowItem(uil,cl,This,"ba");
    laShowItem(uil,cl,This,"pov");

    laShowSeparator(uil,cl);

    laShowLabel(uil,cl,"Thumb",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cl,This,"bc");
    laShowItem(uil,cl,This,"ball");

    laShowSeparator(uil,cl);

    laShowLabel(uil,cl,"Pinky",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cl,This,"pinkyl");
    laShowItem(uil,cl,This,"pinky");


    laShowItem(uil,cr,This,"bb");
    laShowSeparator(uil,cr);

    laShowItem(uil,cc,This,"trigger");
    laShowItem(uil,cc,This,"stick");
    laShowItem(uil,cc,This,"rudder");

    laShowLabel(uil,cr,"H1",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cr,This,"h1");

    laShowSeparator(uil,cr);

    laShowLabel(uil,cr,"H2",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cr,This,"h2");
}