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

// this structure works with locale.library 44.6
// there is no guarantee that it will work with previous or future versions
struct PrivateLocaleBase {
    struct Library plb_LibNode;
    UBYTE plb_pad[94];
    struct List plb_CatalogList;
};

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

MakeHook(catlist_con2hook, catlist_con2func);

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

    return 0;
}

MakeHook(catlist_des2hook, catlist_des2func);

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

    if (ce) {
        msg->strings[0] = ce->ce_Address;
        msg->strings[1] = ce->ce_Name;
        msg->strings[2] = ce->ce_Version;
        msg->strings[3] = ce->ce_Language;
    } else {
        msg->strings[0] = MUIX_B "Address";
        msg->strings[1] = MUIX_B "cat_Name";
        msg->strings[2] = MUIX_B "cat_Version";
        msg->strings[3] = MUIX_B "cat_Language";
    }

    return 0;
}

MakeHook(catlist_dsp2hook, catlist_dsp2func);

static LONG catlist_cmp2colfunc( struct CatalogEntry *ce1,
                                struct CatalogEntry *ce2,
                                ULONG column )
{
    switch (column) {
        case 0: return stricmp(ce1->ce_Address, ce2->ce_Address);
        case 1: return stricmp(ce1->ce_Name, ce2->ce_Name);
        case 2: return stricmp(ce1->ce_Version, ce2->ce_Version);
        case 3: return stricmp(ce1->ce_Language, ce2->ce_Language);
    }
}

static __asm __saveds LONG catlist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct CatalogEntry *ce1, *ce2;
    ULONG col1, col2;

    ce1 = (struct CatalogEntry *)msg->entry1;
    ce2 = (struct CatalogEntry *)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 = catlist_cmp2colfunc(ce2, ce1, col1);
    } else {
        cmp = catlist_cmp2colfunc(ce1, ce2, col1);
    }

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

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = catlist_cmp2colfunc(ce2, ce1, col2);
    } else {
        cmp = catlist_cmp2colfunc(ce1, ce2, col2);
    }

    return cmp;
}

MakeHook(catlist_cmp2hook, catlist_cmp2func);

static void ReceiveList( void (* callback)( struct CatalogEntry *ce, void *userData ),
                         void *userData )
{
    struct CatalogEntry *ce;

    if (ce = tbAllocVecPooled(globalPool, sizeof(struct CatalogEntry))) {
        if (SendDaemon("GetCatalogList")) {
            while (ReceiveDecodedEntry((UBYTE *)ce, sizeof(struct CatalogEntry))) {
                callback(ce, userData);
            }
        }

        tbFreeVecPooled(globalPool, ce);
    }
}

static void IterateList( void (* callback)( struct CatalogEntry *ce, void *userData ),
                         void *userData )
{
    struct PrivateLocaleBase *LocaleBase;

    if (LocaleBase = (struct PrivateLocaleBase *)OpenLibrary("locale.library", 38)) {
        struct Catalog *cat;
        struct CatalogEntry *ce;

        if (ce = tbAllocVecPooled(globalPool, sizeof(struct CatalogEntry))) {
            for (cat = (struct Catalog *)LocaleBase->plb_CatalogList.lh_Head; cat->cat_Link.ln_Succ; cat = (struct Catalog *)cat->cat_Link.ln_Succ) {

                ce->ce_Addr = cat;
                _snprintf(ce->ce_Address, sizeof(ce->ce_Address), "$%08lx", cat);
                stccpy(ce->ce_Name, nonetest(cat->cat_Link.ln_Name), sizeof(ce->ce_Name));
                _snprintf(ce->ce_Version, sizeof(ce->ce_Version), "%ld.%ld", cat->cat_Version, cat->cat_Revision);
                stccpy(ce->ce_Language, nonetest(cat->cat_Language), sizeof(ce->ce_Language));

                callback(ce, userData);
            }

            tbFreeVecPooled(globalPool, ce);
        }

        CloseLibrary((struct Library *)LocaleBase);
    }
}

