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

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

MakeHook(reslist_con2hook, reslist_con2func);

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

    return 0;
}

MakeHook(reslist_des2hook, reslist_des2func);

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

    if (re) {
        msg->strings[0] = re->re_Address;
        msg->strings[1] = re->re_Name;
        msg->strings[2] = re->re_Type;
        msg->strings[3] = re->re_Pri;
        msg->strings[4] = re->re_Version;
        msg->strings[5] = re->re_OpenCount;
        msg->strings[6] = re->re_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(reslist_dsp2hook, reslist_dsp2func);

static LONG reslist_cmp2colfunc( struct ResourceEntry *re1,
                                 struct ResourceEntry *re2,
                                 ULONG column )
{
    LONG pri1, pri2;

    switch (column) {
        case 0: return stricmp(re1->re_Address, re2->re_Address);
        case 1: return stricmp(re1->re_Name, re2->re_Name);
        case 2: return stricmp(re1->re_Type, re2->re_Type);
        case 3: IsDec(re1->re_Pri, &pri1); IsDec(re2->re_Pri, &pri2); return pri2 - pri1;
        case 4: return stricmp(re1->re_Version, re2->re_Version);
        case 5: return stricmp(re1->re_OpenCount, re2->re_OpenCount);
        case 6: return stricmp(re1->re_RAMPtrCount, re2->re_RAMPtrCount);
    }
}

static __asm __saveds LONG reslist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct ResourceEntry *re1, *re2;
    ULONG col1, col2;

    re1 = (struct ResourceEntry *)msg->entry1;
    re2 = (struct ResourceEntry *)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 = reslist_cmp2colfunc(re2, re1, col1);
    } else {
        cmp = reslist_cmp2colfunc(re1, re2, col1);
    }

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

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = reslist_cmp2colfunc(re2, re1, col2);
    } else {
        cmp = reslist_cmp2colfunc(re1, re2, col2);
    }

    return cmp;
}

MakeHook(reslist_cmp2hook, reslist_cmp2func);

static BOOL TestResource( struct Library *lib )
{
    if (stricmp(lib->lib_Node.ln_Name, FSRNAME) == 0 ||
        stricmp(lib->lib_Node.ln_Name, CARDRESNAME) == 0 ||
        stricmp(lib->lib_Node.ln_Name, KEYMAPRESNAME) == 0) {
        return FALSE;
    } else {
        return TRUE;
    }
}

static void ReceiveList( void (* callback)( struct ResourceEntry *re, void *userData ),
                         void *userData )
{
    struct ResourceEntry *re;

    if (re = tbAllocVecPooled(globalPool, sizeof(struct ResourceEntry))) {
        if (SendDaemon("GetResList")) {
            while (ReceiveDecodedEntry((UBYTE *)re, sizeof(struct ResourceEntry))) {
                callback(re, userData);
            }
        }

        tbFreeVecPooled(globalPool, re);
    }
}

static void IterateList( void (* callback)( struct ResourceEntry *re, void *userData ),
                         void *userData )
{
    struct ResourceEntry *re;

    if (re = tbAllocVecPooled(globalPool, sizeof(struct ResourceEntry))) {
        struct Library *res;

        res = FIRSTRESOURCE;
        while (res->lib_Node.ln_Succ) {
            ULONG cnt;

            re->re_Addr = res;

            _snprintf(re->re_Address, sizeof(re->re_Address), "$%08lx", res);
            stccpy(re->re_Name, res->lib_Node.ln_Name, sizeof(re->re_Name));
            _snprintf(re->re_Pri, sizeof(re->re_Pri), "%4ld", res->lib_Node.ln_Pri);

            if (strcmp(re->re_Name, FSRNAME) == 0 || strcmp(re->re_Name, KEYMAPRESNAME) == 0) {
                stccpy(re->re_Version, "---", sizeof(re->re_Version));
            } else {
                _snprintf(re->re_Version, sizeof(re->re_Version), "%ld.%ld", res->lib_Version, res->lib_Revision);
            }

            if (TestResource(res)) {
                _snprintf(re->re_OpenCount, sizeof(re->re_OpenCount), "%6lD", res->lib_OpenCnt);

                cnt = GetRamPointerCount(res);
                if (cnt == (res->lib_NegSize / LIB_VECTSIZE)) {
                    stccpy(re->re_RAMPtrCount, "***", sizeof(re->re_RAMPtrCount));
                } else {
                    _snprintf(re->re_RAMPtrCount, sizeof(re->re_RAMPtrCount), "%4lD", cnt);
                }
            } else {
                stccpy(re->re_OpenCount, "---", sizeof(re->re_OpenCount));
                stccpy(re->re_RAMPtrCount, "---", sizeof(re->re_RAMPtrCount));
            }

            stccpy(re->re_Type, GetNodeType(res->lib_Node.ln_Type), sizeof(re->re_Type));

            callback(re, userData);

            res = (struct Library *)res->lib_Node.ln_Succ;
        }

        tbFreeVecPooled(globalPool, re);
    }
}

