// Copyright (c) 2020 Giorgos Vougioukas
//
// The license can be found in the LICENSE file.

#include "thalia/thalia_plugin.h"
#include "thalia_directsound/audio_streamer_ds.h"
#include "thalia_directsound/audio_streamer_ds_dev.h"

#if defined(_WIN32) && defined(_DEBUG)
#include <vld.h>
#endif

#include "WDL/wdlcstring.h"

int (*THA_GetAudioSystem)();
double (*THA_GetAudioDeviceSamplerate)();
int (*THA_GetAudioDeviceBitDepth)();
int (*THA_GetAudioDeviceOutputChannels)();

HINSTANCE directsound_instance;
static HWND directsound_main_hwnd;

THA_IAudioStreamer *CreateAudioStreamer()
{
  if (THA_GetAudioSystem() == 1)
  {
    return new THA_DirectSound;
  }

  return NULL;
}

THA_AudioStreamerRegister directsound_reg =
{
  &CreateAudioStreamer
};

THA_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new THA_DirectSoundDevice;
}

THA_AudioStreamerDeviceRegister directsound_dev_reg =
{
  &CreateAudioStreamerDevice
};

extern "C"
{
  THA_PLUGIN_EXPORT int THA_PLUGIN_ENTRYPOINT(
    THA_PLUGIN_HINSTANCE instance, THA_PluginInfo *rec)
  {
    directsound_instance = instance;

    if (rec)
    {
      if (rec->caller_version != THA_PLUGIN_VERSION || !rec->GetFunc)
      {
        return 0;
      }

      directsound_main_hwnd = rec->hwnd_main;

      *((void **)&THA_GetAudioSystem) = rec->GetFunc("THA_GetAudioSystem");
      *((void **)&THA_GetAudioDeviceSamplerate) = rec->GetFunc("THA_GetAudioDeviceSamplerate");
      *((void **)&THA_GetAudioDeviceBitDepth) = rec->GetFunc("THA_GetAudioDeviceBitDepth");
      *((void **)&THA_GetAudioDeviceOutputChannels) = rec->GetFunc("THA_GetAudioDeviceOutputChannels");

      if (!rec->Register || !THA_GetAudioSystem || !THA_GetAudioDeviceSamplerate ||
        !THA_GetAudioDeviceBitDepth || ! THA_GetAudioDeviceOutputChannels)
      {
        return 0;
      }

      rec->Register("audio_streamer", &directsound_reg);
      rec->Register("audio_streamer_device", &directsound_dev_reg);

      return 1;
    }
    else
    {
      return 0;
    }
  }
}
