/* Blinker
   Copyright 2011-2019 Stefan Schuermans <stefan@blinkenarea.org>
   Copyleft GNU public license - http://www.gnu.org/copyleft/gpl.html
   a blinkenarea.org project */

#include <string>

#include <BlinkenLib/BlinkenFrame.h>
#include <BlinkenLib/BlinkenMovie.h>

#include "File.h"
#include "Player.h"
#include "PlayerMovie.h"

namespace Blinker {

/**
 * @brief constructor
 * @param[in] player owning player module
 * @param[in] name name of movie
 * @param[in] file movie file
 */
Player::Movie::Movie(Player &player, const std::string &name,
                     const File &file):
  m_player(player),
  m_name(name),
  m_file(file),
  m_pMovie(NULL)
{
  load();
  ifOnlyGoHere();
}

/// destructor
Player::Movie::~Movie()
{
  ifCurGoNext();
  free();
}

/// check for update of configuration
void Player::Movie::updateConfig()
{
  // movie file was modified
  if (m_file.checkModified()) {
    ifCurGoNext();
    load();
    ifOnlyGoHere();
  }
}

/// load movie from current file
void Player::Movie::load()
{
  free();
  m_pMovie = BlinkenMovieLoad(m_file.getPath().c_str());
}

/// free current movie
void Player::Movie::free()
{
  if (m_pMovie) {
    BlinkenMovieFree(m_pMovie);
    m_pMovie = NULL;
  }
}

/// if this is the only movie in playlist go to begin of this movie
void Player::Movie::ifOnlyGoHere()
{
  /* The implementation of ListTracker will first set up the entry and then
     insert it into the list. Thus, we are the only movie if we see an empty
     playlist here. */
  if (m_player.m_playlistTracker.m_list.empty() && m_pMovie) {
    m_player.m_curEntry = m_player.m_playlistTracker.m_list.begin();
    m_player.m_curChange = true;
  }
  /* additional rule in case plalist conatins just broken/empty movies:
   * if current movie is not valid, trigger re-check by setting change flag */
 if (!m_player.m_curValid)
   m_player.m_curChange = true;
}

/// if this is current movie go to begin of next movie
void Player::Movie::ifCurGoNext()
{
  if (m_player.m_curEntry->m_pObj == this) {
    ++m_player.m_curEntry;
    m_player.m_curChange = true;
  }
}

} // namespace Blinker

