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

#include "shared.hpp"
#include "qastools_config.hpp"
#include <QFileInfo>

namespace Tray
{

Shared::Shared ( QObject * parent_n )
: QObject ( parent_n )
{
  icon_names.volume_muted = QStringLiteral ( "audio-volume-muted" );
  icon_names.volume_low = QStringLiteral ( "audio-volume-low" );
  icon_names.volume_medium = QStringLiteral ( "audio-volume-medium" );
  icon_names.volume_high = QStringLiteral ( "audio-volume-high" );

  volume.icon_name = icon_names.volume_low;

  l10n_strings.volume_percent_mask = tr ( "Volume is at %1 %" );
  l10n_strings.volume_change = tr ( "Volume change" );
  l10n_strings.muted = tr ( "Muted" );

  application_title = QStringLiteral ( PROGRAM_TITLE );

  // Init icons
  {
    QIcon icon_def;
    {
      QString def_theme_name;
      if ( QString icon_name ( "multimedia-volume-control" );
           QIcon::hasThemeIcon ( icon_name ) ) {
        def_theme_name = icon_name;
      } else if ( QString icon_name ( icon_names.volume_high );
                  QIcon::hasThemeIcon ( icon_name ) ) {
        def_theme_name = icon_name;
      }

      if ( !def_theme_name.isEmpty () ) {
        icon_def = QIcon::fromTheme ( def_theme_name );
      } else {
        // Use application icon
        QString icon_path ( INSTALL_DIR_ICONS_SVG );
        icon_path += "/";
        icon_path += PROGRAM_NAME;
        icon_path += ".svg";

        QFileInfo finfo ( icon_path );
        if ( finfo.exists () && finfo.isReadable () ) {
          icon_def = QIcon ( icon_path );
        }
      }
    }

    // Fil with default icon
    volume_icons.fill ( icon_def );

    // Volume level icons
    volume_icons[ ICI_VOLUME_LOW ] =
        QIcon::fromTheme ( icon_names.volume_low, icon_def );
    volume_icons[ ICI_VOLUME_MEDIUM ] =
        QIcon::fromTheme ( icon_names.volume_medium, icon_def );
    volume_icons[ ICI_VOLUME_HIGH ] =
        QIcon::fromTheme ( icon_names.volume_high, icon_def );

    // Default and muted
    volume_icons[ ICI_MUTED ] = QIcon::fromTheme (
        icon_names.volume_muted, volume_icons[ ICI_VOLUME_LOW ] );
  }
}

Shared::~Shared () = default;

void
Shared::update_volume_icon ()
{
  if ( volume.muted ) {
    volume.icon_index = ICI_MUTED;
    volume.icon_name = icon_names.volume_muted;
  } else {
    if ( volume.permille < 250 ) {
      volume.icon_index = ICI_VOLUME_LOW;
      volume.icon_name = icon_names.volume_low;
    } else if ( volume.permille < 750 ) {
      volume.icon_index = ICI_VOLUME_MEDIUM;
      volume.icon_name = icon_names.volume_medium;
    } else {
      volume.icon_index = ICI_VOLUME_HIGH;
      volume.icon_name = icon_names.volume_high;
    }
  }
}

} // namespace Tray
