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

#include "RSI/rsi_plugin.h"
#include "rsi_directsound/audio_streamer_ds.h"
#include "rsi_directsound/audio_streamer_ds_dev.h"

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

#include "WDL/wdlcstring.h"

int (*RSI_GetAudioSystem)();
double (*RSI_GetAudioDeviceSamplerate)();
int (*RSI_GetAudioDeviceBitDepth)();
int (*RSI_GetAudioDeviceOutputChannels)();

HINSTANCE directsound_instance;
static HWND directsound_main_hwnd;

RSI_IAudioStreamer *CreateAudioStreamer()
{
  if (RSI_GetAudioSystem() == 1)
  {
    return new RSI_DirectSound;
  }

  return NULL;
}

RSI_AudioStreamerRegister directsound_reg =
{
  &CreateAudioStreamer
};

RSI_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new RSI_DirectSoundDevice;
}

RSI_AudioStreamerDeviceRegister directsound_dev_reg =
{
  &CreateAudioStreamerDevice
};

extern "C"
{
  RSI_PLUGIN_EXPORT int RSI_PLUGIN_ENTRYPOINT(
    RSI_PLUGIN_HINSTANCE instance, RSI_PluginInfo *rec)
  {
    directsound_instance = instance;

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

      directsound_main_hwnd = rec->hwnd_main;

      *((void **)&RSI_GetAudioSystem) = rec->GetFunc("RSI_GetAudioSystem");
      *((void **)&RSI_GetAudioDeviceSamplerate) = rec->GetFunc("RSI_GetAudioDeviceSamplerate");
      *((void **)&RSI_GetAudioDeviceBitDepth) = rec->GetFunc("RSI_GetAudioDeviceBitDepth");
      *((void **)&RSI_GetAudioDeviceOutputChannels) = rec->GetFunc("RSI_GetAudioDeviceOutputChannels");

      if (!rec->Register || !RSI_GetAudioSystem || !RSI_GetAudioDeviceSamplerate ||
        !RSI_GetAudioDeviceBitDepth || ! RSI_GetAudioDeviceOutputChannels)
      {
        return 0;
      }

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

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