/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
#include <QSplitter>
#include <QTreeWidget>
#include <QVBoxLayout>
#include <QSettings>

#include "MvQOgcServiceManagerDialog.h"
#include "MvQOgcServiceManager.h"

MvQOgcServiceManagerDialog::MvQOgcServiceManagerDialog(QWidget* parent) :
    QDialog(parent)
{
    // setAttribute(Qt::WA_DeleteOnClose);
    manager_ = 0;

    setWindowTitle("Metview - OGC Server Manager");

    QLabel* label;
    QWidget* w;

    layout_ = new QVBoxLayout;

    setLayout(layout_);

    QSplitter* splitter = new QSplitter;
    layout_->addWidget(splitter);

    // Servers
    QVBoxLayout* vbServer = new QVBoxLayout;
    w = new QWidget;
    w->setLayout(vbServer);
    splitter->addWidget(w);

    label = new QLabel("Servers:");
    vbServer->addWidget(label);

    serverTree_ = new QTreeWidget;
    serverTree_->setColumnCount(2);
    QStringList headers;
    headers << tr("Name") << tr("URL");
    serverTree_->setHeaderLabels(headers);
    vbServer->addWidget(serverTree_);

    // Versions
    QVBoxLayout* vbVersion = new QVBoxLayout;
    w = new QWidget;
    w->setLayout(vbVersion);
    splitter->addWidget(w);

    label = new QLabel("Versions:");
    vbVersion->addWidget(label);

    versionList_ = new QListWidget;
    versionList_->setMaximumWidth(100);
    vbVersion->addWidget(versionList_);

    // Populate versionList
    versions_ << "Default"
              << "1.0.0"
              << "1.1.1"
              << "1.3.0";

    QPushButton* addPb = new QPushButton("Add");
    QPushButton* deletePb = new QPushButton("Delete");

    QHBoxLayout* hb = new QHBoxLayout;
    layout_->addLayout(hb);
    hb->addWidget(addPb);
    hb->addWidget(deletePb);

    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

    layout_->addWidget(buttonBox);


    connect(addPb, SIGNAL(clicked()),
            this, SLOT(slotAddServer()));

    connect(deletePb, SIGNAL(clicked()),
            this, SLOT(slotDeleteServer()));

    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    connect(serverTree_, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
            this, SLOT(slotSelectServer(QTreeWidgetItem*, QTreeWidgetItem*)));
}

void MvQOgcServiceManagerDialog::init(MvQOgcServiceManager* manager)
{
    manager_ = manager;

    QList<QTreeWidgetItem*> items;

    foreach (MvQOgcServer* server, manager_->wms()) {
        QStringList lst;
        lst << server->shortName() << server->url();
        QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)0, lst);
        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled);

        QList<QVariant> versionStatus;
        foreach (QString version, versions_) {
            if (server->versions().contains(version)) {
                versionStatus.push_back(true);
            }
            else {
                versionStatus.push_back(false);
            }
        }

        item->setData(0, Qt::UserRole, versionStatus);

        items.append(item);
    }

    serverTree_->insertTopLevelItems(0, items);

    foreach (QString str, versions_) {
        QListWidgetItem* item = new QListWidgetItem(str, versionList_);
        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
        item->setCheckState(Qt::Checked);
    }

    connect(versionList_, SIGNAL(itemClicked(QListWidgetItem*)),
            this, SLOT(slotVersionStatusChanged(QListWidgetItem*)));
}

void MvQOgcServiceManagerDialog::accept()
{
    QStringList res;

    manager_->clearWms();

    for (unsigned int i = 0; i < serverTree_->topLevelItemCount(); i++) {
        QTreeWidgetItem* item = serverTree_->topLevelItem(i);

        QString name = item->data(0, Qt::DisplayRole).toString();
        QString url = item->data(1, Qt::DisplayRole).toString();
        QList<QVariant> versionStatus = item->data(0, Qt::UserRole).toList();

        QStringList versions;
        for (unsigned int j = 0; j < versions_.count(); j++) {
            if (versionStatus[j].toBool()) {
                versions.push_back(versions_[j]);
            }
        }

        manager_->addWms(new MvQOgcServer(name, url, versions));
    }

    hide();

    emit dataChanged();
}

void MvQOgcServiceManagerDialog::reject()
{
    QDialog::reject();
}

void MvQOgcServiceManagerDialog::slotSelectServer(QTreeWidgetItem* current, QTreeWidgetItem* prev)
{
    int row = serverTree_->indexOfTopLevelItem(current);
    // const QStringList currentVersions = manager_->wms().at(row)->versions();

    QList<QVariant> versionStatus = current->data(0, Qt::UserRole).toList();

    for (unsigned int i = 0; i < versionList_->count(); i++) {
        QListWidgetItem* item = versionList_->item(i);
        if (versionStatus[i].toBool()) {
            item->setCheckState(Qt::Checked);
        }
        else {
            item->setCheckState(Qt::Unchecked);
        }
    }
}

void MvQOgcServiceManagerDialog::slotVersionStatusChanged(QListWidgetItem* item)
{
    QList<QVariant> versionStatus;
    for (unsigned int i = 0; i < versionList_->count(); i++) {
        QListWidgetItem* item = versionList_->item(i);
        if (item->checkState() == Qt::Checked) {
            versionStatus.push_back(true);
        }
        else {
            versionStatus.push_back(false);
        }
    }

    serverTree_->currentItem()->setData(0, Qt::UserRole, versionStatus);
}


void MvQOgcServiceManagerDialog::slotAddServer()
{
    int row = serverTree_->topLevelItemCount();
    QStringList lst;
    lst << "Name"
        << "URL";
    QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)0, lst);
    item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled);

    serverTree_->insertTopLevelItem(row, item);

    QList<QVariant> versionStatus;
    foreach (QString version, versions_) {
        versionStatus.push_back(false);
    }
    item->setData(0, Qt::UserRole, versionStatus);
}

void MvQOgcServiceManagerDialog::slotDeleteServer()
{
    int row = serverTree_->indexOfTopLevelItem(serverTree_->currentItem());

    QTreeWidgetItem* item = serverTree_->takeTopLevelItem(row);
    if (item)
        delete item;
}
