#include "thalia_mp3/mp3_apic.h"
#include "thalia_mp3/mp3_entry_point.h"

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

int ReadMediaTags(WDL_FileRead *fr, WDL_StringKeyedArray<char*> *metadata,
  WDL_INT64 *_fstart, WDL_INT64 *_fend);

bool ExportMetadataImageToTmpFile(const char *srcfn, const char *infostr,
  WDL_FastString *imgfn);

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

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

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

  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;
  }

  WDL_INT64 fstart = 0, fend = m_file->GetSize();
  ReadMediaTags(m_file, &m_metadata, &fstart, &fend);

  WDL_FastString imgfn;
  ExportMetadataImageToTmpFile(m_fn.Get(), m_metadata.Get("ID3:APIC"), &imgfn);

  WDL_FileRead fr(imgfn.Get());
  if (fr.IsOpen())
  {
    m_apic.Resize(fr.GetSize());
    fr.Read(m_apic.Get(), m_apic.GetSize());
  }

  return true;
}

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

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