#include "Model_singleton_view.h"

#include "Project.h"
#include "Command_template.h"
#include "Model.h"
#include "Model_kit.h"

namespace MM
{
Model_singleton_view::
Model_singleton_view ()
:
    renew_current_model_(0),
    renew_model_content_(0),
    current_model_      (&Model::none())
{
    renew_current_model_ = create_command_1 
        (*this, &Model_singleton_view::handle_renew_current_model);

    renew_model_content_ =
        create_command_1 (*this, &Model_singleton_view::renew);


    Project & project = Project::singleton();
    project.on_change_current (renew_current_model_);

    if (project.model_count() > 0)
        setup_commands (project.current_model());
}

Model_singleton_view::
~Model_singleton_view ()
{
    Project::singleton().on_change_current (renew_current_model_, false);    

    if (current_model_ != &Model::none())
    {
        CHECK ("", current_model_ != 0);
        CHECK ("", current_model_ != &Model::none());

        current_model_->kit().event().
            when_model_changed (renew_model_content_, false);
    }

    renew_current_model_ = 0;
    renew_model_content_ = 0;
    current_model_       = 0;
}

void Model_singleton_view::
handle_renew_current_model (Model &model) 
{
    setup_commands      (model);
    renew_current_model (model);
}

void Model_singleton_view::
setup_commands (Model &model) 
{
    REQUIRE ("", current_model_ != 0);

    if (current_model_ != &Model::none())
    {
        current_model_->kit().event().
            when_model_changed (renew_model_content_, false);
    }

    current_model_ = &model;

    if (current_model_ != &Model::none())
    {
        renew_model_content_ =
            create_command_1 (*this, &Model_singleton_view::renew);

        model.kit().event().when_model_changed (renew_model_content_);
    }
}

}//MM
