#include "listswitcher.h"
#include <QVBoxLayout>

ListSwitcher::ListSwitcher():widget(0)
{
}

ListSwitcher::~ListSwitcher() {
    delete widget;
}

QWidget* ListSwitcher::getComponent(QWidget *parent) {
    if (widget == 0) {
        if (fixedLength) {
            widget = new QWidget(parent);

            QVBoxLayout *vl =  new QVBoxLayout(widget);

            vl->setMargin(0);

            widget->setLayout(vl);

            QMapIterator<QString,QList<QString> > i(this->values);
            while (i.hasNext()) {
                i.next();

                QTableWidget *table = new QTableWidget(i.value().size(), 1, widget);
                table->setVerticalHeaderLabels(i.value());
                table->horizontalHeader()->setVisible(false);
                table->verticalHeader()->setFixedWidth(100);
                table->setMinimumHeight(table->rowHeight(0) * i.value().size() + 4);

                QVBoxLayout *vlayout =  new QVBoxLayout();
                QSpacerItem *verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
                QWidget *btnWidget = new QWidget(widget);
                QWidget *subWidget = new QWidget(widget);
                QPushButton *clearBtn = new QPushButton("Clear data", widget);
                QHBoxLayout *hlayout = new QHBoxLayout;

                btnWidget->setLayout(vlayout);
                vlayout->setMargin(0);
                vlayout->addWidget(clearBtn);
                vlayout->addItem(verticalSpacer);

                hlayout->setMargin(0);
                subWidget->setLayout(hlayout);

                hlayout->addWidget(table);
                hlayout->addWidget(btnWidget);

                QObject::connect(clearBtn,SIGNAL(clicked()),
                                table,SLOT(clearContents()));
                QObject::connect(clearBtn,SIGNAL(clicked()),
                                this,SLOT(onChange()));


                vl->addWidget(subWidget);
                tables.push_back(table);

                QObject::connect(table, SIGNAL(cellChanged(int,int)),
                                 this, SLOT(onChange()));
            }
            } else {
                widget = new QWidget(parent);
                pushb = new QPushButton("Add row",widget);
                table = new AppendableTableWidget(1,1,widget);
                hlayout = new QHBoxLayout;
                QVBoxLayout *vlayout =  new QVBoxLayout();
                QSpacerItem *verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
                QWidget *btnWidget = new QWidget(widget);
                QPushButton *delBtn = new QPushButton("Delete row", widget);

                btnWidget->setLayout(vlayout);
                vlayout->setMargin(0);
                vlayout->addWidget(pushb);
                vlayout->addWidget(delBtn);
                vlayout->addItem(verticalSpacer);

                hlayout->setMargin(0);
                widget->setLayout(hlayout);

                table->horizontalHeader()->setVisible(false);
                table->verticalHeader()->setVisible(false);

                hlayout->addWidget(table);
                hlayout->addWidget(btnWidget);

                QObject::connect(pushb,SIGNAL(clicked()),
                                table,SLOT(appendRow()));
                QObject::connect(table, SIGNAL(cellChanged(int,int)),
                                 this, SLOT(onChange()));
                QObject::connect(delBtn,SIGNAL(clicked()),
                    table,SLOT(deleteRow()));
            }
        }
    return widget;
}

