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

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

MakeHook(memlist_con2hook, memlist_con2func);

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

    return 0;
}

MakeHook(memlist_des2hook, memlist_des2func);

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

    if (me) {
        msg->strings[0] = me->me_Address;
        msg->strings[1] = me->me_Name;
        msg->strings[2] = me->me_Type;
        msg->strings[3] = me->me_Pri;
        msg->strings[4] = me->me_Lower;
        msg->strings[5] = me->me_Upper;
        msg->strings[6] = me->me_Attributes;
    } 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 "mh_Lower";
        msg->strings[5] = MUIX_B "mh_Upper";
        msg->strings[6] = MUIX_B "mh_Attr";
    }

    return 0;
}

MakeHook(memlist_dsp2hook, memlist_dsp2func);

static LONG memlist_cmp2colfunc( struct MemoryEntry *me1,
                                 struct MemoryEntry *me2,
                                 ULONG column )
{
    LONG pri1, pri2;

    switch (column) {
        case 0: return stricmp(me1->me_Address, me2->me_Address);
        case 1: return stricmp(me1->me_Name, me2->me_Name);
        case 2: return stricmp(me1->me_Type, me2->me_Type);
        case 3: IsDec(me1->me_Pri, &pri1); IsDec(me2->me_Pri, &pri2); return pri2 - pri1;
        case 4: return stricmp(me1->me_Lower, me2->me_Lower);
        case 5: return stricmp(me1->me_Upper, me2->me_Upper);
        case 6: return stricmp(me1->me_Attributes, me2->me_Attributes);
    }
}

static __asm __saveds LONG memlist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct MemoryEntry *me1, *me2;
    ULONG col1, col2;

    me1 = (struct MemoryEntry *)msg->entry1;
    me2 = (struct MemoryEntry *)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 = memlist_cmp2colfunc(me2, me1, col1);
    } else {
        cmp = memlist_cmp2colfunc(me1, me2, col1);
    }

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

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = memlist_cmp2colfunc(me2, me1, col2);
    } else {
        cmp = memlist_cmp2colfunc(me1, me2, col2);
    }

    return cmp;
}

MakeHook(memlist_cmp2hook, memlist_cmp2func);

static void ReceiveList( void (* callback)( struct MemoryEntry *me, void *userData ),
                         void *userData )
{
    struct MemoryEntry *me;

    if (me = tbAllocVecPooled(globalPool, sizeof(struct MemoryEntry))) {
        if (SendDaemon("GetMemList")) {
            while (ReceiveDecodedEntry((UBYTE *)me, sizeof(struct MemoryEntry))) {
                callback(me, userData);
            }
        }

        tbFreeVecPooled(globalPool, me);
    }
}

static void IterateList( void (* callback)( struct MemoryEntry *me, void *userData ),
                         void *userData )
{
    struct MemoryEntry *me;

    if (me = tbAllocVecPooled(globalPool, sizeof(struct MemoryEntry))) {
        struct MemHeader *mh;

        mh = FIRSTMEMORY;

        while (mh->mh_Node.ln_Succ) {
            me->me_Header = mh;
            _snprintf(me->me_Address, sizeof(me->me_Address), "$%08lx", mh);
            stccpy(me->me_Name, nonetest(mh->mh_Node.ln_Name), sizeof(me->me_Name));
            stccpy(me->me_Type, GetNodeType(mh->mh_Node.ln_Type), sizeof(me->me_Type));
            _snprintf(me->me_Pri, sizeof(me->me_Pri), "%4ld", mh->mh_Node.ln_Pri);
            _snprintf(me->me_Lower, sizeof(me->me_Lower), "$%08lx", mh->mh_Lower);
            _snprintf(me->me_Upper, sizeof(me->me_Upper), "$%08lx", mh->mh_Upper);
            _snprintf(me->me_Attributes, sizeof(me->me_Attributes), "$%04lx", mh->mh_Attributes);

            callback(me, userData);

            mh = (struct MemHeader *)mh->mh_Node.ln_Succ;
        }

        tbFreeVecPooled(globalPool, me);
    }
}

