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

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

MakeHook(amodelist_con2hook, amodelist_con2func);

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

    return 0;
}

MakeHook(amodelist_des2hook, amodelist_des2func);

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

    if (ame) {
        msg->strings[0] = ame->ame_Id;
        msg->strings[1] = ame->ame_Name;
        msg->strings[2] = ame->ame_Bits;
        msg->strings[3] = ame->ame_MinFrequency;
        msg->strings[4] = ame->ame_MaxFrequency;
    } else {
        msg->strings[0] = MUIX_B "ModeID";
        msg->strings[1] = MUIX_B "Name";
        msg->strings[2] = MUIX_B "Bits";
        msg->strings[3] = MUIX_B "min. Freq";
        msg->strings[4] = MUIX_B "max. Freq";
    }

    return 0;
}

MakeHook(amodelist_dsp2hook, amodelist_dsp2func);

static LONG amodelist_cmp2colfunc( struct AudioModeEntry *ame1,
                                   struct AudioModeEntry *ame2,
                                   ULONG column )
{
    LONG dec1, dec2;

    switch (column) {
        case 0: return stricmp(ame1->ame_Id, ame2->ame_Id);
        case 1: return stricmp(ame1->ame_Name, ame2->ame_Name);
        case 2: IsDec(ame1->ame_Bits, &dec1); IsDec(ame2->ame_Bits, &dec2); return dec2 - dec1;
        case 3: IsDec(ame1->ame_MinFrequency, &dec1); IsDec(ame2->ame_MinFrequency, &dec2); return dec2 - dec1;
        case 4: IsDec(ame1->ame_MaxFrequency, &dec1); IsDec(ame2->ame_MaxFrequency, &dec2); return dec2 - dec1;
    }
}

static __asm __saveds LONG amodelist_cmp2func(register __a2 Object *obj, register __a1 struct NList_CompareMessage *msg, register __a0 struct Hook *hook)
{
    LONG cmp;
    struct AudioModeEntry *ame1, *ame2;
    ULONG col1, col2;

    ame1 = (struct AudioModeEntry *)msg->entry1;
    ame2 = (struct AudioModeEntry *)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 = amodelist_cmp2colfunc(ame2, ame1, col1);
    } else {
        cmp = amodelist_cmp2colfunc(ame1, ame2, col1);
    }

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

    if (msg->sort_type2 & MUIV_NList_TitleMark2_TypeMask) {
        cmp = amodelist_cmp2colfunc(ame2, ame1, col2);
    } else {
        cmp = amodelist_cmp2colfunc(ame1, ame2, col2);
    }

    return cmp;
}

MakeHook(amodelist_cmp2hook, amodelist_cmp2func);

static void ReceiveList( void (* callback)( struct AudioModeEntry *ame, void *userData ),
                         void *userData )
{
    struct AudioModeEntry *ame;

    if (ame = tbAllocVecPooled(globalPool, sizeof(struct AudioModeEntry))) {
        if (SendDaemon("GetAudioModelist")) {
            while (ReceiveDecodedEntry((UBYTE *)ame, sizeof(struct AudioModeEntry))) {
                callback(ame, userData);
            }
        }

        tbFreeVecPooled(globalPool, ame);
    }
}

