#include "Unit.h"

#include <sstream>

#include "User.h"

namespace MM
{
Unit::Unit () : definite_flag_(true) { }

Text Unit::
text () const
{
    //fix 
    //return definite_flag_
    //    ? Text (value ()) + " " + current_type()
    //    : "";

    return Text (value ()) + " " + current_type();
}

bool Unit::
from_text (Text const& str)
{
    using namespace std;

    if (str == "" || str == "-")
    {
        definite_flag_ = false;
    }
    else
    {
        istringstream in (str.c_str());

        double value;
        in >> value;
        if (in.fail())
        {
            if (correct (str))
            {
                set_current_type (str);
                return true;
            }
            else
            {
                Text message =  str + " - is not known units.\n";
                     message += "Supported units: ";

                for (int i=0;  i<type_count();  ++i)
                {
                    message += type (i);
                    message += " ";
                }
                message += ".";

                to_user(). error (message);
                return false;
            }
        }

        string units;   in >> units;
        if (!in.fail())
        {
            if (correct (units.c_str()))
                set_current_type (units.c_str());
            else
            {
                Text message =  str + " - is not known units.\n";
                     message += "Supported units: ";

                for (int i=0;  i<type_count();  ++i)
                {
                    message += type (i);
                    message += " ";
                }
                message += ".";

                to_user(). error (message);
                return false;
            }
        }

        set_value (str.to_double());
        definite_flag_ = true;
    }

    return true;
}

}//MM


