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

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

//#define ENABLE_RSI_FLAC_CONSOLE

#include "RSI/rsi_plugin_public.h"
#include "rsi_flac/flac_input.h"
#include "rsi_flac/flac_tag.h"

#include "WDL/wdlcstring.h"

double (*RSI_GetAudioDeviceSamplerate)();
void (*RSI_GetDiskReadMode)(int *rmode, int *rbufsize, int *rnbufs);
void (*RSI_GetResampleMode)(bool *interp, int *filtercnt,
  bool *sinc, int *sinc_size, int *sinc_interpsize);

static HINSTANCE flac_instance;
static HWND flac_main_hwnd;

RSI_IFileInput *CreateFromType(const char *type)
{
  if (!strcmp(type, "FLAC"))
  {
    return new RSI_FlacInput;
  }

  return NULL;
}

RSI_IFileInput *CreateFromFile(const char *filename)
{
  if (!wdl_filename_cmp(WDL_get_fileext(filename), ".flac"))
  {
    RSI_FlacInput *p = new RSI_FlacInput;

    if (p->Open(filename))
    {
      return p;
    }

    delete p;
  }

  return NULL;
}

struct RSI_FileInputRegister flac_input_reg =
{
  CreateFromType,
  CreateFromFile,
};

RSI_IFileTag *CreateFlacTag(const char *filename)
{
  if (!wdl_filename_cmp(WDL_get_fileext(filename), ".flac"))
  {
    RSI_FlacTag *p = new RSI_FlacTag;

    if (p && p->Open(filename))
    {
      return p;
    }
    else
    {
      delete p;
    }
  }

  return NULL;
}

RSI_FileTagRegister flac_tag_reg =
{
  &CreateFlacTag
};

extern "C"
{
  RSI_PLUGIN_EXPORT int RSI_PLUGIN_ENTRYPOINT(
    RSI_PLUGIN_HINSTANCE instance, RSI_PluginInfo *rec)
  {
#if defined(_WIN32) && defined(_DEBUG) && defined(ENABLE_RSI_FLAC_CONSOLE)
    // The first will use the console only if
    // the application is started by the command 
    // line. The second one will always enable
    // the console.
    //if (AttachConsole(ATTACH_PARENT_PROCESS))
    if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())
    {
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
#endif

    flac_instance = instance;

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

      flac_main_hwnd = rec->hwnd_main;

      *((void **)&RSI_GetAudioDeviceSamplerate) = rec->GetFunc("RSI_GetAudioDeviceSamplerate");
      *((void **)&RSI_GetDiskReadMode) = rec->GetFunc("RSI_GetDiskReadMode");
      *((void **)&RSI_GetResampleMode) = rec->GetFunc("RSI_GetResampleMode");

      if (!rec->Register || !RSI_GetAudioDeviceSamplerate || !RSI_GetDiskReadMode ||
        !RSI_GetResampleMode)
      {
        return 0;
      }

      rec->Register("input", &flac_input_reg);
      rec->Register("tag", &flac_tag_reg);

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