/*
 * audio_playlist.c: The audio playlist manager implementation
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: audio_playlist.c,v 1.6 2005/10/26 19:04:53 cm Exp $
 */

#include <stdlib.h>
#include "audio_playlist.h"

// --- cAudioTune --------------------------------------------------------------

cAudioTune::cAudioTune() {
}

cAudioTune::~cAudioTune() {
}

// --- cAudioPlaylist ----------------------------------------------------------

cAudioPlaylist::cAudioPlaylist() :
  m_lock(false), m_currentItem(-1) {
}

cAudioPlaylist::~cAudioPlaylist() {
}

// --- cAudioTunePreloader -----------------------------------------------------

cAudioTunePreloader::cAudioTunePreloader() : cThread("DAAP TunePreloader"),
  m_ready(false), m_numOfGets(0), mpo_tune(NULL), mpo_blob(NULL) {
  Start();
}

cAudioTunePreloader::~cAudioTunePreloader() {
  Clear();

  Cancel(2);
}

void cAudioTunePreloader::Action(void) {
#ifdef DEBUG
  printf("%.16s (%d) starting preloader\n", __FILE__, __LINE__);
#endif

  while (Running()) {
    if (NULL != mpo_tune && ! m_ready) {
      LOCK_THREAD;

      mpo_blob = mpo_tune->GetData();

      // m_ready _must_ be set true, even when we cannot recieve any data
      // otherwise the player will not skip the song
      m_ready = true;
    } else
      cCondWait::SleepMs(500);
  }

#ifdef DEBUG
  printf("%.16s (%d) stopping preloader\n", __FILE__, __LINE__);
#endif
}

void cAudioTunePreloader::Clear(void) {
  LOCK_THREAD;

  m_ready = false;
  mpo_tune = NULL;

  if (0 == m_numOfGets && NULL != mpo_blob)
    delete mpo_blob;
  else
    m_numOfGets = 0;

  mpo_blob = NULL;
}

void cAudioTunePreloader::SetItem(cAudioTune *tune) {
  Clear();

  mpo_tune = tune;
}

const cMediaDatabaseBlob *cAudioTunePreloader::GetData() {
  LOCK_THREAD;

  if (m_ready && NULL != mpo_blob) {
    m_numOfGets++;

    return mpo_blob;
  }

  return NULL;
}
