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

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

//#define DJ_DBG
#include "djScrollWidget.h"
#include <FL/Fl.H>
#include <FL/Fl_Box.H>

namespace dj {

ScrollWidget::ScrollWidget() :
  Fl_Scroll(0, 0, 0, 0),
  _contentsResizable(true)
{
  //Fl_Scroll::type(Fl_Scroll::BOTH_ALWAYS);
  _dummyWidget = new Fl_Box(0, 0, 0, 0);
  _dummyWidget->hide();
  end();
  
  VLayout * layout = new VLayout(this);
  layout->margin(0);
}

void ScrollWidget::contentsResizable(bool in)
{
  _contentsResizable = in;
  layoutUpdate();
}

const Vec2i ScrollWidget::sizeHint() const
{
  return Vec2i();
}

void ScrollWidget::resize(int x, int y, int w, int h)
{
  Fl_Widget::resize(x, y, w, h);
  LayoutItem::resize(x, y, w, h);
  if (_contentsResizable) layoutUpdate();
}

int ScrollWidget::visible() const { return Fl_Scroll::visible(); }

int ScrollWidget::handle(int in)
{
  switch (in) {
    
    case FL_KEYBOARD:
      switch (Fl::event_key()) {
      
        // XXX Disable arrow-key navigation.
        //
        case FL_Left:
        case FL_Right:
        case FL_Up:
        case FL_Down: return 0;
      }
      break;
  }
  
  return Fl_Scroll::handle(in);
}

void ScrollWidget::layoutUpdate()
{
  DJ_DBG_FNC("dj::ScrollWidget::layoutUpdate");
  
  const Vec2i size = layout()->sizeHint();
  int x = this->x() + Fl::box_dx(box());
  int y = this->y() + Fl::box_dy(box());
  int w = this->w() - Fl::box_dx(box()) * 2;
  int h = this->h() - Fl::box_dy(box()) * 2;
  
  // XXX Determine scrollbar visibility. Can't ask FLTK because it doesn't
  // know until draw() is called.
  //
  bool scrollbarV = false, scrollbarH = false;
  if (size.y() > h) {
    scrollbarV = true;
    w -= Fl_Scroll::scrollbar.w();
  }
  if (size.x() > w) {
    scrollbarH = true;
    h -= Fl_Scroll::hscrollbar.h();
    if (! scrollbarV && size.y() > h) {
      scrollbarV = true;
      w -= Fl_Scroll::scrollbar.w();
    }
  }
  
  if (_contentsResizable) {
    w = max(w, size.x());
    h = max(h, size.y());
  }
  DJ_DBG_PRN("size = " << Vec2i(w, h));
  
  layout()->resize(x, y, w, h);
  _dummyWidget->resize(x, y, w, h);
  redraw();
}

}
