#include "thalia_flac/flac_apic.h"
#include "thalia_flac/flac_entry_point.h"

extern "C"
{
  #include <FLAC/all.h>
}

#include "WDL/wdl_base64.h"
#include "WDL/wdlutf8.h"

THA_FlacAPIC::THA_FlacAPIC()
  : m_file(NULL)
  , m_metadata(false, WDL_StringKeyedArray<char *>::freecharptr)
{}

THA_FlacAPIC::~THA_FlacAPIC()
{
  if (m_file) delete m_file;
}

bool THA_FlacAPIC::Open(const char *filename)
{
  WDL_ASSERT(filename != NULL);

  bool res = false;
  m_fn.Set(filename);

  //int rmode, rbufsize, rnbufs;
  //THA_GetDiskReadMode(&rmode, &rbufsize, &rnbufs);
  //m_file = new WDL_NEW WDL_FileRead(filename, rmode, rbufsize, rnbufs);

  //if (!m_file || !m_file->IsOpen())
  //{
  //  return false;
  //}

#ifdef _WIN32
  flac_internal_set_utf8_filenames(true);
#endif

  FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
  if (FLAC__metadata_chain_read(chain, m_fn.Get()))
  {
    FLAC__Metadata_Iterator *it = FLAC__metadata_iterator_new();
    FLAC__metadata_iterator_init(it, chain);

    WDL_FastString ss;
    while (FLAC__metadata_iterator_next(it))
    {
      FLAC__StreamMetadata *meta = FLAC__metadata_iterator_get_block(it);
      if (meta->type == FLAC__METADATA_TYPE_PICTURE)
      {
        m_apic.Resize(meta->data.picture.data_length);
        memcpy(m_apic.Get(), meta->data.picture.data,
          meta->data.picture.data_length);
      }
    }
    FLAC__metadata_iterator_delete(it); res = true;
  }

  FLAC__metadata_chain_delete(chain);

  return res;
}

int THA_FlacAPIC::GetPicSize() const
{
  return m_apic.GetSize();
}

void *THA_FlacAPIC::GetPic() const
{
  return m_apic.Get();
}
