// @topic W010201 FLTK Graphics -- maze navigation
// @brief Buttons, animation, 2D drawing

#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Output.H>
#include <FL/Fl_Button.H>

#include "Drawing2D.h"

void cb_btn_right( Fl_Widget* btn, void* userdata );
void cb_btn_left( Fl_Widget* btn, void* userdata );
void animation_begin( Fl_Widget* widg, void* userdata );
void animation_continue( void* userdata );

int main()
{
    // create data model
    Room kitchen = "kitchen";
    Room nroom = "north";
    Room eroom = "east";
    Room sroom = "south";
    Room wroom = "west";
    kitchen.add_door( Room::COMPASS_NORTH, &nroom );
    kitchen.add_door( Room::COMPASS_EAST, &eroom );
    kitchen.add_door( Room::COMPASS_SOUTH, &sroom );
    kitchen.add_door( Room::COMPASS_WEST, &wroom );

    Fl_Double_Window window = Fl_Double_Window( 483, 410 );
    Fl_Button button_right = Fl_Button( 30, 15, 100, 25, "->" );
    Fl_Button button_left = Fl_Button( 40, 60, 75, 25, "<-" );

    int x1 = 170;
    int y1 = 30;
    int x2 = 300;
    int y2 = 190;
    Drawing2D canvas( x1, y1, x2, y2, &kitchen );
    canvas.callback( ( Fl_Callback* ) animation_begin, &canvas );
    button_right.callback( ( Fl_Callback* ) cb_btn_right, &canvas );
    button_left.callback( ( Fl_Callback* ) cb_btn_left, &canvas );

    window.end();
    window.resizable( window );
    window.show();
    return Fl::run();
}

void cb_btn_right( Fl_Widget* btn, void* userdata )
{
    Drawing2D* pcanvas = static_cast< Drawing2D* >( userdata );
    pcanvas->turn_head_right();
    Fl::redraw();
}

void cb_btn_left( Fl_Widget* btn, void* userdata )
{
    Drawing2D* pcanvas = static_cast< Drawing2D* >( userdata );
    pcanvas->turn_head_left();
    Fl::redraw();
}

// timer animation
void animation_begin( Fl_Widget* widg, void* userdata )
{
    Drawing2D* pcanvas = static_cast< Drawing2D* >( userdata );
    if ( pcanvas->animate_door_entry() ) {
        Fl::add_timeout( TICK_TIMEOUT, animation_continue, userdata );
    }
}

void animation_continue( void* userdata )
{
    Drawing2D* pcanvas = static_cast< Drawing2D* >( userdata );
    if ( pcanvas->animate_door_entry() ) {
        Fl::redraw();
        Fl::add_timeout( TICK_TIMEOUT, animation_continue, userdata );
    } else {
        Fl::redraw();
    }
}