/**
 * Scout - The Amiga System Monitor
 *
 *------------------------------------------------------------------
 *
 * 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
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * You must not use this source code to gain profit of any kind!
 *
 *------------------------------------------------------------------
 *
 * @author Andreas Gelhausen
 * @author Richard Körber <rkoerber@gmx.de>
 */

#include "system_headers.h"

struct InputCallbackUserData {
    APTR ud_List;
    ULONG ud_Count;
};

static __asm __saveds LONG inputlist_con2func(register __a2 Object *obj, register __a1 struct NList_ConstructMessage *msg, register __a0 struct Hook *hook)
{
    return AllocListEntry(msg->pool, msg->entry, sizeof(struct InputHandlerEntry));
}

MakeHook(inputlist_con2hook, inputlist_con2func);

static __asm __saveds LONG inputlist_des2func(register __a2 Object *obj, register __a1 struct NList_DestructMessage *msg, register __a0 struct Hook *hook)
{
    FreeListEntry(msg->pool, &msg->entry);

    return 0;
}

MakeHook(inputlist_des2hook, inputlist_des2func);

static __asm __saveds LONG inputlist_dsp2func(register __a2 Object *obj, register __a1 struct NList_DisplayMessage *msg, register __a0 struct Hook *hook)
{
    struct InputHandlerEntry *ihe = (struct InputHandlerEntry *)msg->entry;

    if (ihe) {
        msg->strings[0] = ihe->ihe_Address;
        msg->strings[1] = ihe->ihe_Name;
        msg->strings[2] = ihe->ihe_Type;
        msg->strings[3] = ihe->ihe_Pri;
        msg->strings[4] = ihe->ihe_Data;
        msg->strings[5] = ihe->ihe_Code;
    } else {
        msg->strings[0] = "Address";
        msg->strings[1] = "ln_Name";
        msg->strings[2] = "ln_Type";
        msg->strings[3] = "ln_Pri";
        msg->strings[4] = "is_Data";
        msg->strings[5] = "is_Code";
        msg->preparses[0] = MUIX_B;
        msg->preparses[1] = MUIX_B;
        msg->preparses[2] = MUIX_B;
        msg->preparses[3] = MUIX_B;
        msg->preparses[4] = MUIX_B;
        msg->preparses[5] = MUIX_B;
    }

    return 0;
}

MakeHook(inputlist_dsp2hook, inputlist_dsp2func);

static LONG inputlist_cmp2colfunc( struct InputHandlerEntry *ihe1,
                                   struct InputHandlerEntry *ihe2,
                                   ULONG column )
{
    LONG pri1, pri2;

    switch (column) {
        case 0: return stricmp(ihe1->ihe_Address, ihe2->ihe_Address);
        case 1: return stricmp(ihe1->ihe_Name, ihe2->ihe_Name);
        case 2: return stricmp(ihe1->ihe_Type, ihe2->ihe_Type);
        case 3: IsDec(ihe1->ihe_Pri, &pri1); IsDec(ihe2->ihe_Pri, &pri2); return pri2 - pri1;
        case 4: return stricmp(ihe1->ihe_Data, ihe2->ihe_Data);
        case 5: return stricmp(ihe1->ihe_Code, ihe2->ihe_Code);
    }
}

static __asm __saveds LONG inputlist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct InputHandlerEntry *ihe1, *ihe2;
    ULONG col1, col2;

    ihe1 = (struct InputHandlerEntry *)msg->entry1;
    ihe2 = (struct InputHandlerEntry *)msg->entry2;
    col1 = msg->sort_type & MUIV_NList_TitleMark_ColMask;
    col2 = msg->sort_type2 & MUIV_NList_TitleMark2_ColMask;

    if (msg->sort_type == MUIV_NList_SortType_None) return 0;

    if (msg->sort_type & MUIV_NList_TitleMark_TypeMask) {
        cmp = inputlist_cmp2colfunc(ihe2, ihe1, col1);
    } else {
        cmp = inputlist_cmp2colfunc(ihe1, ihe2, col1);
    }

    if (cmp != 0 || col1 == col2) return cmp;

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = inputlist_cmp2colfunc(ihe2, ihe1, col2);
    } else {
        cmp = inputlist_cmp2colfunc(ihe1, ihe2, col2);
    }

    return cmp;
}

MakeHook(inputlist_cmp2hook, inputlist_cmp2func);

