// 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_EUTERPE_FLAC_CONSOLE

#include "euterpe/euterpe_plugin.h"
#include "euterpe_mp3/mp3_input.h"

#include "WDL/wdlcstring.h"

static HINSTANCE mp3_instance;
static HWND mp3_main_hwnd;

RSE_IFileInput *CreateFromType(const char *type)
{
  if (!strcmp(type, "MP3"))
  {
    return new RSE_Mp3Input;
  }

  return NULL;
}

RSE_IFileInput *CreateFromFile(const char *filename)
{
  if (!wdl_filename_cmp(WDL_get_fileext(filename), ".mp3"))
  {
    RSE_Mp3Input *p = new RSE_Mp3Input;

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

    delete p;
  }

  return NULL;
}

struct RSE_AudioInputRegister mp3_reg_struct =
{
  CreateFromType,
  CreateFromFile,
};

extern "C"
{
  EUTERPE_PLUGIN_EXPORT int EUTERPE_PLUGIN_ENTRYPOINT(
    EUTERPE_PLUGIN_HINSTANCE instance, RSE_PluginInfo *rec)
  {
#if defined(_WIN32) && defined(_DEBUG) && defined(ENABLE_EUTERPE_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

    mp3_instance = instance;

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

      mp3_main_hwnd = rec->hwnd_main;

      if (!rec->Register)   // Add more checks in the future...
      {
        return 0;
      }

      rec->Register("pcmsrc", &mp3_reg_struct);

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