//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Fit/Option/MinimizerOptions.cpp
//! @brief     Implements class MinimizerOptions.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Fit/Option/MinimizerOptions.h"
#include "Fit/Tool/StringUtil.h"
#include <iostream>
#include <sstream>
#include <stdexcept>

namespace {

const std::string delimeter = ";";

} // namespace


std::string MinimizerOptions::toOptionString() const
{
    std::ostringstream result;
    for (const auto& option : m_options)
        result << option->name() << "=" << option->value_str() << delimeter;
    return result.str();
}

void MinimizerOptions::setOptionString(const std::string& options)
{
    // splits multiple option string "Strategy=1;Tolerance=0.01;"
    std::vector<std::string> tokens = mumufit::stringUtil::split(options, delimeter);
    try {
        for (const std::string& opt : tokens)
            if (!opt.empty())
                processCommand(opt);
    } catch (std::exception& ex) {
        std::ostringstream ostr;
        ostr << "MinimizerOptions::setOptions -> Error. Cannot parse option string '" << options
             << "'.\n, error message '" << ex.what() << "'";
        throw std::runtime_error(ostr.str());
    }
}

//! Process single option string 'Tolerance=0.01' and sets the value
//! to corresponding MultiOption

void MinimizerOptions::processCommand(const std::string& command)
{
    std::vector<std::string> tokens = mumufit::stringUtil::split(command, "=");
    if (tokens.size() != 2)
        throw std::runtime_error("MinimizerOptions::processOption -> Cannot parse option '"
                                 + command + "'");

    std::string name = tokens[0];
    std::string value = tokens[1];

    OptionContainer::option_t opt = option(name);
    opt->setFromString(value);
}