static struct InputEvent * __asm __saveds dummyIRQFunc( register __a0 struct InputEvent *ie,
                                                        register __a1 APTR handlerData )
{
    return ie;
}

static void ReceiveList( void (* callback)( struct InputHandlerEntry *ihe, void *userData ),
                         void *userData )
{
    struct InputHandlerEntry *ihe;

    if (ihe = tbAllocVecPooled(globalPool, sizeof(struct InputHandlerEntry))) {
        if (SendDaemon("GetInputList")) {
            while (ReceiveDecodedEntry((UBYTE *)ihe, sizeof(struct InputHandlerEntry))) {
                callback(ihe, userData);
            }
        }

        tbFreeVecPooled(globalPool, ihe);
    }
}

static void IterateList( void (* callback)( struct InputHandlerEntry *ihe, void *userData ),
                         void *userData )
{
    struct MinList tmplist;
    struct InputHandlerEntry *ihe, *_ihe;
    struct MsgPort *mp;

    NewList((struct List *)&tmplist);

    if (mp = CreateMsgPort()) {
        struct IOStdReq *io;

        if (io = (struct IOStdReq *)CreateIORequest(mp, sizeof(struct IOStdReq))) {
            if (OpenDevice("input.device", 0, io, 0) == 0) {
                struct Interrupt *myirq;

                if (myirq = tbAllocVecPooled(globalPool, sizeof(struct Interrupt))) {
                    struct List *irqlist;
                    struct Interrupt *irq;

                    myirq->is_Node.ln_Type = NT_INTERRUPT;
                    myirq->is_Node.ln_Pri = -32;
                    myirq->is_Node.ln_Name = "Scout";
                    myirq->is_Code = (void (*)())dummyIRQFunc;
                    myirq->is_Data = NULL;

                    io->io_Command = IND_ADDHANDLER;
                    io->io_Data = myirq;

                    DoIO(io);

                    Forbid();

                    irqlist = FindListOfNode(myirq);

                    ITERATE_LIST(irqlist, struct Interrupt *, irq) {
                        if (irq != myirq) {
                            if (ihe = AllocVec(sizeof(struct InputHandlerEntry), MEMF_PUBLIC)) {
                                ihe->ihe_Addr = irq;

                                _snprintf(ihe->ihe_Address, sizeof(ihe->ihe_Address), "$%08lx", irq);
                                stccpy(ihe->ihe_Name, nonetest(irq->is_Node.ln_Name), sizeof(ihe->ihe_Name));
                                stccpy(ihe->ihe_Type, GetNodeType(irq->is_Node.ln_Type), sizeof(ihe->ihe_Type));
                                _snprintf(ihe->ihe_Pri, sizeof(ihe->ihe_Pri), "%4ld", irq->is_Node.ln_Pri);
                                _snprintf(ihe->ihe_Data, sizeof(ihe->ihe_Data), "$%08lx", irq->is_Data);
                                if (points2ram((APTR)irq->is_Code)) {
                                   _snprintf(ihe->ihe_Code, sizeof(ihe->ihe_Code), MUIX_PH "$%08lx" MUIX_PT, irq->is_Code);
                                } else {
                                   _snprintf(ihe->ihe_Code, sizeof(ihe->ihe_Code), "$%08lx", irq->is_Code);
                                }

                                AddTail((struct List *)&tmplist, (struct Node *)ihe);
                            }
                        }
                    }

                    Permit();

                    io->io_Command = IND_REMHANDLER;
                    io->io_Data = myirq;
                    DoIO(io);

                    tbFreeVecPooled(globalPool, myirq);
                }

                CloseDevice(io);
            }

            DeleteIORequest(io);
        }

        DeleteMsgPort(mp);
    }

    ITERATE_CHANGING_LIST(&tmplist, struct InputHandlerEntry *, ihe, _ihe) {
        callback(ihe, userData);
        FreeVec(ihe);
    }
}

static void UpdateCallback( struct InputHandlerEntry *ihe,
                            void *userData )
{
    struct InputCallbackUserData *ud = (struct InputCallbackUserData *)userData;

    InsertBottomEntry(ud->ud_List, ihe);
    ud->ud_Count++;
}

