#include "EditClientDialog.h"

// Qt
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSettings>
#include <QTabWidget>
#include <QTextEdit>
#include <QVBoxLayout>

// Self
#include "../def.h"
#include "DropFileWidget.h"
#include "LicenseModel/LicenseModel.h"

#define WINDOW_SIZE "WindowSize"

EditClientDialog::EditClientDialog(LicenseModel* model, QWidget *parent)
    : QDialog(parent)
    , m_model(model)
{
    setWindowTitle(tr("Edit Client"));
    setModal(true);
    setAcceptDrops(true);

    // Ui
    {
        auto vLayout = new QVBoxLayout;
        setLayout(vLayout);
        m_tabWidget = new QTabWidget(this);
        vLayout->addWidget(m_tabWidget);

        // Auto filled widget
        {
            auto autoFilledWidget = new QWidget(m_tabWidget);
            auto layout = new QVBoxLayout;
            autoFilledWidget->setLayout(layout);

            auto dropWidget = new DropFileWidget(autoFilledWidget);
            layout->addWidget(dropWidget);
            layout->addStretch();
            m_configPathLabel = new QLabel(tr("Drop file here"));
            m_configPathLabel->setAlignment(Qt::AlignCenter);
            layout->addWidget(m_configPathLabel);
            m_tabWidget->addTab(autoFilledWidget, tr("File autofilled"));

            connect(dropWidget, &DropFileWidget::filesDropped, this, &EditClientDialog::onFilesChanged);
        }

        // Manual user add widget
        {
            m_manualWidget = new QWidget(m_tabWidget);
            auto gridLayout = new QGridLayout();
            m_manualWidget->setLayout(gridLayout);

            gridLayout->setColumnStretch(0, 0);
            gridLayout->setColumnStretch(1, 1);

            gridLayout->addWidget(makeLabel(tr("First name")), 0, 0);
            m_firstNameLineEdit = new QLineEdit(m_manualWidget);
            gridLayout->addWidget(m_firstNameLineEdit, 0, 1);
            gridLayout->addWidget(makeLabel(tr("Last name")), 1, 0);
            m_lastNameLineEdit = new QLineEdit(m_manualWidget);
            gridLayout->addWidget(m_lastNameLineEdit, 1, 1);
            gridLayout->addWidget(makeLabel(tr("Patronymic")), 2, 0);
            m_patronymicLineEdit = new QLineEdit(m_manualWidget);
            gridLayout->addWidget(m_patronymicLineEdit, 2, 1);

            gridLayout->addWidget(makeLabel(tr("Email")), 3, 0);
            m_emailLineEdit = new QLineEdit(m_manualWidget);
            m_emailLineEdit->setPlaceholderText("examplebox@email.com");
            gridLayout->addWidget(m_emailLineEdit, 3, 1);

            gridLayout->addWidget(makeLabel(tr("Phone")), 4, 0);
            m_phoneLineEdit = new QLineEdit(m_manualWidget);
            m_phoneLineEdit->setPlaceholderText("+7(777)777-77-77");
            gridLayout->addWidget(m_phoneLineEdit, 4, 1);

            gridLayout->addWidget(makeLabel(tr("City")), 5, 0);
            m_cityLineEdit = new QLineEdit(m_manualWidget);
            gridLayout->addWidget(m_cityLineEdit, 5, 1);

            gridLayout->addWidget(makeLabel(tr("You company name")), 6, 0);
            m_yourCompanyNameTextEdit = new QLineEdit(m_manualWidget);
            gridLayout->addWidget(m_yourCompanyNameTextEdit, 6, 1);

            gridLayout->addWidget(makeLabel(tr("Hardware hash")), 9, 0);
            m_hardwareHashLineEdit = new QLineEdit(m_manualWidget);
            gridLayout->addWidget(m_hardwareHashLineEdit, 9, 1);

            gridLayout->addWidget(makeLabel(tr("Comment")), 10, 0);
            m_commentTextEdit = new QTextEdit(m_manualWidget);
            gridLayout->addWidget(m_commentTextEdit, 11, 0, 1, 2);
            m_commentTextEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
            gridLayout->setRowStretch(11, 1);

            m_tabWidget->addTab(m_manualWidget, tr("Manual"));
        }

        auto hLayout = new QHBoxLayout;
        hLayout->setSpacing(vLayout->spacing());
        hLayout->addStretch();
        m_saveButton = new QPushButton(tr("Save"), this);
        hLayout->addWidget(m_saveButton);
        auto cancelButton = new QPushButton(tr("Cancel"), this);
        hLayout->addWidget(cancelButton);
        vLayout->addItem(hLayout);

        connect(m_saveButton, &QPushButton::clicked, this, &QDialog::accept);
        connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);
    }

    loadSettings();
}