static void UpdateCallback( struct ResourceEntry *re,
                            void *userData )
{
    struct ResourcesCallbackUserData *ud = (struct ResourcesCallbackUserData *)userData;

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

static void PrintCallback( struct ResourceEntry *re,
                           void *userData )
{
   PrintFOneLine((BPTR)userData, " %s %4s %4s %4s %s %s\n", re->re_Address, re->re_Pri, re->re_OpenCount, re->re_RAMPtrCount, re->re_Name, re->re_Version);
}

static void SendCallback( struct ResourceEntry *re,
                          void *userData )
{
    SendEncodedEntry((UBYTE *)re, sizeof(struct ResourceEntry));
}

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

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, ResourcesText,
        MUIA_Window_ID, MakeID('R','E','S','O'),
        WindowContents, VGroup,

            Child, reslist = MyNListviewObject(MakeID('R','S','L','V'), "BAR,BAR,BAR P=" MUIX_C ",BAR P=" MUIX_R ",BAR P=" MUIX_C ",BAR P=" MUIX_R ",BAR P=" MUIX_R "", &reslist_con2hook, &reslist_des2hook, &reslist_dsp2hook, &reslist_cmp2hook, TRUE),
            Child, MyBelowListview(&restext, &rescount),

            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 ResourcesWinData *rwd = INST_DATA(cl, obj);
        APTR parent;

        rwd->rwd_ResourceList = reslist;
        rwd->rwd_ResourceText = restext;
        rwd->rwd_ResourceCount = rescount;
        rwd->rwd_RemoveButton = removeButton;
        rwd->rwd_PriorityButton = priorityButton;
        rwd->rwd_MoreButton = moreButton;
        rwd->rwd_FunctionsButton = funcButton;

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

        set(obj, MUIA_Window_Title, MyGetWindowTitle("RESOURCES", rwd->rwd_Title, sizeof(rwd->rwd_Title)));
        set(obj, MUIA_Window_ActiveObject, reslist);
        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(reslist,        MUIM_Notify, MUIA_NList_Active,        MUIV_EveryTime, obj,                     1, MUIM_ResourcesWin_ListChange);
        DoMethod(reslist,        MUIM_Notify, MUIA_NList_DoubleClick,   MUIV_EveryTime, obj,                     1, MUIM_ResourcesWin_More);
        DoMethod(updateButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_ResourcesWin_Update);
        DoMethod(printButton,    MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_ResourcesWin_Print);
        DoMethod(removeButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_ResourcesWin_Remove);
        DoMethod(moreButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_ResourcesWin_More);
        DoMethod(priorityButton, MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_ResourcesWin_Priority);
        DoMethod(funcButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_ResourcesWin_Functions);
        DoMethod(exitButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     3, MUIM_Set, MUIA_Window_CloseRequest, TRUE);
        DoMethod(reslist,        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 ResourcesWinData *rwd = INST_DATA(cl, obj);

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(rwd->rwd_ResourceList, MUIM_NList_Clear);

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

static ULONG __saveds mUpdate( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct ResourcesWinData *rwd = INST_DATA(cl, obj);
    struct ResourcesCallbackUserData ud;

    ApplicationSleep(TRUE);
    set(rwd->rwd_ResourceList, MUIA_NList_Quiet, TRUE);
    DoMethod(rwd->rwd_ResourceList, MUIM_NList_Clear);

    ud.ud_List = rwd->rwd_ResourceList;
    ud.ud_Count = 0;

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

    SetCountText(rwd->rwd_ResourceCount, ud.ud_Count);
    MySetContents(rwd->rwd_ResourceText, "");

    set(rwd->rwd_ResourceList, MUIA_NList_Quiet, FALSE);
    set(rwd->rwd_PriorityButton, MUIA_Disabled, TRUE);
    set(rwd->rwd_RemoveButton, MUIA_Disabled, TRUE);
    set(rwd->rwd_MoreButton, MUIA_Disabled, TRUE);
    set(rwd->rwd_FunctionsButton, MUIA_Disabled, TRUE);
    ApplicationSleep(FALSE);

    return 0;
}

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

    return 0;
}

static ULONG __saveds mRemove( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct ResourcesWinData *rwd = INST_DATA(cl, obj);
    struct ResourceEntry *re;

    if (re = (struct ResourceEntry *)GetActiveEntry(rwd->rwd_ResourceList)) {
        if (MyRequest(msgYesNo, msgWantToRemoveResource, re->re_Name)) {
            MyDoCommand("RemoveResource \"%s\"", re->re_Name);
            DoMethod(obj, MUIM_ResourcesWin_Update);
        }
    }

    return 0;
}

static ULONG __saveds mPriority( struct IClass *cl,
                                 Object *obj,
                                 Msg msg )
{
    struct ResourcesWinData *rwd = INST_DATA(cl, obj);
    struct ResourceEntry *re;

    if (re = (struct ResourceEntry *)GetActiveEntry(rwd->rwd_ResourceList)) {
        LONG pri;

        pri = atol(re->re_Pri);
        if (GetPriority(re->re_Name, &pri)) {
            if (MyDoCommand("SetPriority RESOURCE \"%s\" %ld", re->re_Name, pri)) {
                _snprintf(re->re_Pri, sizeof(re->re_Pri), "%4ld", pri);
                RedrawActiveEntry(rwd->rwd_ResourceList);
            }
        }
    }

    return 0;
}

static ULONG __saveds mMore( struct IClass *cl,
                             Object *obj,
                             Msg msg )
{
    struct ResourcesWinData *rwd = INST_DATA(cl, obj);
    struct ResourceEntry *re;

    if (re = (struct ResourceEntry *)GetActiveEntry(rwd->rwd_ResourceList)) {
        APTR detailWin;

        if (detailWin = ResourcesDetailWindowObject,
                MUIA_Window_ParentWindow, obj,
                MUIA_Window_MaxChildWindowCount, (opts.SingleWindows) ? 1 : 0,
            End) {
            set(detailWin, MUIA_ResourcesDetailWin_Resource, re);
            set(detailWin, MUIA_Window_Open, TRUE);
        }
    }

    return 0;
}

static ULONG __saveds mFunctions( struct IClass *cl,
                                  Object *obj,
                                  Msg msg )
{
    struct ResourcesWinData *rwd = INST_DATA(cl, obj);
    struct ResourceEntry *re;

    if (re = (struct ResourceEntry *)GetActiveEntry(rwd->rwd_ResourceList)) {
        APTR funcWin;

        if (funcWin = FunctionsWindowObject,
                MUIA_Window_ParentWindow, obj,
            End) {
            DoMethod(funcWin, MUIM_FunctionsWin_ShowFunctions, MUIV_FunctionsWin_NodeType_Resource, re->re_Addr, re->re_Name);
        }
    }

    return 0;
}

static ULONG __saveds mListChange( struct IClass *cl,
                                   Object *obj,
                                   Msg msg )
{
    struct ResourcesWinData *rwd = INST_DATA(cl, obj);
    struct ResourceEntry *re;

    if (re = (struct ResourceEntry *)GetActiveEntry(rwd->rwd_ResourceList)) {
        MySetContents(rwd->rwd_ResourceText, "%s \"%s\"", re->re_Address, re->re_Name);
        set(rwd->rwd_PriorityButton, MUIA_Disabled, FALSE);
        set(rwd->rwd_RemoveButton, MUIA_Disabled, FALSE);
        if (!clientstate) {
            set(rwd->rwd_MoreButton, MUIA_Disabled, FALSE);
            set(rwd->rwd_FunctionsButton, MUIA_Disabled, FALSE);
        }
    }

    return 0;
}

ULONG __asm __saveds ResourcesWinDispatcher( 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_ResourcesWin_Update:     return (mUpdate(cl, obj, (APTR)msg));
        case MUIM_ResourcesWin_Print:      return (mPrint(cl, obj, (APTR)msg));
        case MUIM_ResourcesWin_Remove:     return (mRemove(cl, obj, (APTR)msg));
        case MUIM_ResourcesWin_Priority:   return (mPriority(cl, obj, (APTR)msg));
        case MUIM_ResourcesWin_More:       return (mMore(cl, obj, (APTR)msg));
        case MUIM_ResourcesWin_Functions:  return (mFunctions(cl, obj, (APTR)msg));
        case MUIM_ResourcesWin_ListChange: return (mListChange(cl, obj, (APTR)msg));
    }

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

void PrintResources( 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 SendResList( void )
{
    IterateList(SendCallback, NULL);
}

