/**
 * 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"

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

    if (mfe) {
        msg->strings[0] = mfe->mfe_Lower;
        msg->strings[1] = mfe->mfe_Upper;
        msg->strings[2] = mfe->mfe_Size;
    } else {
        msg->strings[0] = MUIX_B "Lower";
        msg->strings[1] = MUIX_B "Upper";
        msg->strings[2] = MUIX_B "Size";
    }

    return 0;
}

MakeHook(memmorelist_dsp2hook, memmorelist_dsp2func);

static LONG memmorelist_cmp2colfunc( struct MemoryFreeEntry *mfe1,
                                     struct MemoryFreeEntry *mfe2,
                                     ULONG column )
{
    switch (column) {
        case 0: return stricmp(mfe1->mfe_Lower, mfe2->mfe_Lower);
        case 1: return stricmp(mfe1->mfe_Upper, mfe2->mfe_Upper);
        case 2: return stricmp(mfe1->mfe_Size, mfe2->mfe_Size);
    }
}

static __asm __saveds LONG memmorelist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct MemoryFreeEntry *mfe1, *mfe2;
    ULONG col1, col2;

    mfe1 = (struct MemoryFreeEntry *)msg->entry1;
    mfe2 = (struct MemoryFreeEntry *)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 = memmorelist_cmp2colfunc(mfe2, mfe1, col1);
    } else {
        cmp = memmorelist_cmp2colfunc(mfe1, mfe2, col1);
    }

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

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = memmorelist_cmp2colfunc(mfe2, mfe1, col2);
    } else {
        cmp = memmorelist_cmp2colfunc(mfe1, mfe2, col2);
    }

    return cmp;
}

MakeHook(memmorelist_cmp2hook, memmorelist_cmp2func);

static void SetDetails( struct IClass *cl,
                        Object *obj,
                        struct MemoryEntry *me )
{
    struct MemoryDetailWinData *mdwd = INST_DATA(cl, obj);
    UBYTE *tmp;
    static ULONG memtype[]  = { MEMF_PUBLIC, MEMF_CHIP, MEMF_FAST, MEMF_LOCAL,MEMF_24BITDMA, MEMF_KICK, MEMF_CLEAR, MEMF_LARGEST, MEMF_REVERSE, MEMF_TOTAL, MEMF_ANY };
    static UBYTE *memtypetext[] = { "PUBLIC", "CHIP", "FAST", "LOCAL", "24BITDMA", "KICK", "CLEAR", "LARGEST", "REVERSE", "TOTAL" };

    if (tmp = tbAllocVecPooled(mdwd->mdwd_MemoryPool, PATH_LENGTH)) {
        ULONG total, inuse;

        total = ((ULONG)me->me_Header->mh_Upper) - ((ULONG)me->me_Header->mh_Lower);
        inuse = total - (ULONG)me->me_Header->mh_Free;

        set(mdwd->mdwd_MemoryMoreText[0], MUIA_Text_Contents, me->me_Name);
        MySetContents(mdwd->mdwd_MemoryMoreText[1], MUIX_R "$%08lx\n" MUIX_C "%ld\n%s\n" MUIX_R "%lD\n%lD", me->me_Header, me->me_Header->mh_Node.ln_Pri, GetNodeType(me->me_Header->mh_Node.ln_Type), me->me_Header->mh_Free, AvailMem(MEMF_LARGEST | me->me_Header->mh_Attributes));
        MySetContents(mdwd->mdwd_MemoryMoreText[2], MUIX_R "$%08lx\n$%08lx\n$%08lx\n%lD\n%lD", me->me_Header->mh_First, me->me_Header->mh_Lower, me->me_Header->mh_Upper, inuse, total);

        tmp[0] = 0x00;
        if (me->me_Header->mh_Attributes) {
            ULONG i;

            i = 0;
            while (memtype[i]) {
                if (me->me_Header->mh_Attributes & memtype[i]) {
                    if (strlen(tmp)) _strcatn(tmp, ", ", PATH_LENGTH);
                    _strcatn(tmp, memtypetext[i], PATH_LENGTH);
                }

                i++;
            }
        } else {
            stccpy(tmp, "ANY", PATH_LENGTH);
        }
        set(mdwd->mdwd_MemoryMoreText[3], MUIA_Text_Contents, tmp);

        DoMethod(mdwd->mdwd_MemoryMoreList, MUIM_NList_Clear);

        if (me->me_Header->mh_First) {
            struct MemChunk *mc;
            struct MemoryFreeEntry *mfel;
            ULONG mccnt;

            mc = me->me_Header->mh_First;
            mccnt = 0;
            while (mc) {
                mccnt++;
                mc = mc->mc_Next;
            }
            mccnt += (mccnt / 10 < 0) ? 10 : (mccnt / 10);

            if (mfel = tbAllocVecPooled(mdwd->mdwd_MemoryPool, mccnt * sizeof(struct MemoryFreeEntry))) {
                struct MemoryFreeEntry *mfe;
                set(mdwd->mdwd_MemoryMoreList, MUIA_NList_Quiet, TRUE);

                mc = me->me_Header->mh_First;
                mfe = mfel;
                while (mc != NULL && mccnt > 0) {
                    _snprintf(mfe->mfe_Lower, sizeof(mfe->mfe_Lower), "$%08lx", mc);
                    _snprintf(mfe->mfe_Upper, sizeof(mfe->mfe_Upper), "$%08lx", (ULONG)mc + mc->mc_Bytes);
                    _snprintf(mfe->mfe_Size, sizeof(mfe->mfe_Size), "%12lD", mc->mc_Bytes);

                    InsertBottomEntry(mdwd->mdwd_MemoryMoreList, mfe);

                    mfe++;
                    mccnt--;

                    mc = mc->mc_Next;
                }

                set(mdwd->mdwd_MemoryMoreList, MUIA_NList_Quiet, FALSE);
            }
        }

        set(obj, MUIA_Window_Title, MyGetChildWindowTitle("MEMORY", me->me_Name, mdwd->mdwd_Title, sizeof(mdwd->mdwd_Title)));

        tbFreeVecPooled(mdwd->mdwd_MemoryPool, tmp);
    }
}

static ULONG __saveds mNew( struct IClass *cl,
                            Object *obj,
                            struct opSet *msg )
{
    APTR memmoretext[4], memmorelist;

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, MemoryText,
        MUIA_Window_ID, MakeID('.','M','E','M'),
        WindowContents, HGroup,
            Child, VGroup, MUIA_Group_SameWidth, TRUE,
                Child, MyLabel2("Name:"),
                Child, MyLabel2("Address:\nPri:\nType:\nFree:\nLargest:"),
                Child, MyLabel2("Attributes:"),
                Child, MyLabel2("\nChunks:"),
                Child, MyVSpace(0),
            End,
            Child, VGroup, MUIA_Group_SameWidth, TRUE,
                Child, memmoretext[0] = MyTextObject(),
                Child, HGroup,
                    Child, memmoretext[1] = MyTextObject2(),
                    Child, MyLabel("First:\nLower:\nUpper:\nInUse:\nTotal:"),
                    Child, memmoretext[2] = MyTextObject2(),
                End,
                Child, memmoretext[3] = MyTextObject(),

                Child, memmorelist = MyNListviewObject(MakeID('.','M','L','V'), "BAR,BAR,BAR P=" MUIX_R, NULL, NULL, &memmorelist_dsp2hook, &memmorelist_cmp2hook, FALSE),
            End,
        End,
        TAG_MORE, msg->ops_AttrList))
    {
        struct MemoryDetailWinData *mdwd = INST_DATA(cl, obj);
        APTR parent;

        CopyMem(memmoretext, mdwd->mdwd_MemoryMoreText, sizeof(mdwd->mdwd_MemoryMoreText));
        mdwd->mdwd_MemoryMoreList = memmorelist;
        mdwd->mdwd_MemoryPool = tbCreatePool(MEMF_CLEAR | MEMF_PUBLIC, 4096, 4096);

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

        set(obj, MUIA_Window_ActiveObject, memmorelist);

        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);
    }

    return (ULONG)obj;
}

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

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(mdwd->mdwd_MemoryMoreList, MUIM_NList_Clear);

    tbDeletePool(mdwd->mdwd_MemoryPool);

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

static ULONG __saveds mSet( struct IClass *cl,
                            Object *obj,
                            Msg msg )
{
    struct TagItem *tags, *tag;

    for (tags = ((struct opSet *)msg)->ops_AttrList; tag = NextTagItem(&tags); ) {
        switch (tag->ti_Tag) {
            case MUIA_Window_ParentWindow:
                DoMethod(obj, MUIM_Notify, MUIA_Window_CloseRequest, TRUE, MUIV_Notify_Application, 5, MUIM_Application_PushMethod, (APTR)tag->ti_Data, 2, MUIM_Window_RemChildWindow, obj);
                break;

            case MUIA_MemoryDetailWin_Memory:
                SetDetails(cl, obj, (struct MemoryEntry *)tag->ti_Data);
                break;
        }
    }

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

ULONG __asm __saveds MemoryDetailWinDispatcher( 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 OM_SET:     return (mSet(cl, obj, (APTR)msg));
    }

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

