/* dpnet.dll
 *
 * Copyright 2003 TransGaming Technologies
 *
 * David Hammerton (david@transgaming.com)
 */

#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "winreg.h"
#include "objbase.h"
#include "wine/debug.h"
#include "winerror.h"
#include "winnt.h"
#include "winuser.h"

#include "dplay8.h"
#include "dpaddr.h"
#include "dplay8_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(dplay);

WCHAR *pHostNameUserInput = NULL;
HANDLE hHostNameUserInputMutex;
HINSTANCE hinstDpnet;

HRESULT DPNET_HostNameDialogInit(HINSTANCE hinstDLL)
{
    pHostNameUserInput = NULL;
    hinstDpnet = hinstDLL;
    hHostNameUserInputMutex = CreateMutexA(NULL, FALSE, "DPNET HostNameUserInputMutex");
    return TRUE;
}

HRESULT DPNET_HostNameDialogUninit()
{
    CloseHandle(hHostNameUserInputMutex);
    return TRUE;
}

BOOL WINAPI DPNET_HostNameDlgProc(HWND hwnd, UINT msg, WPARAM wParam,
                                  LPARAM lParam)
{
    switch (msg)
    {
    case WM_COMMAND:
        switch LOWORD(wParam)
        {
        case IDOK:
        {
            int textlen;
            textlen = GetWindowTextLengthW(GetDlgItem(hwnd, 701)) + 1;
            pHostNameUserInput = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * textlen);
            GetWindowTextW(GetDlgItem(hwnd, 701), pHostNameUserInput,
                           textlen);
            EndDialog(hwnd, wParam);
            return TRUE;
        }
        case IDCANCEL:
            EndDialog(hwnd, wParam);
            return TRUE;
        }
    }
    return FALSE;
}

/* FIXME: maybe we should return a DirectPlay8Address ? */
HRESULT DPNET_HostNameShowDialog(PWCHAR *ppUserInput)
{
    int hostnamebytelen;
    HINSTANCE hinstDpnet2 = LoadLibraryA("DPNET");

    TRACE("(%p)\n", ppUserInput);

    WaitForSingleObject(hHostNameUserInputMutex, INFINITE);
    DialogBoxA(hinstDpnet2, "HOSTNAME", 0, DPNET_HostNameDlgProc);

    if (!pHostNameUserInput && !lstrlenW(pHostNameUserInput))
    {
        TRACE("returning fail\n");
        return E_FAIL;
    }
    hostnamebytelen = (lstrlenW(pHostNameUserInput)+1) * sizeof(WCHAR);
    *ppUserInput = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, hostnamebytelen);
    memcpy(*ppUserInput, pHostNameUserInput, hostnamebytelen);
    HeapFree(GetProcessHeap(), 0, pHostNameUserInput);

    ReleaseMutex(hHostNameUserInputMutex);
    return S_OK;
}

HRESULT DPNET_HostNameFree(PWCHAR pUserInput)
{
    HeapFree(GetProcessHeap(), 0, pUserInput);
    return S_OK;
}

