/***************************************************************************
**
**  This file is part of SciFigs.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2004-12-01
**  Copyright: 2004-2019
**    Marc Wathelet
**    Marc Wathelet (ULg, Liège, Belgium)
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include "LegendItemWidget.h"
#include "SciFigsGlobal.h"

namespace SciFigs {

LegendItemDisplay::LegendItemDisplay()
{
  TRACE;
  _displayText=true;
}

LegendItemDisplay::LegendItemDisplay(const LegendItem& o)
  : LegendItem(o)
{
  TRACE;
  _displayText=true;
}

QSize LegendItemDisplay::sizeHint (const QFont& font) const
{
  TRACE;
  int spw=_pen.screenWidth(SciFigsGlobal::screenResolution())+8;
  if(_displayText) {
    QFontMetrics f(font);
    QRect r=f.boundingRect(0,0,INT_MAX,INT_MAX, Qt::AlignLeft | Qt::AlignTop,_text);
    QSize s;
    if(spw>r.height())
      s.setHeight(spw);
    else
      s.setHeight(r.height());
    s.setWidth(r.width()+25);
    return s;
  }
  else return QSize(25,spw);
}

void LegendItemDisplay::paint(QPainter& p, double dotpercm, int x, int y, int w, int h) const
{
  TRACE;
  p.fillRect(x, y, w, h, Qt::white);
  int lim=w;
  if(_displayText) {
    QRect r=p.boundingRect(0,0,INT_MAX,h,Qt::AlignLeft | Qt::AlignVCenter,_text);
    lim-=r.width();
    if(lim<1.4*dotpercm) lim=(int)floor(1.4*dotpercm+0.5);
    r.translate(lim,0);
    p.setBrush(_textColor);
    p.drawText(r, Qt::AlignLeft | Qt::AlignVCenter, _text);
  }
  p.setPen(_pen.qpen(dotpercm));
  int yc=y+(h >> 1);
  p.drawLine(x, yc, x+lim, yc);
  _symbol.paint(p, QPointF(x+(lim >> 1), yc));
}

LegendItemWidget::LegendItemWidget(QWidget *parent) :
    GraphicObject(parent)
{
  TRACE;
}

void LegendItemWidget::paintEvent(QPaintEvent * )
{
  TRACE;
  QPainter p(this);
  p.setFont(font());
  LegendItemDisplay::paint(p, SciFigsGlobal::screenResolution(), 0, 0, width(), height());
}

void LegendItemWidget::paint(QPainter& p, double dotpercm, int w, int h, bool)
{
  TRACE;
  p.setFont(font());
  LegendItemDisplay::paint(p, dotpercm, 0, 0, w, h);
}

} // namespace SciFigs
