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

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

//#define DJ_DBG
#include "djShuttleWidget.h"
#include <djIcon.h>
#include <FL/Fl.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Image.H>

namespace dj {

ShuttleWidget::ShuttleWidget() :
  _value(0.0),
  _pressed(false)
{
  _icon[0] = dj::icon("shuttle0");
  _icon[1] = dj::icon("shuttle1");
  _icon[2] = dj::icon("shuttle2");
  _icon[3] = dj::icon("shuttle3");
  _icon[4] = dj::icon("shuttle4");
  _icon[5] = dj::icon("shuttle5");
  _icon[6] = dj::icon("shuttle6");
  _icon[7] = dj::icon("shuttle7");

  //box(FL_THIN_UP_BOX);
  box(FL_FLAT_BOX);

  sizePolicy(FIXED, FIXED);
}

const Vec2i ShuttleWidget::sizeHint() const
{
  return Vec2i(_icon[0]->w(), _icon[0]->h()) + frameWidth() * 2 + 2 * 2;
}

void ShuttleWidget::draw()
{
  WidgetBase::draw();

  DJ_DBG_FNC("dj::ShuttleWidget::draw");

  const Fl_Boxtype boxUp = FL_FLAT_BOX;
  const Fl_Boxtype boxDown = FL_THIN_DOWN_BOX;
  const Fl_Boxtype box = _pressed ? boxDown : boxUp;
  
  const int i = mod(int(_value / 10.0), 8);
  DJ_DBG_PRN("index = " << i);
  
  fl_draw_box(box, x(), y(), w(), h(), color());
  _icon[i]->draw(
    x() + (w() - _icon[0]->w()) / 2,
    y() +
     (h() - _icon[0]->h()) / 2
  );
}

int ShuttleWidget::handle(int in)
{
  const Vec2i mouse(Fl::event_x(), Fl::event_y());
  
  switch (in) {
  
    case FL_PUSH:
      _value = 0;
      _pressed = true;
      _mouseTd = mouse;
      _startSig.emit(true);
      redraw();
      return 1;
      
    case FL_RELEASE:
      _value = 0;
      _pressed = false;
      _stopSig.emit(true);
      redraw();
      return 1;
    
    case FL_DRAG: {
      const int tmp = mouse.x() - _mouseTd.x();
      if (tmp != _value) {
        _value = tmp;
        _valueSig.emit(int(_value / 10.0));
        redraw();
      }
    } return 1;
  }
  
  return Widget::handle(in);
}

}
