#include "thalia_vorbis/vorbis_apic.h"
#include "thalia_vorbis/vorbis_entry_point.h"

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

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

THA_VorbisAPIC::~THA_VorbisAPIC()
{
  ov_clear(&m_vf);
  if (m_file) delete m_file;
}

bool THA_VorbisAPIC::Open(const char *filename)
{
  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;
  //}

  FILE *file = fopen(m_fn.Get(), "rb");
  if (ov_open_callbacks(file, &m_vf, NULL, 0, OV_CALLBACKS_NOCLOSE) < 0)
  {
    fclose(file);
    return false;
  }

  vorbis_comment *vc = m_vf.vc;

  if (vc)
  {
    for (int i = 0; i < vc->comments; i++)
    {
      if (!strnicmp(m_strbuf.Get(), "METADATA_BLOCK_PICTURE=", 23))
      {
        // Do nothing. Need to properly read METADATA_BLOCK_PICTURE
        //m_strbuf.DeleteSub(0, 23);
        //m_apic.Resize(m_strbuf.GetLength());
        //int sz = wdl_base64decode(m_strbuf.Get(),
        //  (unsigned char *)m_apic.Get(), m_apic.GetSize());
        //m_apic.Resize(sz);
      }
    }
  }

  fclose(file);
  return true;
}

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

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