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

#include "thalia/thalia_plugin.h"
#include "thalia_wasapi/audio_streamer_wasapi.h"
#include "thalia_wasapi/audio_streamer_wasapi_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)();
bool (*THA_GetWASAPIExclusiveMode)();

HINSTANCE wasapi_instance;
static HWND wasapi_main_hwnd;

THA_IAudioStreamer *CreateAudioStreamer()
{
  if (THA_GetAudioSystem() == 2)
  {
    return new THA_Wasapi;
  }

  return NULL;
}

THA_AudioStreamerRegister wasapi_reg =
{
  &CreateAudioStreamer
};

THA_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new THA_WasapiDevice;
}

THA_AudioStreamerDeviceRegister wasapi_dev_reg =
{
  &CreateAudioStreamerDevice
};

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

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

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

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

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

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