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

#include "euterpe/euterpe_plugin.h"
#include "euterpe_wasapi/res/resource.h"
#include "euterpe_wasapi/audio_streamer_wasapi.h"
#include "euterpe_wasapi/audio_streamer_wasapi_dev.h"
#include "euterpe_wasapi/audio_streamer_wasapi_prop.h"

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

#include "WDL/wdlcstring.h"

HINSTANCE wasapi_instance;
static HWND wasapi_main_hwnd;

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

RSE_IAudioStreamer *CreateAudioStreamer()
{
  return new RSE_Wasapi;
}

RSE_AudioStreamerRegister wasapi_reg =
{
  &CreateAudioStreamer
};

RSE_IAudioStreamerDevice *CreateAudioStreamerDevice()
{
  return new RSE_WasapiDevice;
}

RSE_AudioStreamerDeviceRegister wasapi_dev_reg =
{
  &CreateAudioStreamerDevice
};

RSE_IAudioStreamerProperties *CreateAudioStreamerProperties()
{
  return new RSE_WasapiProperties;
}

RSE_AudioStreamerPropertiesRegister wasapi_prop_reg =
{
  &CreateAudioStreamerProperties
};

extern "C"
{
  EUTERPE_PLUGIN_EXPORT int EUTERPE_PLUGIN_ENTRYPOINT(
    EUTERPE_PLUGIN_HINSTANCE instance, RSE_PluginInfo *rec)
  {
    wasapi_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");

      wasapi_main_hwnd = rec->hwnd_main;

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

      rec->Register("audio_streamer:WASAPI", &wasapi_reg);
      rec->Register("audio_device:WASAPI", &wasapi_dev_reg);
      rec->Register("audio_properties:WASAPI", &wasapi_prop_reg);

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

#ifndef _WIN32
#include <WDL/swell/swell-dlggen.h>
#include <euterpe_wasapi/res/wasapi.rc_mac_dlg>

#undef BEGIN
#undef END
#include <WDL/swell/swell-menugen.h>
#include <euterpe_wasapi/res/wasapi.rc_mac_menu>
#endif
