#include "textswitcher.h"
#include <QProcess>

TextSwitcher::TextSwitcher():widget(0),combo(0)
{
}

QString TextSwitcher::buildSwitcherString() {
    if (isOptions) {
        if (combo == 0 || combo->currentIndex() <= 0) return "";
        return switcher + " " + quotesText(options.at(combo->currentIndex()-1));
    } else {
        if (widget == 0 || widget->text().isEmpty()) return "";
        else return switcher + " " + quotesText(widget->text());
    }
}

QWidget* TextSwitcher::getComponent(QWidget *parent) {
    if (isOptions) {
        if (combo == 0) {
            combo = new QComboBox(parent);
            QObject::connect(combo, SIGNAL(currentIndexChanged(int)),
                             this, SLOT(onChange()));
            combo->addItem(NONE_STR);
            for (int i = 0; i < options.size(); i++) {
                combo->addItem(options.at(i));
            }
        }

        return combo;
    } else {
        if (widget == 0) {
            widget = new QLineEdit(parent);
            QObject::connect(widget, SIGNAL(textChanged(QString)),
                             this, SLOT(onChange()));

        }

        return widget;
    }
}

void TextSwitcher::setValuesFromNode(QDomElement &el) {
    Switcher::setValuesFromNode(el);

    isOptions = el.hasAttribute("options");
    if (isOptions) {
        QString command = el.attribute("options", "");

        QObject parent;
        QProcess process(&parent);
        process.start(QString(APP_DIR) + "/scripts/" + command);
        process.waitForFinished();

        QByteArray text = process.readAll();

        QList<QByteArray> lines = text.split('\n');
        foreach ( const QByteArray &line, lines ) {
            QString tmp = line.trimmed();
            if (!tmp.isEmpty()) options.append(tmp);
        }
    }
}
