// Copyright (c) 2022 Giorgos Vougioukas
//
// The license can be found in the LICENSE file.

#include "thalia/track.h"
#include "thalia/plugin.h"
#include "thalia/preferences.h"

THA_Track::THA_Track()
  : m_eof(false)
  , m_bqms(1200)
  , m_input(NULL)
  , m_length(0.0)
  , m_nch(0)
  , m_stream(false)
{
  m_bqms = g_preferences->GetMediaBufferSize();
}

THA_Track::~THA_Track()
{
  if (m_input) delete m_input;
}

bool THA_Track::Open(const char *filepath)
{
  WDL_ASSERT(!m_input);

  m_input = CreateFileInput(filepath);

  if (m_input)
  {
    m_length = m_input->GetLength();
    m_nch = m_input->GetChannels();
    m_stream = m_input->IsStreaming();
    return true;
  }

  m_eof = true;
  return false;
}

bool THA_Track::IsDrained() const
{
  return m_eof;
}

bool THA_Track::WantMore() const
{
  if (m_input && !m_eof)
  {
    double srate = THA_GetAudioDeviceSamplerate();
    // duration = filesize / (srate * nch * (bps / 8))
    int duration = (int)(((double)m_bq.GetSize() / (srate * m_nch * sizeof(SAM))) * 1000);
    if (duration < m_bqms) return true;
  }

  return false;
}

bool THA_Track::DoBuffering()
{
  if (m_input && !m_eof)
  {
    m_buffer.Resize(2048 * m_input->GetChannels());
    int nsam = m_input->GetSamples(m_buffer.Get(), m_buffer.GetSize());
    if (nsam > 0)
    {
      m_buffer.Resize(nsam, false);
      m_bq.AddBlock(&m_buffer, m_input->GetPosition());
      return true;
    }
    else m_eof = true;
  }

  return false;
}

bool THA_Track::IsStreaming() const
{
  return m_stream;
}

const char *THA_Track::GetStreamInfo() const
{
  if (m_stream) return m_input->GetFileName();
  return "";
}
