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

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

//#define DJ_DBG
#include "djWindow.h"
#include <djApp.h>
#include <FL/Fl.H>

namespace dj {

Window::Window(const Str & title) :
  Fl_Double_Window(0, 0, 0, 0),
  _title(title),
  _fullscreen(false)
{
  DJ_DBG_FNC("dj::Window::Window");
  DJ_DBG_PRN("this = " << int(this));

  label(_title.toAscii());
  end();
  
  // Initialize.
  //
  djApp->windowAdd(this);
  size(Vec2i(400, 300));

  // Callbacks.
  //
  callback(closeCallback, this);
}

Window::~Window()
{
  DJ_DBG_FNC("dj::Window::~Window");

  djApp->windowDel(this);
}

void Window::title(const Str & in)
{
  _title = in;
  label(_title.toAscii());
}

void Window::size(const Vec2i & in)
{
  if (in == _geom.size()) return;
  
  DJ_DBG_FNC("dj::Window::size");
  DJ_DBG_PRN("in = " << in);
  
  if (_fullscreen) {
  
    Fl_Double_Window::fullscreen_off(
      _geomTmp.x(), _geomTmp.y(), in.x(), in.y()
    );
    _fullscreen = false;
    
  } else {
  
    Fl_Double_Window::size(in.x(), in.y());
  }
  size_range(16, 16, 0, 0);
  free_position();
}

void Window::resize(int x, int y, int w, int h)
{
  DJ_DBG_FNC("dj::Window::resize");
  DJ_DBG_PRN("in = " << Box2i(x, y, w, h));
  
  const Box2i tmp = _geom;
  _geom = Box2i(x, y, w, h);

  Fl_Double_Window::resize(x, y, w, h);
  if (Vec2i(w, h) != tmp.size())
    WidgetBase::resize(0, 0, w, h);
  size_range(16, 16, 0, 0);
}

int Window::visible() const
{
  return Fl_Double_Window::visible();
}

void Window::fullscreen(bool in)
{
  if (in == _fullscreen) return;
  
  _fullscreen = in;
  
  if (_fullscreen) {
  
    _geomTmp = _geom;
    Fl_Double_Window::fullscreen();
    
  } else {
  
    Fl_Double_Window::fullscreen_off(
      _geomTmp.x(), _geomTmp.y(), _geomTmp.width(), _geomTmp.height()
    );
    size_range(16, 16, 0, 0);
    free_position();
  }
}

int Window::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_Double_Window::handle(in);
}

void Window::closeCallback()
{
  hide();
  
  _closeSig.emit(true);
}

void Window::layoutUpdate()
{
  //DJ_DBG_FNC("dj::Window::layoutUpdate");

  const Vec2i size = max(Vec2i(w(), h()), sizeHint());
  //DJ_DBG_PRN("size = " << size);
  
  WidgetBase::resize(0, 0, size.x(), size.y());
  redraw();
}

}
