#include "Console_application.h"

//#include "Test_suite.h"
#include "Timer.h"
#include "DbC.h"
#include "Flaw.h"
#include "Log.h"

#include <iostream>
#include <string>

namespace MM
{

Console_application::
Console_application (int, char * argv[])
:
    name_(argv[0])
{
}


int Console_application::
run ()
{
    //Test_suite::singleton ("correctness").run();
    using namespace std;

    Timer timer;
    string command;

    do
    { 
        while (!task_.empty())
        {
            Command *current_task = task_.front();
            task_.pop();
            current_task->execute();
            delete current_task;
        }
    
        try
        {
            cin >> command;
        }
        catch (DbC::Contract_violation & error)
        {
            cout << error.message().c_str();
		    log() << "\n";
        }
        catch (Flaw & error)
        {
            cout << "Flaw: " << error.message().c_str();
		    log() << "\n";
        }
        catch (char * error)
        {
            cout << "Exception: " << error;
		    log() << "\n\n" << "Exception: " << error << "\n\n";
        }
        catch (std::exception & error)
        {
            Text message;
            message += "std::exception: ";
            message += typeid(error).name();
            message += "\n";
            message += error.what();
            message += "\n";

            cout << message.c_str();
		    log() << "\n\n" << message << "\n";
        }
        catch (...)
        {
            Text message ("Console_application crash: Unknown exception\n");
            cout << message.c_str();
		    log() << "\n\n" << message << "\n";
        }
    }
    while (!(command == "q"    || 
             command == "Q"    || 
             command == "quit" || 
             command == "exit"));

    Text message ("Duration ");
    message += timer.elapsed ();
    message += " sec.";
    cout  << message.c_str();
    log() << message << "\n\n";
    
    return 0;
}
}