static void IterateList( void (* callback)( struct AudioModeEntry *ame, void *userData ),
                         void *userData )
{
    struct AudioModeEntry *ame;

    if (ame = tbAllocVecPooled(globalPool, sizeof(struct AudioModeEntry))) {
        struct MsgPort *mp;

        if (mp = CreateMsgPort()) {
            struct AHIRequest *ahir;

            if (ahir = CreateIORequest(mp, sizeof(struct AHIRequest))) {
                ahir->ahir_Version = 4;

                if (OpenDevice(AHINAME, 0, ahir, 0) == 0) {
                    struct Device *AHIBase;
                    ULONG id = AHI_INVALID_ID;

                    AHIBase = ahir->ahir_Std.io_Device;

                    while ((id = AHI_NextAudioID(id)) != AHI_INVALID_ID) {
                        ULONG bits, minfreq, maxfreq, numfreqs;

                        ame->ame_ModeID = id;
                        _snprintf(ame->ame_Id, sizeof(ame->ame_Id), "$%08lx", id);

                        AHI_GetAudioAttrs(id, NULL, AHIDB_Name, ame->ame_Name,
                                                    AHIDB_BufferLen, sizeof(ame->ame_Name),
                                                    TAG_DONE);
                        AHI_GetAudioAttrs(id, NULL, AHIDB_Bits, &bits,
                                                    AHIDB_MinMixFreq, &minfreq,
                                                    AHIDB_MaxMixFreq, &maxfreq,
                                                    AHIDB_Frequencies, &numfreqs,
                                                    TAG_DONE);
                        _snprintf(ame->ame_Bits, sizeof(ame->ame_Bits), "%3lD", bits);
                        if (numfreqs > 1) {
                            _snprintf(ame->ame_MinFrequency, sizeof(ame->ame_MinFrequency), "%6lD Hz", minfreq);
                            _snprintf(ame->ame_MaxFrequency, sizeof(ame->ame_MaxFrequency), "%6lD Hz", maxfreq);
                        } else {
                            stccpy(ame->ame_MinFrequency, "---", sizeof(ame->ame_MinFrequency));
                            stccpy(ame->ame_MaxFrequency, "---", sizeof(ame->ame_MaxFrequency));
                        }

                        callback(ame, userData);
                    }

                    CloseDevice(ahir);
                } else {
                    MyRequest(msgErrorContinue, msgCantOpenAHIDevice, AHINAME, ahir->ahir_Version);
                }

                DeleteIORequest(ahir);
            }

            DeleteMsgPort(mp);
        }

        tbFreeVecPooled(globalPool, ame);
    }
}