QString ListSwitcher::buildSwitcherString() {
    if (widget == 0) return "";

    if (fixedLength) { //data jsou v tabulce s pevnou delkou
        int lastChanged = -1;

        //zjisteny v jakych tabulkach jsou data
        for (int i = 0; i < tables.size(); i++) {
            QTableWidget *table = tables.at(i);
            bool wasChange = false;

            for (int j = 0; j < table->rowCount(); j++) {
                QTableWidgetItem *tmp = table->item(j, 0);
                if (tmp == 0 || tmp->text().trimmed().isEmpty()) continue;
                wasChange = true;
                break;
            }

            if (wasChange) lastChanged = i;
        }

        QString res = "";
        QString sep = "";
        //oprava prazdnych bunek a vytvoreni stringu
        for (int i = 0; i <= lastChanged; i++) {
            QTableWidget *table = tables.at(i);

            zerosToTable(table);

            for (int j = 0; j < table->rowCount(); j++) {
                QTableWidgetItem *tmp = table->item(j, 0);
                if (tmp == 0 || tmp->text().trimmed().isEmpty()) continue;
                res += sep + tmp->text();
                sep = separator;
            }
        }

        if (res.isEmpty()) return "";
        else return switcher + " " + quotesText(res);
    } else { //data jsou v tabulce s promennou delkou
        QString res = "";
        QString sep = "";
        for (int i = 0; i < table->rowCount(); i++) {
            QTableWidgetItem *vi = table->item(i, 0);
            if (vi == 0) continue;
            QString v = vi->text();

            if (v.trimmed().isEmpty()) continue;
            res +=  sep + v;
            sep = separator;
        }
        if (res.isEmpty()) return "";
        else  return switcher + " " + quotesText(res);
    }
}

void ListSwitcher::zerosToTable(QTableWidget *table) {
    QObject::disconnect(table, SIGNAL(cellChanged(int,int)),
                             this, SLOT(onChange()));
    for (int j = 0; j < table->rowCount(); j++) {
        QTableWidgetItem *tmp = table->item(j, 0);
        if (tmp == 0 || tmp->text().trimmed().isEmpty()) {
            table->setItem(j, 0, new QTableWidgetItem("0"));
        }
    }
    QObject::connect(table, SIGNAL(cellChanged(int,int)),
                             this, SLOT(onChange()));
}

void ListSwitcher::setValuesFromNode(QDomElement &el) {
    Switcher::setValuesFromNode(el);
    setSeparator(el.attribute("separator"));
    fixedLength = el.attribute("fixed_length", "true") == "true";

   QMap< QString, QList<QString> > values;
   QDomNode itemNode = el.firstChild();
   while(!itemNode.isNull()) {
       QDomElement itemElement = itemNode.toElement();
       values[itemElement.attribute("gr")].append(itemElement.text().trimmed());
       itemNode = itemNode.nextSibling();
   }
   setValues(values);
}


QDomNode& ListSwitcher::getProjectNode(QDomElement &el) {
        Switcher::getProjectNode(el);

    if (fixedLength) { //data jsou v tabulce s pevnou delkou
        for (int i = 0; i < tables.size(); i++) {
            QTableWidget *table = tables.at(i);

            for (int j = 0; j < table->rowCount(); j++) {
                QTableWidgetItem *tmp = table->item(j, 0);
                if (tmp == 0 || tmp->text().trimmed().isEmpty()) continue;

                QDomElement e = el.ownerDocument().createElement("value");
                e.setAttribute("value", tmp->text());
                el.appendChild(e);
            }
        }

    } else { //data jsou v tabulce s promennou delkou
        for (int i = 0; i < table->rowCount(); i++) {
            QTableWidgetItem *vi = table->item(i, 0);
            if (vi == 0) continue;
            QString v = vi->text();

            if (v.trimmed().isEmpty()) continue;

            QDomElement e = el.ownerDocument().createElement("value");
            e.setAttribute("value", v);
            el.appendChild(e);
        }
    }


    return el;
}

void ListSwitcher::setSavedValues(QDomElement &el) {
    QDomNode it = el.firstChild();

    int counter = 0, sum = 0;
    QListIterator<QTableWidget*> tit(tables);
    QTableWidget *t = 0;
    if (fixedLength && tit.hasNext()) t = tit.next();

    while (!it.isNull()) {
        QDomElement element = it.toElement();

        if (element.isNull()) continue;

        QString value = element.attribute("value");

        if (fixedLength) {
            if (t == 0) break;
            if (counter < sum + t->rowCount()) t->setItem(counter - sum, 0, new QTableWidgetItem(value));
            else {
                if (!tit.hasNext()) break;

                sum += t->rowCount();
                t = tit.next();
            }
        } else {
            table->appendRow();
            table->setItem(counter, 0, new QTableWidgetItem(value));
        }

        counter++;
        it = it.nextSibling();
    }
}
