/**
 * DESCRIPTION OF THE FILE
 *
 * @author Michal KravĨenko
 * @date 4.9.18 -
 */

#include <boost/serialization/export.hpp>

#include "exprtk.hpp"
#include "ExprtkWrapper.h"
#include "ExprtkWrapperSerialization.h"
#include "exceptions.h"
#include <string>

//BOOST_CLASS_EXPORT_IMPLEMENT(ExprtkWrapper);

ExprtkWrapper::ExprtkWrapper(std::string expression_string) {

//    this = new ExprtkWrapperImpl();

    this->expression_str = expression_string;

    this->symbol_table = new symbol_table_t();

    this->symbol_table->add_variable("x",
                                             this->x);
    this->symbol_table->add_variable("y",
                                             this->y);
    this->symbol_table->add_variable("z",
                                             this->z);
    this->symbol_table->add_variable("t",
                                             this->t);
    this->symbol_table->add_variable("f",
                                             this->z);

    this->expression = new expression_t();
    this->expression->register_symbol_table(*this->symbol_table);

    this->parser = new parser_t();
    this->parser->compile(this->expression_str,
                                  *this->expression);
}

ExprtkWrapper::~ExprtkWrapper() {

    if (this->expression) {
        delete this->expression;
        this->expression = nullptr;
    }

    if (this->symbol_table) {
        delete this->symbol_table;
        this->symbol_table = nullptr;
    }

    if (this->parser) {
        delete this->parser;
        this->parser = nullptr;
    }

    delete this;
//    this = nullptr;

}

double ExprtkWrapper::eval(double x1,
                           double x2,
                           double x3,
                           double x4) {

    this->x = x1;
    this->y = x2;
    this->z = x3;
    this->t = x4;

    return this->expression->value();

}

double ExprtkWrapper::eval(std::vector<double>& p) {


    if (p.size() > 0) {
        this->x = p[0];
    }
    if (p.size() > 1) {
        this->y = p[1];
    }
    if (p.size() > 2) {
        this->z = p[2];
    }
    if (p.size() > 3) {
        this->t = p[3];
    }

    double result = this->expression->value();

    return result;
}

ExprtkWrapper::ExprtkWrapper(expression_t* expression,
                             symbol_table_t* symbol_table,
                             parser_t* parser,
                             double x,
                             double y,
                             double z,
                             double t,
                             double f,
                             std::string expression_str) {
    this->expression = expression;
    this->symbol_table = symbol_table;
    this->parser = parser;
    this->x = x;
    this->y = y;
    this->z = z;
    this->t = t;
    this->f = f;
    this->expression_str = expression_str;
}