/*------------------------------------------------------------------------------
 src/lib/djWidget/djEnumWidget_.h

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

#include <FL/fl_draw.H>
#include <FL/Fl.H>
#include <FL/Fl_Choice.H>

namespace dj {

template <class T>
EnumWidget<T>::EnumWidget(const StrList & in) :
  _value(T(0)),
  _menuList(in)
{
  _widget = new Fl_Choice(0, 0, 0, 0);
  _widget->textfont(dj::font());
  _widget->textsize(dj::fontSize());
  _widget->textcolor(FL_FOREGROUND_COLOR);
  add(_widget);
  
  sizePolicy(FIXED, FIXED);
  widgetUpdate();
  
  _widget->callback(widgetCallback, this);
}

template <class T>
void EnumWidget<T>::set(T in)
{
  _widget->value(int(in));
}

template <class T>
T EnumWidget<T>::get() const
{
  return T(_widget->value());
}

template <class T>
void EnumWidget<T>::menuList(const StrList & in)
{
  _menuList = in;
  widgetUpdate();
}

template <class T>
const Vec2i EnumWidget<T>::sizeHint() const
{
  fl_font(labelfont(), labelsize());
  int itemWidth = 0;
  for (ConstStrListIt it = _menuList; it.isValid(); ++it)
    itemWidth = max(ceil(fl_width(it().toAscii())), itemWidth);
  
  const int buttonWidth = labelsize() + layoutWidgetMargin() * 2;
  return
    Vec2i(max(itemWidth + buttonWidth, layoutButtonSize()), labelsize()) +
    Vec2i(Fl::box_dw(FL_DOWN_BOX), Fl::box_dh(FL_DOWN_BOX)) +
    2 * 2;
}

template <class T>
void EnumWidget<T>::resize(int x, int y, int w, int h)
{
  Widget::resize(x, y, w, h);
  _widget->resize(x, y, w, h);
}

template <class T>
void EnumWidget<T>::widgetCallback()
{
  _sig.emit(T(_widget->value()));
}

template <class T>
void EnumWidget<T>::widgetUpdate()
{
  _widget->clear();
  for (StrListIt it = _menuList; it.isValid(); ++it)
    _widget->add(it().toAscii());
}

}
