#include "rsi_mp3/mp3_tag.h"
#include "rsi_mp3/mp3_entry_point.h"

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

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

RSI_Mp3Tag::~RSI_Mp3Tag()
{
  if (m_file) delete m_file;
  m_metadata.DeleteAll();
}

bool RSI_Mp3Tag::Open(const char *filename)
{
  m_fn.Set(filename);

  int rmode, rbufsize, rnbufs;
  RSI_GetDiskReadMode(&rmode, &rbufsize, &rnbufs);
  m_file = new WDL_FileRead(filename, rmode, rbufsize, rnbufs);

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

  WDL_INT64 fstart = 0, fend = m_file->GetSize();
  if (ReadMediaTags(m_file, &m_metadata, &fstart, &fend))
  {
    //WDL_FastString ss;
    //for (int i = 0; i < m_metadata.GetSize(); i++)
    //{
    //  char **key = 0;
    //  ss.AppendFormatted(512, "%s %s\n",
    //    m_metadata.ReverseLookup(m_metadata.Enumerate(i)),
    //    m_metadata.Enumerate(i));
    //}

    //MessageBox(NULL, ss.Get(), "", MB_OK);

    return true;
  }

  m_file->SetPosition(0);

  return false;
}

const char *RSI_Mp3Tag::GetType() const
{
  return "MP3";
}

const char *RSI_Mp3Tag::GetTitle() const
{
  if (strcmp(m_metadata.Get("ID3:TIT2", ""), ""))
  {
    return m_metadata.Get("ID3:TIT2", "");
  }
  return m_fn.get_filepart();
}

const char *RSI_Mp3Tag::GetArtist() const
{
  return m_metadata.Get("ID3:TPE1", "");
}

const char *RSI_Mp3Tag::GetAlbum() const
{
  return m_metadata.Get("ID3:TALB", "");
}

const char *RSI_Mp3Tag::GetGenre() const
{
  return m_metadata.Get("ID3:TCON", "");
}

const char *RSI_Mp3Tag::GetTrack() const
{
  return m_metadata.Get("ID3:TRCK", "");
}

const char *RSI_Mp3Tag::GetYear() const
{
  return m_metadata.Get("ID3:TYER", "");
}

const char *RSI_Mp3Tag::GetComment() const
{
  return m_metadata.Get("ID3:COMM", "");
}

WDL_INT64 RSI_Mp3Tag::GetFileSize() const
{
  return m_file->GetSize();
}

const char *RSI_Mp3Tag::GetFileName() const
{
  return m_fn.get_filepart();
}

const char *RSI_Mp3Tag::GetFilePath() const
{
  return m_fn.Get();
}

const char *RSI_Mp3Tag::GetFileExtension() const
{
  return m_fn.get_fileext();
}