static void PrintCallback( struct InputHandlerEntry *ihe,
                           void *userData )
{
    if (points2ram((APTR)ihe->ihe_Addr->is_Code)) {
        PrintFOneLine((BPTR)userData, " %s %-9s %4s %s  %-9.9s  %s\n", ihe->ihe_Address, ihe->ihe_Type, ihe->ihe_Pri, ihe->ihe_Data, ihe->ihe_Code + 2, ihe->ihe_Name);
    } else {
        PrintFOneLine((BPTR)userData, " %s %-9s %4s %s  %-9.9s  %s\n", ihe->ihe_Address, ihe->ihe_Type, ihe->ihe_Pri, ihe->ihe_Data, ihe->ihe_Code, ihe->ihe_Name);
    }
}

static void SendCallback( struct InputHandlerEntry *ihe,
                          void *userData )
{
    SendEncodedEntry((UBYTE *)ihe, sizeof(struct InputHandlerEntry));
}

static ULONG __saveds mNew( struct IClass *cl,
                            Object *obj,
                            struct opSet *msg )
{
    APTR inputlist, inputtext, inputcount, updateButton, printButton, removeButton, priorityButton, exitButton;

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, InputHandlersText,
        MUIA_Window_ID, MakeID('I','N','P','U'),
        WindowContents, VGroup,

            Child, inputlist = MyNListviewObject(MakeID('I','N','L','V'), "BAR,BAR,BAR P=" MUIX_C ",BAR P=" MUIX_R ",BAR,BAR", &inputlist_con2hook, &inputlist_des2hook, &inputlist_dsp2hook, &inputlist_cmp2hook, TRUE),
            Child, MyBelowListview(&inputtext, &inputcount),

            Child, MyVSpace(4),

            Child, HGroup, MUIA_Group_SameSize, TRUE,
                Child, updateButton   = MakeButton(txtUpdate),
                Child, printButton    = MakeButton(txtPrint),
                Child, removeButton   = MakeButton(txtRemove),
                Child, priorityButton = MakeButton(txtPriority),
                Child, exitButton     = MakeButton(txtExit),
            End,
        End,
        TAG_MORE, msg->ops_AttrList))
    {
        struct InputHandlersWinData *ihwd = INST_DATA(cl, obj);
        APTR parent;

        ihwd->ihwd_InputHandlerList = inputlist;
        ihwd->ihwd_InputHandlerText = inputtext;
        ihwd->ihwd_InputHandlerCount = inputcount;
        ihwd->ihwd_RemoveButton = removeButton;
        ihwd->ihwd_PriorityButton = priorityButton;

        parent = (APTR)GetTagData(MUIA_Window_ParentWindow, (ULONG)NULL, msg->ops_AttrList);

        set(obj, MUIA_Window_Title, MyGetWindowTitle("INPUTHANDLERS", ihwd->ihwd_Title, sizeof(ihwd->ihwd_Title)));
        set(obj, MUIA_Window_ActiveObject, inputlist);
        set(removeButton, MUIA_Disabled, TRUE);
        set(priorityButton, MUIA_Disabled, TRUE);

        DoMethod(parent,         MUIM_Window_AddChildWindow, obj);
        DoMethod(obj,            MUIM_Notify, MUIA_Window_CloseRequest, TRUE,           MUIV_Notify_Application, 5, MUIM_Application_PushMethod, parent, 2, MUIM_Window_RemChildWindow, obj);
        DoMethod(inputlist,      MUIM_Notify, MUIA_NList_Active,        MUIV_EveryTime, obj,                     1, MUIM_InputHandlersWin_ListChange);
        DoMethod(updateButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_InputHandlersWin_Update);
        DoMethod(printButton,    MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_InputHandlersWin_Print);
        DoMethod(removeButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_InputHandlersWin_Remove);
        DoMethod(priorityButton, MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_InputHandlersWin_Priority);
        DoMethod(exitButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     3, MUIM_Set, MUIA_Window_CloseRequest, TRUE);
    }

    return (ULONG)obj;
}

static ULONG __saveds mDispose( struct IClass *cl,
                                Object *obj,
                                struct opSet *msg )
{
    struct InputHandlersWinData *ihwd = INST_DATA(cl, obj);

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(ihwd->ihwd_InputHandlerList, MUIM_NList_Clear);

    return (DoSuperMethodA(cl, obj, msg));
}

