/*------------------------------------------------------------------------------
 src/lib/djWidget/labelWidget.cxx

 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

//#define DJ_DBG
#include "djLabelWidget.h"
#include <FL/Fl_Image.H>
#include <FL/fl_draw.h>

namespace dj {

LabelWidget::LabelWidget(const Str & in) :
  _value(in)
{
  sizePolicy(FIXED, FIXED);
  alignPolicy(LEFT, CENTER);
}

void LabelWidget::set(const Str & in)
{
  _value = in;
  layoutUpdate();
}

static const Vec2i _measure(const Str & in, int h)
{
  const StrList lineList = split(in, '\n', true);
  int w = 0;
  for (ConstStrListIt it = lineList; it.isValid(); ++it)
    w = max(ceil(fl_width(it().toAscii())), w);
  return Vec2i(w, lineList.size() * h + (lineList.size() - 1) * 2);
}

const Vec2i LabelWidget::sizeHint() const
{
  fl_font(labelfont(), labelsize());
  
  Vec2i size = _measure(_value.toAscii(), labelsize());
  for (ConstListIt<LabelWidget *> it = _labelGroup; it.isValid(); ++it)
    if (it()->visible())
      size = max(_measure(it()->get(), labelsize()), size);
  
  //return size + layoutWidgetMargin() * 2;
  return size;
}

void LabelWidget::labelGroup(const List<LabelWidget *> & in)
{
  _labelGroup = in;
}

void LabelWidget::draw()
{
  WidgetBase::draw();
  
  fl_font(labelfont(), labelsize());
  fl_color(labelcolor());
  
  const Vec2i size = sizeHint();
  const StrList lineList = split(_value, '\n', true);
  int x = this->x(), y = this->y();
  switch (alignPolicy()[0]) {
    case LEFT: break;
    case CENTER: x += w() / 2 - size.x() / 2; break;
    case RIGHT: break;
  }
  switch (alignPolicy()[1]) {
    case LEFT: break;
    case CENTER: y += h() / 2 - size.y() / 2; break;
    case RIGHT: break;
  }
    
  for (ConstStrListIt it = lineList; it.isValid(); ++it) {
    fl_draw(it().toAscii(), x, y + labelsize() - fl_descent());
    y += labelsize() + 2;
  }
}

ImageLabelWidget::ImageLabelWidget(Fl_Image * in) :
  _value(in)
{
  sizePolicy(STRETCH, STRETCH);
  alignPolicy(CENTER, CENTER);
}

void ImageLabelWidget::set(Fl_Image * in)
{
  _value = in;
  layoutUpdate();
}

const Vec2i ImageLabelWidget::sizeHint() const
{
  return _value ? Vec2i(_value->w(), _value->h()) : Vec2i();
}

void ImageLabelWidget::draw()
{
  WidgetBase::draw();
  
  if (_value)
    _value->draw(x() + (w() - _value->w()) / 2, y() + (h() - _value->h()) / 2);
}

}
