/// QasTools: Desktop toolset for the Linux sound system ALSA.
/// \copyright See COPYING file.

#pragma once

#include "utility/setup.hpp"
#include <QByteArray>
#include <QHash>
#include <QString>
#include <memory>

// Forward declaration
namespace QSnd
{
class Cards_Db;
class Ctl_Address;
} // namespace QSnd
namespace MState::Mixer
{
class State;
}

namespace MState::Mixer
{

/// @brief States
///
class States_Db : public Utility::Setup
{
  public:
  // -- Construction

  States_Db ( QSnd::Cards_Db * cards_db_n );

  ~States_Db ();

  // -- Cards database

  QSnd::Cards_Db *
  cards_db () const
  {
    return _cards_db;
  }

  // -- State

  /// @brief Returns the state for the given control address
  ///
  /// A new state with default settings is created if none
  /// has been found in the database for the given address.
  const std::shared_ptr< Mixer::State > &
  state ( const QSnd::Ctl_Address & addr_n );

  // -- Storage

  /// @brief Returns true if changes were made since the last
  ///        read_from_storage () or write_to_storage ()
  bool
  differs_from_storage () const
  {
    return ( _storage_change_id != change_id () );
  }

  /// @brief Read the database from the storage (file)
  void
  read_from_storage ();

  /// @brief Write the database to the storage (file)
  void
  write_to_storage ();

  private:
  // -- Utility

  QByteArray
  read_config_file () const;

  void
  add_state ( const QString & key_n,
              const std::shared_ptr< Mixer::State > & state_n );

  private:
  // -- Attributes
  QString _config_file;
  QSnd::Cards_Db * _cards_db = nullptr;
  QHash< QString, std::shared_ptr< Mixer::State > > _states;
  std::shared_ptr< Mixer::State > _empty_state;
  std::size_t _storage_change_id = 0;
};

} // namespace MState::Mixer