static ULONG __saveds mUpdate( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct InputHandlersWinData *ihwd = INST_DATA(cl, obj);
    struct InputCallbackUserData ud;

    ApplicationSleep(TRUE);
    set(ihwd->ihwd_InputHandlerList, MUIA_NList_Quiet, TRUE);
    DoMethod(ihwd->ihwd_InputHandlerList, MUIM_NList_Clear);

    ud.ud_List = ihwd->ihwd_InputHandlerList;
    ud.ud_Count = 0;

    if (clientstate) {
        ReceiveList(UpdateCallback, &ud);
    } else {
        IterateList(UpdateCallback, &ud);
    }

    SetCountText(ihwd->ihwd_InputHandlerCount, ud.ud_Count);
    MySetContents(ihwd->ihwd_InputHandlerText, "");

    set(ihwd->ihwd_InputHandlerList, MUIA_NList_Quiet, FALSE);
    set(ihwd->ihwd_RemoveButton, MUIA_Disabled, TRUE);
    set(ihwd->ihwd_PriorityButton, MUIA_Disabled, TRUE);
    ApplicationSleep(FALSE);

    return 0;
}

static ULONG __saveds mPrint( struct IClass *cl,
                              Object *obj,
                              Msg msg )
{
    PrintInputHandlers(NULL);

    return 0;
}

static ULONG __saveds mRemove( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct InputHandlersWinData *ihwd = INST_DATA(cl, obj);
    struct InputHandlerEntry *ihe;

    if (ihe = (struct InputHandlerEntry *)GetActiveEntry(ihwd->ihwd_InputHandlerList)) {
        if (MyRequest(msgYesNo, msgWantToRemoveInputHandler, ihe->ihe_Name)) {
            MyDoCommand("RemoveInputHandler %s", ihe->ihe_Address);
            DoMethod(obj, MUIM_InputHandlersWin_Update);
        }
    }

    return 0;
}

static ULONG __saveds mPriority( struct IClass *cl,
                                 Object *obj,
                                 Msg msg )
{
    struct InputHandlersWinData *ihwd = INST_DATA(cl, obj);
    struct InputHandlerEntry *ihe;

    if (ihe = (struct InputHandlerEntry *)GetActiveEntry(ihwd->ihwd_InputHandlerList)) {
        LONG pri;

        pri = atol(ihe->ihe_Pri);
        if (GetPriority(ihe->ihe_Name, &pri)) {
            if (MyDoCommand("SetPriority INPUTHANDLER \"%s\" %ld", ihe->ihe_Name, pri)) {
                DoMethod(obj, MUIM_InputHandlersWin_Update);
            }
        }
    }

    return 0;
}

static ULONG __saveds mListChange( struct IClass *cl,
                                   Object *obj,
                                   Msg msg )
{
    struct InputHandlersWinData *ihwd = INST_DATA(cl, obj);
    struct InputHandlerEntry *ihe;

    if (ihe = (struct InputHandlerEntry *)GetActiveEntry(ihwd->ihwd_InputHandlerList)) {
        MySetContents(ihwd->ihwd_InputHandlerText, "%s \"%s\"", ihe->ihe_Address, ihe->ihe_Name);
        set(ihwd->ihwd_RemoveButton, MUIA_Disabled, FALSE);
        set(ihwd->ihwd_PriorityButton, MUIA_Disabled, FALSE);
    }

    return 0;
}

ULONG __asm __saveds InputHandlersWinDispatcher( register __a0 struct IClass *cl,
                                             register __a2 Object *obj,
                                             register __a1 Msg msg )
{
    switch (msg->MethodID) {
        case OM_NEW:                           return (mNew(cl, obj, (APTR)msg));
        case OM_DISPOSE:                       return (mDispose(cl, obj, (APTR)msg));
        case MUIM_InputHandlersWin_Update:     return (mUpdate(cl, obj, (APTR)msg));
        case MUIM_InputHandlersWin_Print:      return (mPrint(cl, obj, (APTR)msg));
        case MUIM_InputHandlersWin_Remove:     return (mRemove(cl, obj, (APTR)msg));
        case MUIM_InputHandlersWin_Priority:   return (mPriority(cl, obj, (APTR)msg));
        case MUIM_InputHandlersWin_ListChange: return (mListChange(cl, obj, (APTR)msg));
    }

    return (DoSuperMethodA(cl, obj, msg));
}

void PrintInputHandlers( char *filename )
{
    BPTR handle;

    if (handle = HandlePrintStart(filename)) {
        PrintFOneLine(handle, "\n  Address  Type       Pri    Data       Code     Name\n\n");
        IterateList(PrintCallback, (void *)handle);
    }

    HandlePrintStop();
}

void SendInputList( void )
{
    IterateList(SendCallback, NULL);
}

