/* 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 "Loveletter.h"
#include "LoveletterMovie.h"

namespace Blinker {

/**
 * @brief constructor
 * @param[in] loveletter owning loveletter module
 * @param[in] name name of movie
 * @param[in] file movie file
 */
Loveletter::Movie::Movie(Loveletter &loveletter, const std::string &name,
                         const File &file):
  m_loveletter(loveletter),
  m_name(name),
  m_file(file),
  m_addedToMap(false),
  m_pMovie(NULL)
{
  // add movie to map
  name2number(m_name, m_number);
  if (m_loveletter.m_movieMap.find(m_number) ==
      m_loveletter.m_movieMap.end()) {
    m_loveletter.m_movieMap[m_number] = this;
    m_addedToMap = true;
  }

  // load movie
  load();
}

/// destructor
Loveletter::Movie::~Movie()
{
  // check if this is the current movie
  if (m_loveletter.m_pCurMovie == this) {
    // select no movie
    m_loveletter.m_pCurMovie = NULL;
    m_loveletter.m_curChange = true;
  }

  // free movie
  free();

  // remove movie from map
  if (m_addedToMap)
    m_loveletter.m_movieMap.erase(m_number);
}

/// check for update of configuration
void Loveletter::Movie::updateConfig()
{
  // movie file was modified
  if (m_file.checkModified()) {
    // load new movie
    load();
    // if this is the current movie, remember that it changed
    if (m_loveletter.m_pCurMovie == this)
      m_loveletter.m_curChange = true;
  }
}

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

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

/**
 * @brief convert movie name to movie number
 * @param[in] name movie name
 * @param[out] number movie number (name without all non-digits)
 */
void Loveletter::Movie::name2number(const std::string &name,
                                    std::string &number)
{
  number.clear();
  for (std::string::const_iterator pos = name.begin();
       pos != name.end(); ++pos)
    if (*pos >= '0' && *pos <= '9')
      number += *pos;
}

} // namespace Blinker

