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

#include "label_styled.hpp"
#include "wdg/style_db.hpp"
#include <QPainter>

namespace Wdg
{

Label_Styled::Label_Styled ( const Wdg::Style_Db * style_db_n,
                             QWidget * parent_n )
: QWidget ( parent_n )
, _style_db ( style_db_n )
{
  connect ( _style_db,
            &Wdg::Style_Db::sig_palette_changed,
            this,
            &Label_Styled::style_palette_changed );
}

Label_Styled::~Label_Styled () = default;

QSize
Label_Styled::minimumSizeHint () const
{
  // The offset is to fix a too small bounding rect.
  const int offset = 2;
  QSize res ( fontMetrics ().boundingRect ( text () ).width () + offset,
              fontMetrics ().height () );
  {
    const QMargins mgs = contentsMargins ();
    res.rwidth () += mgs.left ();
    res.rwidth () += mgs.right ();
    res.rheight () += mgs.top ();
    res.rheight () += mgs.bottom ();
  }
  return res;
}

QSize
Label_Styled::sizeHint () const
{
  // The offset is to fix a too small bounding rect.
  const int offset = 2;
  QSize res ( fontMetrics ().boundingRect ( text () ).width () + offset,
              fontMetrics ().height () );
  {
    const QMargins mgs = contentsMargins ();
    res.rwidth () += mgs.left ();
    res.rwidth () += mgs.right ();
    res.rheight () += mgs.top ();
    res.rheight () += mgs.bottom ();
  }
  return res;
}

void
Label_Styled::set_style_id ( unsigned int id_n )
{
  if ( _style_id != id_n ) {
    _style_id = id_n;
    update ();
  }
}

void
Label_Styled::setText ( const QString txt_n )
{
  if ( txt_n != _text ) {
    _text = txt_n;
    updateGeometry ();
    update ();
  }
}

void
Label_Styled::setAlignment ( Qt::Alignment align_n )
{
  if ( align_n != _alignment ) {
    _alignment = align_n;
    update ();
  }
}

void
Label_Styled::style_palette_changed ( unsigned int style_id_n )
{
  if ( _style_id == style_id_n ) {
    update ();
  }
}

void
Label_Styled::resizeEvent ( QResizeEvent * event_n )
{
  QWidget::resizeEvent ( event_n );
  update ();
}

void
Label_Styled::paintEvent ( QPaintEvent * event_n )
{
  QWidget::paintEvent ( event_n );
  {
    QPainter painter ( this );
    painter.setRenderHints ( QPainter::Antialiasing |
                             QPainter::TextAntialiasing |
                             QPainter::SmoothPixmapTransform );
    {
      QPen pen ( painter.pen () );
      pen.setColor (
          _style_db->palette ( _style_id ).color ( QPalette::WindowText ) );
      painter.setPen ( pen );
    }
    painter.drawText ( contentsRect (), _alignment, _text );
  }
}

} // namespace Wdg
