/****************************************************************************
 ** Copyright (C) 2008-2013 Grigory A. Mozhaev <zcrendel@gmail.com>
 **
 ** This file is part of QMultiRecord (http://qt-apps.org/content/show.php?content=106254).
 **
 ** This file may be used under the terms of the GNU General Public
 ** License version 2.0 as published by the Free Software Foundation
 ** and appearing in the file LICENSE.GPL included in the packaging of
 ** this file.  Please review the following information to ensure GNU
 ** General Public Licensing requirements will be met:
 ** http://www.trolltech.com/products/qt/opensource.html
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 ****************************************************************************/

#include <QMessageBox>
#include <QFileDialog>

#include "application.h"
#include "drivestablemodel.h"
#include "checkableitemdelegate.h"
#include "dvdmodel.h"
#include "settingsdialog.h"

SettingsDialog::SettingsDialog(QWidget *parent)
    : QDialog(parent)
    , m_drivesConfigChanged(false)
{
    setupUi(this);

    m_model = new DrivesTableModel;
#if HAVE_QT5
    connect(m_model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)),
            this, SLOT(drivesModelDataChanged(const QModelIndex &, const QModelIndex &)));
#else
    connect(m_model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),
            this, SLOT(drivesModelDataChanged(const QModelIndex &, const QModelIndex &)));
#endif
    drivesTableView->setModel(m_model);
    drivesTableView->setColumnHidden(3, true);
    drivesTableView->setItemDelegate(new NoFocusItemDelegate(drivesTableView));
    drivesTableView->setItemDelegateForColumn(0, new CheckableItemDelegate(Qt::AlignCenter, drivesTableView));
    drivesTableView->horizontalHeader()->setStretchLastSection(1);

    drivesTableView->setColumnWidth(0, 30);
    drivesTableView->setColumnWidth(1, 150);
    drivesTableView->setColumnWidth(2, 250);

    /**** setup paths ****/
    pathsListWidget->clear();

    QSettings settings;
    QStringList paths = settings.value("paths").toStringList();
    qDebug() << paths;
    for (int i=0; i < paths.count(); i++) {
        QString path = paths.at(i);

        Q_ASSERT(!path.isEmpty());

        bool disabled = false;
        if (path.at(0) == '>') {
            disabled = true;
            path.remove(0, 1);
        }

        QListWidgetItem *item = new QListWidgetItem(path);
        item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        item->setCheckState(disabled ? Qt::Unchecked : Qt::Checked);

        pathsListWidget->addItem(item);
    }
    /********/

    updateButtons();
}

bool SettingsDialog::drivesConfigChanged() const {
    return m_drivesConfigChanged;
}

void SettingsDialog::on_addPathButton_clicked() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select directory with ISO collection"), QDir::homePath());
    if (!dir.isEmpty()) {
        QListWidgetItem *item = new QListWidgetItem(dir);
        item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        item->setCheckState(Qt::Checked);
        pathsListWidget->addItem(item);
    }
}

void SettingsDialog::on_removePathButton_clicked() {
    if ((pathsListWidget->currentRow() >= 0)
        && (pathsListWidget->currentRow() < pathsListWidget->count())) {
        delete pathsListWidget->takeItem(pathsListWidget->currentRow());
    }
}

void SettingsDialog::closeEvent(QCloseEvent *event) {
    setResult(QDialog::Rejected);

    QDialog::closeEvent(event);
}

/*#if HAVE_QT5
void SettingsDialog::drivesModelDataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int> & roles)
{
    Q_UNUSED(topLeft)
    Q_UNUSED(bottomRight)
    Q_UNUSED(roles)

    updateButtons();
}
#else*/
void SettingsDialog::drivesModelDataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight)
{
    Q_UNUSED(topLeft)
    Q_UNUSED(bottomRight)

    updateButtons();
}
//#endif

void SettingsDialog::updateButtons() {
    bool enabled = false;

    for (int i=0; i < m_model->rowCount(); i++) {
        if (m_model->item(i, 0)->data(Qt::CheckStateRole).toBool()) {
            enabled = true;
        }
    }

    buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enabled);
}

void SettingsDialog::accept() {
    bool changed = false;

    QStringList activeDrives;
    for (int i=0; i < m_model->rowCount(); i++) {
        DvdModel *drive = DvdModel::devicesByFile(m_model->item(i, 1)->text());
        bool driveEnabled = m_model->item(i, 0)->data(Qt::CheckStateRole).toBool();
        if (driveEnabled != drive->enabled()) {
            changed = true;
        }
        drive->setEnabled(driveEnabled);
        if (drive->enabled()) {
            activeDrives << drive->deviceFile();
        }
    }

    m_drivesConfigChanged = changed;

    QStringList paths;
    for (int i=0; i < pathsListWidget->count(); i++) {
        QListWidgetItem *item = pathsListWidget->item(i);

        QString path = item->text();

        if (item->checkState() == Qt::Unchecked) {
            path = QLatin1Char('>') + path;
        }

        paths << path;
    }

    QSettings settings;
    settings.setValue("drives", activeDrives);
    settings.setValue("paths", paths);

    QDialog::accept();
}
