////////////////////////////////////////////////////////////////////////////////
// Main.cpp
//
//  Main program logic.

#include "stdhdr.h"

#include "ddutil.h"
#include "Debug.h"
#include "Sound.h"
#include "Input.h"
#include "Draw.h"
#include "Window.h"

////////////////////////////////////////////////////////////////////////////////
// DirectX Audio

IDirectMusicSegment8    *g_pBackgroundMusic;
bool                    g_bMusicPlaying, g_bFinishedInit;
bool                    g_bMusicEnabled;

////////////////////////////////////////////////////////////////////////////////
// DirectInput

// {BD0E8406-FB56-4322-8BC6-BD6E481F5564}
GUID g_guidApp = 
{ 0xbd0e8406, 0xfb56, 0x4322, { 0x8b, 0xc6, 0xbd, 0x6e, 0x48, 0x1f, 0x55, 0x64 } };
DWORD   g_dwGenre = DIVIRTUAL_ARCADE_SIDE2SIDE;
LPCTSTR g_tszActionMapName = _T("Sample");

enum Actions 
{
    ACTIONS_LEFTRIGHT,
    ACTIONS_LEFT,
    ACTIONS_RIGHT,
    ACTIONS_QUIT,
    ACTIONS_NONE
};

bool    g_bQuit;
bool    g_bLeft, g_bRight;

DIACTION g_rgActions[] =
{
    // Genre-defined virtual axes
    { ACTIONS_LEFTRIGHT,    DIAXIS_ARCADES_LATERAL,         0, "Left/Right" },

    // Actions mapped to keys as well as to virtual controls
    { ACTIONS_LEFT,         DIKEYBOARD_LEFT,                0, "Left" },
    { ACTIONS_RIGHT,        DIKEYBOARD_RIGHT,               0, "Right" },

    // Actions mapped to keys
    { ACTIONS_QUIT,         DIKEYBOARD_ESCAPE,              0, "Quit" },
};

DWORD g_nActions = sizeof(g_rgActions) / sizeof(DIACTION);

////////////////////////////////////////////////////////////////////////////////
// DirectDraw

// Surface containing our background.
IDirectDrawSurface7 *lpA;
// Surface containing our sprites.
IDirectDrawSurface7 *lpSprites;

void ReloadAllSurfaces()
{
    DDReLoadBitmap(lpA, "a.bmp");
    DDReLoadBitmap(lpSprites, "sprites.bmp");
}

////////////////////////////////////////////////////////////////////////////////
// Music handling

void PlayBackgroundMusic()
{
    if ((g_pBackgroundMusic != NULL) && !g_bMusicPlaying && g_bFinishedInit && g_bMusicEnabled)
    {
        // Play the background music
        TRACE0("Playing background music...\n");
        g_bMusicPlaying = true;
        PlaySound(g_pBackgroundMusic);
    }
}

void StopBackgroundMusic()
{
    StopAllSound();
    g_bMusicPlaying = false;
}

////////////////////////////////////////////////////////////////////////////////
// Input handling

#define AXIS_THRESHOLD  20

void HandleAction(UINT nAction, DWORD dwData)
{
    int nAxisPos = (int)dwData;

    switch (nAction)
    {
    case ACTIONS_LEFTRIGHT:
        if (nAxisPos < -AXIS_THRESHOLD)
        {
            g_bLeft = true;
            g_bRight = false;
        }
        else if (nAxisPos > AXIS_THRESHOLD)
        {
            g_bRight = true;
            g_bLeft = false;
        }
        else
        {
            g_bLeft = g_bRight = false;
        }
        break;
    
    case ACTIONS_LEFT:
        g_bLeft = (dwData != 0);
        break;

    case ACTIONS_RIGHT:
        g_bRight = (dwData != 0);
        break;

    case ACTIONS_QUIT:
        g_bQuit = true;
        break;
    
    default:
        break;
    }
}

////////////////////////////////////////////////////////////////////////////////
// Idle-time processing function.

