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

#include "RSI/rsi_plugin.h"
#include "rsi_waveout/audio_streamer_waveout.h"
#include "rsi_waveout/audio_streamer_waveout_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 waveout_instance;
static HWND waveout_main_hwnd;

RSI_IAudioStreamer *CreateAudioStreamer()
{
  if (RSI_GetAudioSystem() == 0)
  {
    return new RSI_WaveOut;
  }

  return NULL;
}

RSI_AudioStreamerRegister waveout_reg =
{
  &CreateAudioStreamer
};

RSI_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new RSI_WaveOutDevice;
}

RSI_AudioStreamerDeviceRegister waveout_dev_reg =
{
  &CreateAudioStreamerDevice
};

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

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

      waveout_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", &waveout_reg);
      rec->Register("audio_streamer_device", &waveout_dev_reg);

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