EditClientDialog::~EditClientDialog()
{
    saveSettings();
}

void EditClientDialog::loadSettings()
{
    QSettings settings(ORGANIZATION_NAME, metaObject()->className());
    if (settings.contains(WINDOW_SIZE))
        resize(settings.value(WINDOW_SIZE).toSize());
}

void EditClientDialog::saveSettings()
{
    QSettings settings(ORGANIZATION_NAME, metaObject()->className());
    settings.setValue(WINDOW_SIZE, size());
}

void EditClientDialog::onFilesChanged(const QStringList &paths)
{
    if (paths.isEmpty())
        return;
    QFile file(paths.at(0));
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    m_filesPath = paths.at(0);
    m_configPathLabel->setText(paths.at(0).split("/").last());

    auto configBody = QJsonDocument::fromJson(file.readAll()).object();
    if (configBody.contains("lastName"))
        m_lastNameLineEdit->setText(configBody.value("lastName").toString());
    if (configBody.contains("firstName"))
        m_firstNameLineEdit->setText(configBody.value("firstName").toString());
    if (configBody.contains("patronymic"))
        m_patronymicLineEdit->setText(configBody.value("patronymic").toString());
    if (configBody.contains("email"))
        m_emailLineEdit->setText(configBody.value("email").toString());
    if (configBody.contains("phone"))
        m_phoneLineEdit->setText(configBody.value("phone").toString());
    if (configBody.contains("city"))
        m_cityLineEdit->setText(configBody.value("city").toString());
    if (configBody.contains("yourCompany"))
        m_yourCompanyNameTextEdit->setText(configBody.value("yourCompany").toString());
    if (configBody.contains("createdAtUtc"))
        m_createdAtUtc = configBody.value("createdAtUtc").toString();
    if (configBody.contains("hardwareHash"))
        m_hardwareHashLineEdit->setText(configBody.value("hardwareHash").toString());

    file.close();
}

QLabel* EditClientDialog::makeLabel(const QString &text)
{
    auto *label = new QLabel(text, m_manualWidget);
    label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
    return label;
};

void EditClientDialog::setType(Type type)
{
    m_type = type;
}

EditClientDialog::Type EditClientDialog::getType() const
{
    return m_type;
}

LicenseModel::LicenseItem EditClientDialog::getLicenseItem() const
{
    LicenseModel::LicenseItem item;
    item.lastName = m_lastNameLineEdit->text().trimmed();
    item.firstName = m_firstNameLineEdit->text().trimmed();
    item.patronymic = m_patronymicLineEdit->text().trimmed();
    item.email = m_emailLineEdit->text().trimmed();
    item.phone = m_phoneLineEdit->text().trimmed();
    item.city = m_cityLineEdit->text().trimmed();
    item.yourCompany = m_yourCompanyNameTextEdit->text().trimmed();
    item.hardwareHash = m_hardwareHashLineEdit->text().trimmed();
    item.createdAtUtc = m_createdAtUtc;
    item.comment = m_commentTextEdit->toPlainText().trimmed();
    return item;
}

void EditClientDialog::clear()
{
    m_firstNameLineEdit->clear();
    m_lastNameLineEdit->clear();
    m_patronymicLineEdit->clear();
    m_emailLineEdit->clear();
    m_phoneLineEdit->clear();
    m_cityLineEdit->clear();
    m_yourCompanyNameTextEdit->clear();
    m_hardwareHashLineEdit->clear();
    m_commentTextEdit->clear();
    m_configPathLabel->setText(tr("Drop file here"));
}

void EditClientDialog::setClientInfo(int index)
{
    if (index < 0 || index >= m_model->rowCount())
        return;

    auto item = m_model->getItem(index);
    m_lastNameLineEdit->setText(item.lastName);
    m_firstNameLineEdit->setText(item.firstName);
    m_patronymicLineEdit->setText(item.patronymic);
    m_emailLineEdit->setText(item.email);
    m_phoneLineEdit->setText(item.phone);
    m_cityLineEdit->setText(item.city);
    m_yourCompanyNameTextEdit->setText(item.yourCompany);
    m_hardwareHashLineEdit->setText(item.hardwareHash);
}