void OnIdle(void)
{
    if (g_lpPrimary == NULL)
        return;

    if (!g_bActive)
        return;

    CheckInput();

    if (g_bQuit)
    {
        PostMessage(hWndMain, WM_CLOSE, 0, 0);
        return;
    }

    RECT    r;
    
    // Draw the background to the screen.
    r.left = 0;
    r.top = 0;
    r.right = 640;
    r.bottom = 480;
    BackBlt(0, 0, lpA, &r, 
        DDBLTFAST_NOCOLORKEY | DDBLTFAST_WAIT);

    // Draw a sprite in the middle of the screen.
    r.left = 128;
    r.top = 0;
    r.right = 192;
    r.bottom = 64;
    BackBlt(288, 208, lpSprites, &r, 
        DDBLTFAST_SRCCOLORKEY | DDBLTFAST_WAIT);

    // Move a sprite around automatically.
    static int x;

    x++;
    if (x > 100)
        x = -100;
    
    r.left = 0;
    r.right = 64;
    BackBlt(288 + x, 100, lpSprites, &r, 
        DDBLTFAST_SRCCOLORKEY | DDBLTFAST_WAIT);

    // Move a sprite around with the input.
    static int xSprite;

    if (g_bLeft)
        xSprite--;
    if (g_bRight)
        xSprite++;
    r.left = 64;
    r.right = 128;
    BackBlt(288 + xSprite, 150, lpSprites, &r, 
        DDBLTFAST_SRCCOLORKEY | DDBLTFAST_WAIT); 

    g_lpPrimary->Flip(NULL, DDFLIP_WAIT);
}

////////////////////////////////////////////////////////////////////////////////
// Initialisation and shutdown

BOOL InitApplication(HINSTANCE hInstance)
{
    if (!InitWindow("DirectX Sample Application with tidying"))
        return FALSE;

    if (!InitDirectMusic())
        return FALSE;

    // Load the background music
    g_pBackgroundMusic = LoadSound(L"passport.mid");
    if (g_pBackgroundMusic == NULL)
    {
        ExitDirectMusic();
        DISPLAYERROR("Could not load background music.");
        return FALSE;
    }
    // Standard MIDI file
    g_pBackgroundMusic->SetParam(GUID_StandardMIDIFile, 
        0xFFFFFFFF, DMUS_SEG_ALLTRACKS, 0, NULL);
    // Repeat forever
    g_pBackgroundMusic->SetRepeats(DMUS_SEG_REPEAT_INFINITE);
    // Download it, ready for playback
    DownloadSound(g_pBackgroundMusic);
    g_bMusicEnabled = true;

    if (!InitDirectInput())
    {
        DISPLAYERROR("Failed to initialise DirectInput.");
        ExitDirectMusic();
        return FALSE;
    }

    if (!InitDirectDraw())
    {
        ExitDirectInput();
        ExitDirectMusic();
        return FALSE;
    }

    // Load our background.
    lpA = LoadSurface(_T("a.bmp"));
    if (lpA == NULL)
    {
        ExitDirectDraw();
        
        DISPLAYERROR("Could not load background image.");
        return FALSE;
    }

    // Load the sprites.
    lpSprites = LoadSurface(_T("sprites.bmp"));
    if (lpSprites == NULL)
    {
        ExitDirectDraw();
        
        DISPLAYERROR("Could not load sprites.");
        return FALSE;
    }
    DDSetColorKey(lpSprites, RGB(255, 0, 255));

    AcquireDevices();
    g_bFinishedInit = true;
    return TRUE;
}

void OnClose()
{
    StopBackgroundMusic();

    // Release our sprites surface.
    lpSprites->Release();
    lpSprites = NULL;

    // Release our background surface.
    lpA->Release();
    lpA = NULL;

    ExitDirectDraw();

    UnloadSound(g_pBackgroundMusic);
    g_pBackgroundMusic->Release();
    g_pBackgroundMusic = NULL;
    ExitDirectMusic();

    UnacquireDevices();
    ExitDirectInput();
}

// Program entry point.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) 
{
    if (!InitApplication(hInstance))
        return 1;

    // Play the background music
    PlayBackgroundMusic();

    Run();

    return 0;
}