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

#pragma once

#include "qsnd/ctl_address.hpp"
#include <QModelIndex>
#include <QVBoxLayout>
#include <QWidget>
#include <memory>

// Forward declaration
class QModelIndex;
namespace MWdg
{
class Mixers_View;
class User_Device_Input;
} // namespace MWdg
namespace QSnd
{
class Cards_Db;
class Mixers_Model;
} // namespace QSnd
namespace Views
{
class Device_Selection_View_Setup;
}

class QItemSelection;

namespace Views
{

/// @brief Device_Selection_View
///
/// Mixer device selection view
class Device_Selection_View : public QWidget
{
  Q_OBJECT

  public:
  // -- Construction

  Device_Selection_View ( QSnd::Cards_Db * cards_db_n,
                          QWidget * parent_n = nullptr );

  ~Device_Selection_View ();

  // -- Setup

  void
  set_view_setup ( Views::Device_Selection_View_Setup * setup_n );

  // -- Selected control

  /// @brief Currently selected control address
  const QSnd::Ctl_Address &
  selected_ctl () const
  {
    return _selected_ctl;
  }

  void
  silent_select_ctl ( const QSnd::Ctl_Address & ctl_addr_n );

  Q_SIGNAL
  void
  sig_control_selected ();

  // -- Signals

  Q_SIGNAL
  void
  sig_close ();

  // -- Public slots

  Q_SLOT
  void
  reload_database ();

  protected:
  // -- Layout access

  QVBoxLayout *
  lay_top ()
  {
    return _lay_top;
  }

  QVBoxLayout *
  lay_bottom ()
  {
    return _lay_bottom;
  }

  // -- Event processing

  void
  contextMenuEvent ( QContextMenuEvent * event_n ) override;

  private:
  // -- Private methods

  Q_SLOT
  void
  mixer_selection_changed ( const QItemSelection & selected_n,
                            const QItemSelection & deselected_n );

  QModelIndex
  current_index () const;

  QSnd::Ctl_Address
  acquire_ctl_address () const;

  void
  update_selected_ctl ();

  void
  user_device_input_update ();

  Q_SLOT
  void
  user_device_input_changed ();

  private:
  // -- Attributes
  Views::Device_Selection_View_Setup * _view_setup = nullptr;

  std::unique_ptr< QSnd::Mixers_Model > _mixers_model;
  std::unique_ptr< MWdg::Mixers_View > _mixers_view;
  std::unique_ptr< MWdg::User_Device_Input > _user_device_input;

  // Selection state
  QSnd::Ctl_Address _selected_ctl;
  bool _silent_ctl_change = false;

  // Layout
  QVBoxLayout * _lay_user_device = nullptr;
  QVBoxLayout * _lay_top = nullptr;
  QVBoxLayout * _lay_bottom = nullptr;

  // Context menu
  QAction * _act_close = nullptr;
};

} // namespace Views
