#include "Pause_stage.h"

#include <sstream>

#include "Timer.h"
#include "Sleep.h"
#include "User.h"

namespace MM
{

Pause_stage::
Pause_stage (Protocol &protocol, Text const & init)
:
    Protocol_stage_frame (protocol),
    iteration_finished_(new No_command)
{
    using namespace std;
    istringstream str(init.c_str());
    string intention, length, comment_first_word, comment_end;
    str >> intention >> length >> comment_first_word;
    //title_ = title.c_str();

    length_.set_current_type    ("sec");
    length_.set_step_length_ps  (1);
    length_.from_text           (length.c_str());

    getline (str, comment_end);
    comment_ = (comment_first_word + comment_end).c_str();
}

void Pause_stage::
execute ()
{
    stop_flag_ = false;
    double pause_time = length_.sec();
    Timer timer, timer_1_sec;

    while (timer.elapsed() < pause_time && !stop_flag_)
    {
        sleep (1);

        if (timer_1_sec.elapsed() > 1.)
        {
            Text status ("Pause  (");
            status += (int)timer.elapsed();
            status += " sec form ";
            status += pause_time;
            status += ").";
            to_user().status (status);
            timer_1_sec.restart();
        }

        iteration_finished_().execute ();
    }
}

void Pause_stage::
stop ()
{
    stop_flag_ = true;
}

bool Pause_stage::
was_stopped ()
{
    return stop_flag_;
}

Text Pause_stage::
option (Text const& key) const
{
    if      (key == "Length")   return Text (length_.text());
    else if (key == "Comment")  return comment_;
    return ""; 
}

void Pause_stage::
set_option (Text const & key, Text const & value)
{
    if (key == "Length")
        length_.from_text (value);

    else if (key == "Comment")
        comment_ = value;

    else
        to_user().status (Text("'") + key + "' - unknown key.");
}

void Pause_stage::
get_option (int i, Text & key, Text & value) const
{
        switch (i)
        {
        case 0: key = "Length";     value = length_.sec();  return;
        case 1: key = "Comment";    value = "No comments";  return;
        default:
            FLAW (Text(i) + " is out of range. Options count is " 
                          + option_count() + ".");
        }
}

}//MM



