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

#include "RSI/rsi_plugin.h"
#include "rsi_wasapi/audio_streamer_wasapi.h"
#include "rsi_wasapi/audio_streamer_wasapi_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)();
bool (*RSI_GetWASAPIExclusiveMode)();

HINSTANCE wasapi_instance;
static HWND wasapi_main_hwnd;

RSI_IAudioStreamer *CreateAudioStreamer()
{
  if (RSI_GetAudioSystem() == 2)
  {
    return new RSI_Wasapi;
  }

  return NULL;
}

RSI_AudioStreamerRegister wasapi_reg =
{
  &CreateAudioStreamer
};

RSI_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new RSI_WasapiDevice;
}

RSI_AudioStreamerDeviceRegister wasapi_dev_reg =
{
  &CreateAudioStreamerDevice
};

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

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

      wasapi_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");
      *((void **)&RSI_GetWASAPIExclusiveMode) = rec->GetFunc("RSI_GetWASAPIExclusiveMode");

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

      rec->Register("audio_streamer", &wasapi_reg);
      rec->Register("audio_streamer_device", &wasapi_dev_reg);

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