static void UpdateCallback( struct MemoryEntry *me,
                            void *userData )
{
    struct MemoryCallbackUserData *ud = (struct MemoryCallbackUserData *)userData;

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

static void PrintCallback( struct MemoryEntry *me,
                           void *userData )
{
    PrintFOneLine((BPTR)userData, " %s %-20.20s %-8s%4s %s %s %s\n", me->me_Address, me->me_Name, me->me_Type, me->me_Pri, me->me_Lower, me->me_Upper, me->me_Attributes);
}

static void SendCallback( struct MemoryEntry *me,
                          void *userData )
{
    SendEncodedEntry((UBYTE *)me, sizeof(struct MemoryEntry));
}

static ULONG __saveds mNew( struct IClass *cl,
                            Object *obj,
                            struct opSet *msg )
{
    APTR memlist, memtext, updateButton, printButton, priorityButton, moreButton, exitButton;

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, MemoryText,
        MUIA_Window_ID, MakeID('M','E','M','O'),
        WindowContents, VGroup,

            Child, memlist = MyNListviewObject(MakeID('M','E','L','V'), "BAR,BAR,BAR P=" MUIX_C ",BAR P=" MUIX_R ",BAR,BAR,BAR", &memlist_con2hook, &memlist_des2hook, &memlist_dsp2hook, &memlist_cmp2hook, TRUE),
            Child, memtext = MyTextObject(),

            Child, MyVSpace(4),

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

        mwd->mwd_MemoryList = memlist;
        mwd->mwd_MemoryText = memtext;
        mwd->mwd_PriorityButton = priorityButton;
        mwd->mwd_MoreButton = moreButton;

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

        set(obj, MUIA_Window_Title, MyGetWindowTitle("MEMORY", mwd->mwd_Title, sizeof(mwd->mwd_Title)));
        set(obj, MUIA_Window_ActiveObject, memlist);
        set(priorityButton, MUIA_Disabled, TRUE);
        set(moreButton, 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(memlist,        MUIM_Notify, MUIA_NList_Active,        MUIV_EveryTime, obj,                     1, MUIM_MemoryWin_ListChange);
        DoMethod(memlist,        MUIM_Notify, MUIA_NList_DoubleClick,   MUIV_EveryTime, obj,                     1, MUIM_MemoryWin_More);
        DoMethod(updateButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_MemoryWin_Update);
        DoMethod(printButton,    MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_MemoryWin_Print);
        DoMethod(priorityButton, MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_MemoryWin_Priority);
        DoMethod(moreButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_MemoryWin_More);
        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 MemoryWinData *mwd = INST_DATA(cl, obj);

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(mwd->mwd_MemoryList, MUIM_NList_Clear);

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

static ULONG __saveds mUpdate( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct MemoryWinData *mwd = INST_DATA(cl, obj);
    struct MemoryCallbackUserData ud;

    ApplicationSleep(TRUE);
    set(mwd->mwd_MemoryList, MUIA_NList_Quiet, TRUE);
    DoMethod(mwd->mwd_MemoryList, MUIM_NList_Clear);

    ud.ud_List = mwd->mwd_MemoryList;
    ud.ud_Count = 0;

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

    MySetContents(mwd->mwd_MemoryText, "");

    set(mwd->mwd_MemoryList, MUIA_NList_Quiet, FALSE);
    set(mwd->mwd_PriorityButton, MUIA_Disabled, TRUE);
    set(mwd->mwd_MoreButton, MUIA_Disabled, TRUE);
    ApplicationSleep(FALSE);

    return 0;
}

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

    return 0;
}

static ULONG __saveds mPriority( struct IClass *cl,
                                 Object *obj,
                                 Msg msg )
{
    struct MemoryWinData *mwd = INST_DATA(cl, obj);
    struct MemoryEntry *me;

    if (me = (struct MemoryEntry *)GetActiveEntry(mwd->mwd_MemoryList)) {
        LONG pri;

        pri = atol(me->me_Pri);
        if (GetPriority(me->me_Name, &pri)) {
            if (MyDoCommand("SetPriority MEMORY \"%s\" %ld", me->me_Name, pri)) {
                _snprintf(me->me_Pri, sizeof(me->me_Pri), "%4ld", pri);
                RedrawActiveEntry(mwd->mwd_MemoryList);
            }
        }
    }

    return 0;
}

static ULONG __saveds mMore( struct IClass *cl,
                             Object *obj,
                             Msg msg )
{
    struct MemoryWinData *mwd = INST_DATA(cl, obj);
    struct MemoryEntry *me;

    if (me = (struct MemoryEntry *)GetActiveEntry(mwd->mwd_MemoryList)) {
        APTR detailWin;

        if (detailWin = MemoryDetailWindowObject,
                MUIA_Window_ParentWindow, obj,
            End) {
            set(detailWin, MUIA_MemoryDetailWin_Memory, me);
            set(detailWin, MUIA_Window_Open, TRUE);
        }
    }

    return 0;
}

static ULONG __saveds mListChange( struct IClass *cl,
                                   Object *obj,
                                   Msg msg )
{
    struct MemoryWinData *mwd = INST_DATA(cl, obj);
    struct MemoryEntry *me;

    if (me = (struct MemoryEntry *)GetActiveEntry(mwd->mwd_MemoryList)) {
        MySetContents(mwd->mwd_MemoryText, "%s \"%s\"", me->me_Address, me->me_Name);
        set(mwd->mwd_PriorityButton, MUIA_Disabled, FALSE);
        if (!clientstate) set(mwd->mwd_MoreButton, MUIA_Disabled, FALSE);
    }

    return 0;
}

ULONG __asm __saveds MemoryWinDispatcher( 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_MemoryWin_Update:     return (mUpdate(cl, obj, (APTR)msg));
        case MUIM_MemoryWin_Print:      return (mPrint(cl, obj, (APTR)msg));
        case MUIM_MemoryWin_Priority:   return (mPriority(cl, obj, (APTR)msg));
        case MUIM_MemoryWin_More:       return (mMore(cl, obj, (APTR)msg));
        case MUIM_MemoryWin_ListChange: return (mListChange(cl, obj, (APTR)msg));
    }

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

void PrintMemory( char *filename )
{
    BPTR handle;

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

    HandlePrintStop();
}

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

