#include <QSettings>
#include <stdio.h>

#include "ConfigPanel.h"
#include "QuantityFormat.h"

QuantityFormat::QuantityFormat() {

    ConfigPanel &config = ConfigPanel::instance();
    connect(&config, &ConfigPanel::fractionalDigitsChanged, this, &QuantityFormat::setFractionalDigits);

    csvopt = &config.getCSVOptions();
    setFractionalDigits(csvopt->frac_digits);
}

void QuantityFormat::toPreferredUnit(Quantity &qty) const {

    unit_category_t cat = unit_category(qty.unit);
    unit_t pref = csvopt->units[cat];

    quantity_convert_to_unit(&qty, pref);
}

QString QuantityFormat::toString(double value) const {

    QString result;
    result.sprintf(format, value);

    return result;
}

QString QuantityFormat::toString(const Quantity &qty) const { return toString(quantity_value_as_double(&qty)); }

void QuantityFormat::setFractionalDigits(int n) {

    sprintf(format, "%%.%df", n);
    csvopt->frac_digits = n;
}
