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

#include "euterpe/euterpe_plugin.h"
#include "euterpe_ds/audio_streamer_pa_ds.h"
#include "euterpe_ds/audio_streamer_pa_ds_dev.h"
#include "euterpe_ds/audio_streamer_pa_ds_prop.h"

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

#include "WDL/wdlcstring.h"

HINSTANCE directsound_instance;
static HWND directsound_main_hwnd;

double (*GetHardwareSampleRate)();
const char *(*GetSettingsPath)();

RSE_IAudioStreamer *CreateAudioStreamer()
{
  return new RSE_PaDirectSound;
}

RSE_AudioStreamerRegister directsound_reg =
{
  &CreateAudioStreamer
};

RSE_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new RSE_PaDirectSoundDevice;
}

RSE_AudioStreamerDeviceRegister directsound_dev_reg =
{
  &CreateAudioStreamerDevice
};

RSE_IAudioStreamerProperties *CreateAudioStreamerProperties()
{
  return new RSE_PaDirectSoundProperties;
}

RSE_AudioStreamerPropertiesRegister directsound_prop_reg =
{
  &CreateAudioStreamerProperties
};

extern "C"
{
  EUTERPE_PLUGIN_EXPORT int EUTERPE_PLUGIN_ENTRYPOINT(
    EUTERPE_PLUGIN_HINSTANCE instance, RSE_PluginInfo *rec)
  {
    directsound_instance = instance;

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

      *((void **)&GetSettingsPath) = rec->GetFunc("GetClientSettingsPath");
      *((void **)&GetHardwareSampleRate) = rec->GetFunc("GetHardwareSampleRate");

      directsound_main_hwnd = rec->hwnd_main;

      if (!GetHardwareSampleRate || !GetSettingsPath || !rec->Register)
      {
        return 0;
      }

      rec->Register("audio_streamer:DirectSound", &directsound_reg);
      rec->Register("audio_device:DirectSound", &directsound_dev_reg);
      rec->Register("audio_properties:DirectSound", &directsound_prop_reg);

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