static void UpdateCallback( struct CatalogEntry *ce,
                            void *userData )
{
    struct CatalogsCallbackUserData *ud = (struct CatalogsCallbackUserData *)userData;

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

static void PrintCallback( struct CatalogEntry *ce,
                           void *userData )
{
    PrintFOneLine((BPTR)userData, " %s   %-5.5s %-10.10s %s\n", ce->ce_Address, ce->ce_Version, ce->ce_Language, ce->ce_Name);
}

static void SendCallback( struct CatalogEntry *ce,
                          void *userData )
{
    SendEncodedEntry((UBYTE *)ce, sizeof(struct CatalogEntry));
}

static ULONG __saveds mNew( struct IClass *cl,
                            Object *obj,
                            struct opSet *msg )
{
    APTR catlist, cattext, catcount, updateButton, printButton, exitButton;

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, CatalogsText,
        MUIA_Window_ID, MakeID('C','A','T','A'),
        WindowContents, VGroup,

            Child, catlist = MyNListviewObject(MakeID('C','A','L','V'), "BAR,BAR,BAR P=" MUIX_C ",BAR", &catlist_con2hook, &catlist_des2hook, &catlist_dsp2hook, &catlist_cmp2hook, TRUE),
            Child, MyBelowListview(&cattext, &catcount),

            Child, MyVSpace(4),

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

        cwd->cwd_CatalogList = catlist;
        cwd->cwd_CatalogText = cattext;
        cwd->cwd_CatalogCount = catcount;

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

        set(obj, MUIA_Window_Title, MyGetWindowTitle("CATALOGS", cwd->cwd_Title, sizeof(cwd->cwd_Title)));
        set(obj, MUIA_Window_ActiveObject, catlist);

        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(catlist,         MUIM_Notify, MUIA_NList_Active,        MUIV_EveryTime, obj,                     1, MUIM_CatalogsWin_ListChange);
        DoMethod(updateButton,    MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_CatalogsWin_Update);
        DoMethod(printButton,     MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_CatalogsWin_Print);
        DoMethod(exitButton,      MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     3, MUIM_Set, MUIA_Window_CloseRequest, TRUE);
        DoMethod(catlist,         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 CatalogsWinData *cwd = INST_DATA(cl, obj);

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(cwd->cwd_CatalogList, MUIM_NList_Clear);

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

static ULONG __saveds mUpdate( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct CatalogsWinData *cwd = INST_DATA(cl, obj);
    struct CatalogsCallbackUserData ud;

    ApplicationSleep(TRUE);
    set(cwd->cwd_CatalogList, MUIA_NList_Quiet, TRUE);
    DoMethod(cwd->cwd_CatalogList, MUIM_NList_Clear);

    ud.ud_List = cwd->cwd_CatalogList;
    ud.ud_Count = 0;

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

    SetCountText(cwd->cwd_CatalogCount, ud.ud_Count);
    MySetContents(cwd->cwd_CatalogText, "");

    set(cwd->cwd_CatalogList, MUIA_NList_Quiet, FALSE);
    ApplicationSleep(FALSE);

    return 0;
}

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

    return 0;
}

static ULONG __saveds mListChange( struct IClass *cl,
                                   Object *obj,
                                   Msg msg )
{
    struct CatalogsWinData *cwd = INST_DATA(cl, obj);
    struct CatalogEntry *ce;

    if (ce = (struct CatalogEntry *)GetActiveEntry(cwd->cwd_CatalogList)) {
        MySetContents(cwd->cwd_CatalogText, "%s \"%s\"", ce->ce_Address, ce->ce_Name);
    }

    return 0;
}

ULONG __asm __saveds CatalogsWinDispatcher( 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_CatalogsWin_Update:     return (mUpdate(cl, obj, (APTR)msg));
        case MUIM_CatalogsWin_Print:      return (mPrint(cl, obj, (APTR)msg));
        case MUIM_CatalogsWin_ListChange: return (mListChange(cl, obj, (APTR)msg));
    }

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

void PrintCatalogs( char *filename )
{
    BPTR handle;

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

    HandlePrintStop();
}

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