static void UpdateCallback( struct AudioModeEntry *ame,
                            void *userData )
{
    struct AudioModesCallbackUserData *ud = (struct AudioModesCallbackUserData *)userData;

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

static void PrintCallback( struct AudioModeEntry *ame,
                           void *userData )
{
    PrintFOneLine((BPTR)userData, " %s %4s %8s %8s %s\n", ame->ame_Id, ame->ame_Bits, ame->ame_MinFrequency, ame->ame_MaxFrequency, ame->ame_Name);
}

static void SendCallback( struct AudioModeEntry *ame,
                          void *userData )
{
    SendEncodedEntry((UBYTE *)ame, sizeof(struct AudioModeEntry));
}

static ULONG __saveds mNew( struct IClass *cl,
                            Object *obj,
                            struct opSet *msg )
{
    APTR amodelist, amodetext, amodecount, updateButton, printButton, moreButton, exitButton;

    if (obj = (Object *)DoSuperNew(cl, obj,
        MUIA_HelpNode, AudioModesText,
        MUIA_Window_ID, MakeID('A','M','D','E'),
        WindowContents, VGroup,

            Child, amodelist = MyNListviewObject(MakeID('A','M','L','V'), "BAR,BAR,BAR P=" MUIX_R ",BAR P=" MUIX_R ",BAR P=" MUIX_R, &amodelist_con2hook, &amodelist_des2hook, &amodelist_dsp2hook, &amodelist_cmp2hook, TRUE),
            Child, MyBelowListview(&amodetext, &amodecount),

            Child, MyVSpace(4),

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

        amwd->amwd_AudioModeList = amodelist;
        amwd->amwd_AudioModeText = amodetext;
        amwd->amwd_AudioModeCount = amodecount;
        amwd->amwd_MoreButton = moreButton;

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

        set(obj, MUIA_Window_Title, MyGetWindowTitle("AUDIOMODES", amwd->amwd_Title, sizeof(amwd->amwd_Title)));
        set(obj, MUIA_Window_ActiveObject, amodelist);
        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(amodelist,    MUIM_Notify, MUIA_NList_Active,        MUIV_EveryTime, obj,                     1, MUIM_AudioModesWin_ListChange);
        DoMethod(amodelist,    MUIM_Notify, MUIA_NList_DoubleClick,   MUIV_EveryTime, obj,                     1, MUIM_AudioModesWin_More);
        DoMethod(updateButton, MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_AudioModesWin_Update);
        DoMethod(printButton,  MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_AudioModesWin_Print);
        DoMethod(moreButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     1, MUIM_AudioModesWin_More);
        DoMethod(exitButton,   MUIM_Notify, MUIA_Pressed,             FALSE,          obj,                     3, MUIM_Set, MUIA_Window_CloseRequest, TRUE);
        DoMethod(amodelist,    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 AudioModesWinData *amwd = INST_DATA(cl, obj);

    set(obj, MUIA_Window_Open, FALSE);
    DoMethod(amwd->amwd_AudioModeList, MUIM_NList_Clear);

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

static ULONG __saveds mUpdate( struct IClass *cl,
                               Object *obj,
                               Msg msg )
{
    struct AudioModesWinData *amwd = INST_DATA(cl, obj);
    struct AudioModesCallbackUserData ud;

    ApplicationSleep(TRUE);
    set(amwd->amwd_AudioModeList, MUIA_NList_Quiet, TRUE);
    DoMethod(amwd->amwd_AudioModeList, MUIM_NList_Clear);

    ud.ud_List = amwd->amwd_AudioModeList;
    ud.ud_Count = 0;

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

    SetCountText(amwd->amwd_AudioModeCount, ud.ud_Count);
    MySetContents(amwd->amwd_AudioModeText, "");

    set(amwd->amwd_AudioModeList, MUIA_NList_Quiet, FALSE);
    set(amwd->amwd_MoreButton, MUIA_Disabled, TRUE);
    ApplicationSleep(FALSE);

    return 0;
}

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

    return 0;
}

static ULONG __saveds mMore( struct IClass *cl,
                             Object *obj,
                             Msg msg )
{
    struct AudioModesWinData *amwd = INST_DATA(cl, obj);
    struct AudioModeEntry *ame;

    if (ame = (struct AudioModeEntry *)GetActiveEntry(amwd->amwd_AudioModeList)) {
        APTR detailWin;

        if (detailWin = AudioModesDetailWindowObject,
                MUIA_Window_ParentWindow, obj,
            End) {
            set(detailWin, MUIA_AudioModesDetailWin_AudioMode, ame);
            set(detailWin, MUIA_Window_Open, TRUE);
        }
    }

    return 0;
}

static ULONG __saveds mListChange( struct IClass *cl,
                                   Object *obj,
                                   Msg msg )
{
    struct AudioModesWinData *amwd = INST_DATA(cl, obj);
    struct AudioModeEntry *ame;

    if (ame = (struct AudioModeEntry *)GetActiveEntry(amwd->amwd_AudioModeList)) {
        MySetContents(amwd->amwd_AudioModeText, "%s \"%s\"", ame->ame_Id, ame->ame_Name);
        if (!clientstate) set(amwd->amwd_MoreButton, MUIA_Disabled, FALSE);
    }

    return 0;
}

ULONG __asm __saveds AudioModesWinDispatcher( 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_AudioModesWin_Update:     return (mUpdate(cl, obj, (APTR)msg));
        case MUIM_AudioModesWin_Print:      return (mPrint(cl, obj, (APTR)msg));
        case MUIM_AudioModesWin_More:       return (mMore(cl, obj, (APTR)msg));
        case MUIM_AudioModesWin_ListChange: return (mListChange(cl, obj, (APTR)msg));
    }

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

void PrintAudioModes( char *filename )
{
    BPTR handle;

    if (handle = HandlePrintStart(filename)) {
        PrintFOneLine(handle, "\n  ModeID    Bits MinFreq  MaxFreq Name\n\n");
        IterateList(PrintCallback, (void *)handle);
    }

    HandlePrintStop();
}

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

