// src/jump_to_dialog.cc - Copyright 2005, 2006, University
//               of Padova, dept. of Pure and Applied
//               Mathematics
//
// This file is part of SGPEMv2.
//
// This is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// SGPEMv2 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SGPEMv2. If not, see http://www.gnu.org/licenses/.


#include "jump_to_dialog.hh"

#include <sgpemv2/templates/sequences.tcc>
#include <sgpemv2/history.hh>
#include <sgpemv2/environment.hh>
#include <sgpemv2/simulation.hh>
#include <sgpemv2/resource.hh>

#include "gettext.h"

#include <gtkmm/button.h>
#include <gtkmm/main.h>
#include <gtkmm/messagedialog.h>

#include <cassert>
#include <iostream>

using namespace sgpem;
using namespace Gtk;
using namespace Glib;


JumpToDialog::JumpToDialog(BaseObjectType* cobject, const RefPtr<Builder>& ui) :
  Dialog(cobject), _target_instant(0)
{
  Button* stop_button;
  ui->get_widget("Button.Stop", stop_button);
  ui->get_widget("ProgressBar", _progress);

  // Attach signal handlers
  stop_button->signal_clicked().connect(sigc::mem_fun(*this, &JumpToDialog::_on_stop));
  signal_response().connect(sigc::hide(sigc::mem_fun(*this, &JumpToDialog::hide)));
}


unsigned int
JumpToDialog::set_target_instant(unsigned int new_target)
{
  unsigned int temp = _target_instant;
  _target_instant = new_target;
  return temp;
}


unsigned int
JumpToDialog::get_target_instant() const
{
  return _target_instant;
}


void
JumpToDialog::start()
{
  show();
  _progress->set_fraction(0.0);
  
  Simulation& sim = Simulation::get_instance();
  History&    h   = sim.get_history();

  // start listening to simulation updates
  sim.attach(*this);
  
  try
  {
    if(_target_instant < h.get_size() - 1)
      sim.jump_to(_target_instant);
    else
      sim.jump_to(h.get_size() - 1);

    // disable notifications on History since we could call 
    // run() a lot of times
    History::LockNotify h_lock(h);
    while(h.get_front() <= _target_instant)
    {
      sim.run();
      if(sim.get_state() == Simulation::state_stopped)
	      break; // Simulation ended before reaching _target_instant
    }
  }
  // TODO: exception handling copied from SimulationController, it should be factored out (?)
  catch(const UserInterruptException& uie)
  {
    // Show the user a dialog
    MessageDialog diag(_("<b>The selected user CPU policy stopped before returning:</b>\n") + Markup::escape_text(uie.what()), 
                       true, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
    diag.run();
  }
  catch(const MalformedPolicyException& mpe)
  {
    // Show user a dialog
    MessageDialog diag(_("<b>The selected user CPU policy was malformed and failed to sort the queue:</b>\n") + 
                       Markup::escape_text(mpe.what()), true, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
    diag.run();

    try
    {
      // Deactivate the policy
      sim.set_policy(NULL);
    }
    catch(const CPUPolicyException& cpe)
    {
      // Fatal error. We should never get here.
      std::cerr << _(" [EE] Fatal error. Impossible to deactivate the policy in ") <<  __FILE__ << ":" << __LINE__
                << std::endl << _(" [EE] ") << cpe.what() << std::endl;
      abort();
    }
  }
  catch(const NullPolicyException& npe)
  {
    MessageDialog diag(_("<b>No active policy selected:</b>\n") + Markup::escape_text(npe.what()), 
                       true, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
    diag.run();

  }
  catch(const CPUPolicyException& cpe)
  {
    MessageDialog diag(_("<b>Unexpected error</b>:\n") + Markup::escape_text(cpe.what()), 
                       true, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
    diag.run();
  }

  // Ending successfully: detach me, reenable notifications,
  // and emit response ``okay''
  sim.detach(*this);
  response(Gtk::RESPONSE_OK);
}


void
JumpToDialog::_on_stop()
{
  Simulation::get_instance().stop();
  response(Gtk::RESPONSE_CANCEL);
}


bool
JumpToDialog::on_delete_event(GdkEventAny* event)
{
  _on_stop();
  return Dialog::on_delete_event(event);
}


void
JumpToDialog::update(const Simulation& changed_simulation)
{
  const unsigned int front = changed_simulation.get_history().get_front();

  const double percent = _target_instant == 0 ? 0 : std::min(static_cast<double>(front) / _target_instant, 1.0);

  _progress->set_fraction(percent);

  //  Needed to force display (else under
  //  intensive computation it doesn't have
  //  the time to flush all UI events):
  while(Gtk::Main::events_pending())
    Gtk::Main::iteration();
}
