/**
 * 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 DeviceCallbackUserData {
    APTR ud_List;
    ULONG ud_Count;
};

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

MakeHook(devlist_con2hook, devlist_con2func);

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

    return 0;
}

MakeHook(devlist_des2hook, devlist_des2func);

__asm __saveds LONG devlist_dsp2func(register __a2 Object *obj, register __a1 struct NList_DisplayMessage *msg, register __a0 struct Hook *hook)
{
    struct DeviceEntry *de = (struct DeviceEntry *)msg->entry;

    if (de) {
        msg->strings[0] = de->de_Address;
        msg->strings[1] = de->de_Name;
        msg->strings[2] = de->de_Type;
        msg->strings[3] = de->de_Pri;
        msg->strings[4] = de->de_Version;
        msg->strings[5] = de->de_OpenCount;
        msg->strings[6] = de->de_RAMPtrCount;
    } else {
        msg->strings[0] = MUIX_B "Address";
        msg->strings[1] = MUIX_B "ln_Name";
        msg->strings[2] = MUIX_B "ln_Type";
        msg->strings[3] = MUIX_B "ln_Pri";
        msg->strings[4] = MUIX_B "Version";
        msg->strings[5] = MUIX_B "OCnt";
        msg->strings[6] = MUIX_B "RPC";
    }

    return 0;
}

MakeHook(devlist_dsp2hook, devlist_dsp2func);

static LONG devlist_cmp2colfunc( struct DeviceEntry *de1,
                                 struct DeviceEntry *de2,
                                 ULONG column )
{
    LONG pri1, pri2;

    switch (column) {
        case 0: return stricmp(de1->de_Address, de2->de_Address);
        case 1: return stricmp(de1->de_Name, de2->de_Name);
        case 2: return stricmp(de1->de_Type, de2->de_Type);
        case 3: IsDec(de1->de_Pri, &pri1); IsDec(de2->de_Pri, &pri2); return pri2 - pri1;
        case 4: return stricmp(de1->de_Version, de2->de_Version);
        case 5: return stricmp(de1->de_OpenCount, de2->de_OpenCount);
        case 6: return stricmp(de1->de_RAMPtrCount, de2->de_RAMPtrCount);
    }
}

__asm __saveds LONG devlist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct DeviceEntry *de1, *de2;
    ULONG col1, col2;

    de1 = (struct DeviceEntry *)msg->entry1;
    de2 = (struct DeviceEntry *)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 = devlist_cmp2colfunc(de2, de1, col1);
    } else {
        cmp = devlist_cmp2colfunc(de1, de2, col1);
    }

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

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = devlist_cmp2colfunc(de2, de1, col2);
    } else {
        cmp = devlist_cmp2colfunc(de1, de2, col2);
    }

    return cmp;
}

MakeHook(devlist_cmp2hook, devlist_cmp2func);

void FlushDevices( void )
{
    struct Library *lib, *next;

    lib = FIRSTDEVICE;

    Forbid();
    while (next = (struct Library *)lib->lib_Node.ln_Succ) {
        if (lib->lib_OpenCnt == 0) RemDevice((struct Device *)lib);
        lib = next;
    }
    Permit();
}

static void ReceiveList( void (* callback)( struct DeviceEntry *de, void *userData ),
                         void *userData )
{
    struct DeviceEntry *de;

    if (de = tbAllocVecPooled(globalPool, sizeof(struct DeviceEntry))) {
        if (SendDaemon("GetDevList")) {
            while (ReceiveDecodedEntry((UBYTE *)de, sizeof(struct DeviceEntry))) {
                callback(de, userData);
            }
        }

        tbFreeVecPooled(globalPool, de);
    }
}

static void IterateList( void (* callback)( struct DeviceEntry *de, void *userData ),
                         void *userData )
{
    struct DeviceEntry *de;

    if (de = tbAllocVecPooled(globalPool, sizeof(struct DeviceEntry))) {
        struct Device *dd;

        dd = FIRSTDEVICE;
        while (dd->dd_Library.lib_Node.ln_Succ) {
            ULONG cnt;

            de->de_Addr = dd;

            _snprintf(de->de_Address, sizeof(de->de_Address), "$%08lx", dd);
            stccpy(de->de_Name, dd->dd_Library.lib_Node.ln_Name, sizeof(de->de_Name));
            _snprintf(de->de_Pri, sizeof(de->de_Pri), "%4ld", dd->dd_Library.lib_Node.ln_Pri);
            _snprintf(de->de_Version, sizeof(de->de_Version), "%ld.%ld", dd->dd_Library.lib_Version, dd->dd_Library.lib_Revision);
            _snprintf(de->de_OpenCount, sizeof(de->de_OpenCount), "%6lD", dd->dd_Library.lib_OpenCnt);

            cnt = GetRamPointerCount(&dd->dd_Library);
            if (cnt == (dd->dd_Library.lib_NegSize / LIB_VECTSIZE)) {
                stccpy(de->de_RAMPtrCount, "***", sizeof(de->de_RAMPtrCount));
            } else {
                _snprintf(de->de_RAMPtrCount, sizeof(de->de_RAMPtrCount), "%4lD", cnt);
            }

            stccpy(de->de_Type, GetNodeType(dd->dd_Library.lib_Node.ln_Type), sizeof(de->de_Type));

            callback(de, userData);

            dd = (struct Device *)dd->dd_Library.lib_Node.ln_Succ;
        }

        tbFreeVecPooled(globalPool, de);
    }
}

static void UpdateCallback( struct DeviceEntry *de,
                            void *userData )
{
    struct DeviceCallbackUserData *ud = (struct DeviceCallbackUserData *)userData;

    InsertSortedEntry(ud->ud_List, de);
    ud->ud_Count++;
}

static void PrintCallback( struct DeviceEntry *de,
                           void *userData )
{
    PrintFOneLine((BPTR)userData, " %s %4s %4s %4s %s %s\n", de->de_Address, de->de_Pri, de->de_OpenCount, de->de_RAMPtrCount, de->de_Name, de->de_Version);
}

static void SendCallback( struct DeviceEntry *de,
                          void *userData )
{
    SendEncodedEntry((UBYTE *)de, sizeof(struct DeviceEntry));
}

static ULONG __saveds mNew( struct IClass *cl,
                            Object *obj,
                            struct opSet *msg )
{
    APTR devlist, devtext, devcount, updateButton, printButton, removeButton, priorityButton, moreButton, funcButton, exitButton;

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, DevicesText,
        MUIA_Window_ID, MakeID('D','E','V','S'),
        WindowContents, VGroup,

            Child, devlist = MyNListviewObject(MakeID('D','E','L','V'), "BAR,BAR,BAR P=" MUIX_C ",BAR P=" MUIX_R ",BAR P=" MUIX_C ",BAR P=" MUIX_R ",BAR P=" MUIX_R, &devlist_con2hook, &devlist_des2hook, &devlist_dsp2hook, &devlist_cmp2hook, TRUE),
            Child, MyBelowListview(&devtext, &devcount),

            Child, MyVSpace(4),

            Child, HGroup, MUIA_Group_SameSize, TRUE,
                Child, priorityButton = MakeButton(txtPriority),
                Child, removeButton   = MakeButton(txtRemove),
                Child, funcButton     = MakeButton(txtFunctions),
            End,

            Child, HGroup, MUIA_Group_SameSize, TRUE,
                Child, updateButton   = MakeButton(txtUpdate),
                Child, printButton    = MakeButton(txtPrint),
                Child, moreButton     = MakeButton(txtMore),
                Child, exitButton     = MakeButton(txtExit),
            End,
        End,
        TAG_MORE, msg->ops_AttrList))
    {
        struct DevicesWinData *dwd = INST_DATA(cl, obj);
        APTR parent;

        dwd->dwd_DeviceList = devlist;
        dwd->dwd_DeviceText = devtext;
        dwd->dwd_DeviceCount = devcount;
        dwd->dwd_RemoveButton = removeButton;
        dwd->dwd_PriorityButton = priorityButton;
        dwd->dwd_MoreButton = moreButton;
        dwd->dwd_FunctionsButton = funcButton;

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

        set(obj, MUIA_Window_Title, MyGetWindowTitle("DEVICES", dwd->dwd_Title, sizeof(dwd->dwd_Title)));
        set(obj, MUIA_Window_ActiveObject, devlist);
        set(removeButton, MUIA_Disabled, TRUE);
        set(priorityButton, MUIA_Disabled, TRUE);
        set(moreButton, MUIA_Disabled, TRUE);
        set(funcButton, 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(devlist,         MUIM_Notify, MUIA_NList_Active,        MUIV_EveryTime, obj,                     1, MUIM_DevicesWin_ListChange);
        DoMethod(devlist,         MUIM_Notify, MUIA_NList_DoubleClick,   MUIV_EveryTime, obj,                     1, MUIM_DevicesWin_More);
        DoMethod(updateButton,    MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_DevicesWin_Update);
        DoMethod(printButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_DevicesWin_Print);
        DoMethod(removeButton,    MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_DevicesWin_Remove);
        DoMethod(moreButton,      MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_DevicesWin_More);
        DoMethod(priorityButton,  MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_DevicesWin_Priority);
        DoMethod(funcButton,      MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_DevicesWin_Functions);
        DoMethod(exitButton,      MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     3, MUIM_Set, MUIA_Window_CloseRequest, TRUE);
        DoMethod(devlist,         MUIM_NList_Sort3, MUIV_NList_Sort3_SortType_1, MUIV_NList_SortTypeAdd_None, MUIV_NList_Sort3_SortType_Both);
    }

    return (ULONG)obj;
}

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

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(dwd->dwd_DeviceList, MUIM_NList_Clear);

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

static ULONG __saveds mUpdate( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct DevicesWinData *dwd = INST_DATA(cl, obj);
    struct DeviceCallbackUserData ud;

    ApplicationSleep(TRUE);
    set(dwd->dwd_DeviceList, MUIA_NList_Quiet, TRUE);
    DoMethod(dwd->dwd_DeviceList, MUIM_NList_Clear);

    ud.ud_List = dwd->dwd_DeviceList;
    ud.ud_Count = 0;

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

    SetCountText(dwd->dwd_DeviceCount, ud.ud_Count);
    MySetContents(dwd->dwd_DeviceText, "");

    set(dwd->dwd_DeviceList, MUIA_NList_Quiet, FALSE);
    set(dwd->dwd_PriorityButton, MUIA_Disabled, TRUE);
    set(dwd->dwd_RemoveButton, MUIA_Disabled, TRUE);
    set(dwd->dwd_MoreButton, MUIA_Disabled, TRUE);
    set(dwd->dwd_FunctionsButton, MUIA_Disabled, TRUE);
    ApplicationSleep(FALSE);

    return 0;
}

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

    return 0;
}

static ULONG __saveds mRemove( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct DevicesWinData *dwd = INST_DATA(cl, obj);
    struct DeviceEntry *de;

    if (de = (struct DeviceEntry *)GetActiveEntry(dwd->dwd_DeviceList)) {
        if (MyRequest(msgYesNo, msgWantToRemoveDevice, de->de_Name)) {
            MyDoCommand("RemoveDevice \"%s\"", de->de_Name);
            DoMethod(obj, MUIM_DevicesWin_Update);
        }
    }

    return 0;
}

static ULONG __saveds mPriority( struct IClass *cl,
                                 Object *obj,
                                 Msg msg )
{
    struct DevicesWinData *dwd = INST_DATA(cl, obj);
    struct DeviceEntry *de;

    if (de = (struct DeviceEntry *)GetActiveEntry(dwd->dwd_DeviceList)) {
        LONG pri;

        pri = atol(de->de_Pri);
        if (GetPriority(de->de_Name, &pri)) {
            if (MyDoCommand("SetPriority DEVICE \"%s\" %ld", de->de_Name, pri)) {
                _snprintf(de->de_Pri, sizeof(de->de_Pri), "%4ld", pri);
                RedrawActiveEntry(dwd->dwd_DeviceList);
            }
        }
    }

    return 0;
}

static ULONG __saveds mMore( struct IClass *cl,
                             Object *obj,
                             Msg msg )
{
    struct DevicesWinData *dwd = INST_DATA(cl, obj);
    struct DeviceEntry *de;

    if (de = (struct DeviceEntry *)GetActiveEntry(dwd->dwd_DeviceList)) {
        APTR detailWin;

        if (detailWin = DevicesDetailWindowObject,
                MUIA_Window_Title, de->de_Name,
                MUIA_Window_ParentWindow, obj,
                MUIA_Window_MaxChildWindowCount, (opts.SingleWindows) ? 1 : 0,
            End) {
            set(detailWin, MUIA_DevicesDetailWin_Device, de);
            set(detailWin, MUIA_Window_Open, TRUE);
        }
    }

    return 0;
}

static ULONG __saveds mFunctions( struct IClass *cl,
                                  Object *obj,
                                  Msg msg )
{
    struct DevicesWinData *dwd = INST_DATA(cl, obj);
    struct DeviceEntry *de;

    if (de = (struct DeviceEntry *)GetActiveEntry(dwd->dwd_DeviceList)) {
        APTR funcWin;

        if (funcWin = FunctionsWindowObject,
                MUIA_Window_ParentWindow, obj,
            End) {
            DoMethod(funcWin, MUIM_FunctionsWin_ShowFunctions, MUIV_FunctionsWin_NodeType_Device, de->de_Addr, de->de_Name);
        }
    }

    return 0;
}

static ULONG __saveds mListChange( struct IClass *cl,
                                   Object *obj,
                                   Msg msg )
{
    struct DevicesWinData *dwd = INST_DATA(cl, obj);
    struct DeviceEntry *de;

    if (de = (struct DeviceEntry *)GetActiveEntry(dwd->dwd_DeviceList)) {
        MySetContents(dwd->dwd_DeviceText, "%s \"%s\"", de->de_Address, de->de_Name);
        set(dwd->dwd_PriorityButton, MUIA_Disabled, FALSE);
        set(dwd->dwd_RemoveButton, MUIA_Disabled, FALSE);
        if (!clientstate) {
            set(dwd->dwd_MoreButton, MUIA_Disabled, FALSE);
            set(dwd->dwd_FunctionsButton, MUIA_Disabled, FALSE);
        }
    }

    return 0;
}

ULONG __asm __saveds DevicesWinDispatcher( 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_DevicesWin_Update:     return (mUpdate(cl, obj, (APTR)msg));
        case MUIM_DevicesWin_Print:      return (mPrint(cl, obj, (APTR)msg));
        case MUIM_DevicesWin_Remove:     return (mRemove(cl, obj, (APTR)msg));
        case MUIM_DevicesWin_Priority:   return (mPriority(cl, obj, (APTR)msg));
        case MUIM_DevicesWin_More:       return (mMore(cl, obj, (APTR)msg));
        case MUIM_DevicesWin_Functions:  return (mFunctions(cl, obj, (APTR)msg));
        case MUIM_DevicesWin_ListChange: return (mListChange(cl, obj, (APTR)msg));
    }

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

void PrintDevices( char *filename )
{
    BPTR handle;

    if (handle = HandlePrintStart(filename)) {
        PrintFOneLine(handle, "\n  Address   Pri  OpenC  RPC Name & Version\n\n");
        IterateList(PrintCallback, (void *)handle);
    }

    HandlePrintStop();
}

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

