#include "Panel.h"

#include "Main_window.h"
#include "Model_RM_window.h"
#include "Model_RM_widget.h"
#include "Project.h"

#include <QShowEvent>

namespace MM
{

Panel::
Panel (Text const & title, Text const & layout)
:
    title_  (title),
    layout_ (layout)
{
    setAttribute (Qt::WA_DeleteOnClose);
    add_to_tab ();
}

Panel::
~Panel ()
{
    //Main_window *main = Main_window::singleton();

    //if (layout_ == "right") 
    //    main->min_right_panel ();
    //else if (layout_ == "left") 
    //    main->min_left_panel ();
    //else if (layout_ == "middle") 
    //    main->min_middle_panel ();
    //else if (layout_ == "bottom") 
    //    main->min_bottom_panel ();
}

void Panel::
add_to_tab ()
{
    Main_window *main = Main_window::singleton();

    if (layout_ == "right") 
    {
        main->tabWidget_right->addTab (this, title_.c_str());
        main->min_right_panel ();
    }
    else if (layout_ == "left") 
    {
        main->tabWidget_left->addTab (this, title_.c_str());
        main->min_left_panel ();
    }
    else if (layout_ == "middle") 
    {
        main->tabWidget_middle->addTab (this, title_.c_str());
        main->min_middle_panel ();
    }
    else if (layout_ == "bottom") 
    {
        main->tabWidget_bottom->addTab (this, title_.c_str());
        main->min_bottom_panel ();
    }
}

void Panel::
popup ()
{
    Main_window *main = Main_window::singleton();

    if (layout_ == "right") 
        main->tabWidget_right-> setCurrentWidget (this);

    else if (layout_ == "left") 
        main->tabWidget_left->  setCurrentWidget (this);

    else if (layout_ == "middle") 
        main->tabWidget_middle->setCurrentWidget (this);

    else if (layout_ == "bottom") 
        main->tabWidget_bottom->setCurrentWidget (this);

    turn (true);
}

Model_RM_window * Panel::
window ()
{
    return (Model_RM_window*) Main_window::singleton()->current_model_window();
}

Model_RM_widget * Panel::
widget ()
{
    REQUIRE ("Model window exist.", window () != 0);

    return window ()->current_model_widget ();

    //Model_RM_widget * result = 
    //    dynamic_cast <Model_RM_widget *> (window ()->focusWidget ());

    //if (result == 0)
    //    result = window ()->RM_widget_1_;

    //return result;
}

Model & Panel::
model ()
{
    Model_RM_window * win = window();

    if (win == 0)
        return Project::singleton().current_model();

    return win->model ();
}

void Panel::
showEvent (QShowEvent * event) 
{
    if (!event->spontaneous ())
        turn (true);

    QWidget::showEvent (event);
}

void Panel::
hideEvent (QHideEvent * event) 
{
    if (!event->spontaneous ())
        turn (false);

    QWidget::hideEvent (event);
}

void Panel::
closeEvent (QCloseEvent * event)
{
    if (event->isAccepted())
        turn (false);

    resize (10,10);
    setMinimumSize (10,10);
    setSizePolicy (QSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored));

    QWidget::closeEvent (event);
}

}//MM
