#include "PrefsDialog.h"
//#include "SettingsInfo.h"
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QFileDialog>
#include <QFileInfo>
#include <QSettings>
#include <QMenu>
#include <QDebug>


PrefsDialog::PrefsDialog(QWidget * parent, Qt::WindowFlags f, int tabShowed)
        : QDialog(parent, f)
{
    setupUi(this);

     /* translate buttons in QDialogButtonBox buttonBox */
    QPushButton * bbOkButton = buttonBox->button( QDialogButtonBox::Ok );
    QPushButton * bbCancelButton = buttonBox->button( QDialogButtonBox::Cancel );
    //QPushButton * bbApplyButton = buttonBox->button( QDialogButtonBox::Apply );
    bbOkButton->setText( tr("OK") );
    bbCancelButton->setText( tr("Cancel") );
    //bbApplyButton->setText( tr("Apply") );

    /* context menu for button pbAccountRemove (which in the end has been morphed into a QToolButton) */
    deleteAccountAction = new QAction ( QIcon(":images/fileclose.png"), tr("Delete selected account : sure ?"), this);
    connect( deleteAccountAction, SIGNAL( triggered() ), this, SLOT( pbAccountRemoveClicked() ) );
    QMenu *minu = new QMenu(this);
    minu->addAction(deleteAccountAction);
    pbAccountRemove->setMenu(minu);

    /* context menu for listWidget Items */
    connect( listWidget, SIGNAL( currentRowChanged (int ) ), this, SLOT( listWidgetChanged( int) ) );
    connect( listWidget, SIGNAL( itemDoubleClicked ( QListWidgetItem * ) ), this, SLOT( pbAccountEditClicked() ) );
    connect( pbAccountSave, SIGNAL( clicked () ), this, SLOT( pbAccountSaveClicked() ) );
    connect( pbAccountAdd, SIGNAL( clicked () ), this, SLOT( pbAccountAddClicked() ) );
    connect( pbAccountEdit, SIGNAL( clicked () ), this, SLOT( pbAccountEditClicked() ) );
    connect( pbAccountCancel, SIGNAL( clicked () ), this, SLOT( pbAccountCancelClicked() ) );
    connect( cbSound, SIGNAL( currentIndexChanged( int ) ), this, SLOT( cbSoundChanged(int) ) );
    connect( cbProtocol, SIGNAL( currentIndexChanged( int ) ), this, SLOT( cbProtocolChanged(int) ) );
    connect( checkBoxInbox, SIGNAL( stateChanged( int ) ), this, SLOT( checkBoxInboxChanged(int) ) );
    connect( checkBoxPort, SIGNAL( stateChanged( int ) ), this, SLOT( checkBoxPortChanged(int) ) );
    connect( buttonBox, SIGNAL( accepted () ), this, SLOT( okAccept() ) );
    connect( buttonBox, SIGNAL( rejected () ), this, SLOT( reject() ) );

    restoreSettings();
    listWidgetUpdate();

    if (tabShowed>0)
        tabWidget->setCurrentIndex(tabShowed);
}

void PrefsDialog::okAccept()
{
    QSettings settings;//QSettings settings(settingsFile, QSettings::IniFormat);
    settings.beginGroup("MAIN");
    settings.setValue("check_interval", spCheck->value());
    settings.setValue("first_check", spFirstCheck->value());
    settings.setValue("timeout_duration", spTimeoutDuration->value());
    settings.setValue("popup_duration", spPopupDuration->value());
    settings.setValue("popups", cbPopups->currentIndex());
    settings.setValue("sound", cbSound->currentIndex());
    if ( cbSound->count() > 3 )
        settings.setValue("sound_file", cbSound->itemText(3));
    settings.setValue("email_client", leClient->text().trimmed());
    settings.setValue("email_composer", leComposer->text().trimmed());
    settings.endGroup();

    accept();
}

void PrefsDialog::restoreSettings()
{
     // Get Settings from config file
     QSettings settings;//QSettings settings(settingsFile, QSettings::IniFormat);
     settings.beginGroup("MAIN");
         spCheck->setValue( settings.value("check_interval", 4).toInt() );//imapCheckIntervaltTime = 15;
         spFirstCheck->setValue( settings.value("first_check", 1).toInt() );
         spPopupDuration->setValue( settings.value("popup_duration", 30).toInt() );
         spTimeoutDuration->setValue( settings.value("timeout_duration", 90).toInt() );
         int playSoundOk = settings.value("sound",  1).toInt();
         cbPopups->setCurrentIndex( settings.value("popups",  0).toInt() );
         QString soundFileOther = settings.value("sound_file", "").toString();
         leClient->setText( settings.value("email_client", "thunderbird -mail").toString() );
         leComposer->setText( settings.value("email_composer", "thunderbird -compose").toString() );
     settings.endGroup();

     // Apply settings
     if ( !soundFileOther.isEmpty() )
     {
         if (cbSound->count()<4)
         {
             cbSound->addItem(soundFileOther);
             //qDebug() << "GRINCHEUX";
         }
         else
             cbSound->setItemText(3,soundFileOther);
     }

     cbSound->setCurrentIndex(playSoundOk);
}

void PrefsDialog::pbAccountAddClicked()
{
         QSqlQuery query;
         query.prepare("INSERT INTO accounts (type, name, host, port, user, pwd, check_time, inbox) "
                       "VALUES (:type, :name, :host, :port, :user, :pwd, DATETIME('NOW'), :inbox )");
         query.bindValue(":type", 1);
         query.bindValue(":name", "New_Account");
         query.bindValue(":host", "");
         query.bindValue(":port", 143);
         query.bindValue(":user", "");
         query.bindValue(":pwd", "");
         query.bindValue(":inbox", "");
         query.exec();
         listWidgetUpdate( listWidget->count() );
}

void PrefsDialog::pbAccountRemoveClicked()
{
         QSqlQuery query;
         if ( query.exec("DELETE FROM accounts WHERE id=" + listWidget->currentItem()->data(Qt::UserRole).toString()) )
         {
             //db.close();
             listWidgetUpdate( listWidget->currentRow()-1 );
         }
}

void PrefsDialog::pbAccountSaveClicked()
{
         QSqlQuery query;
         query.prepare("UPDATE accounts SET type=:type, name=:name, host=:host, user=:user, pwd=:pwd, port=:port, inbox=:inbox "
                   "WHERE id=" + listWidget->currentItem()->data(Qt::UserRole).toString());
         query.bindValue(":type", cbProtocol->currentIndex()+1);
         query.bindValue(":name", leName->text().trimmed());
         query.bindValue(":host", leHost->text().trimmed());
         query.bindValue(":user", leUser->text().trimmed());
         query.bindValue(":pwd", lePwd->text());
         if (checkBoxPort->isEnabled())
             query.bindValue(":port", spPort->value());
         else
             query.bindValue(":port", 143);
         query.exec();
          if (checkBoxInbox->isEnabled())
             query.bindValue(":inbox", leInbox->text().trimmed());
         else
             query.bindValue(":inbox", "");
         query.exec();

         toggleAccountEditMode(false);
         listWidgetUpdate(listWidget->currentRow());
     //}
}

void PrefsDialog::pbAccountEditClicked()
{
    toggleAccountEditMode(true);
}

void PrefsDialog::pbAccountCancelClicked()
{
    toggleAccountEditMode(false);
}

void PrefsDialog::toggleAccountEditMode(bool boul)
{
    listWidget->setDisabled(boul);
    pbAccountAdd->setDisabled(boul);
    pbAccountRemove->setDisabled(boul);
    pbAccountEdit->setDisabled(boul);
    buttonBox->setDisabled(boul);

    gbBasic->setEnabled(boul);
    gbMisc->setEnabled(boul);
    pbAccountSave->setEnabled(boul);
    pbAccountCancel->setEnabled(boul);
}

void PrefsDialog::listWidgetChanged(int idx)
{
    if (idx == -1) // accounts list is empty
    {
        cbProtocol->setCurrentIndex(0);
         leName->setText( "" );
         leHost->setText("" );
         spPort->setValue( 143 );
         leUser->setText( "" );
         lePwd->setText( "" );
        leInbox->setText( "" );
         //deleteAccountAction->setText( tr("Delete selected account : sure ?") );
        return;
    }

         QSqlQuery query( "SELECT id, type, name, host, port, user, pwd, inbox FROM accounts WHERE id="
                          + listWidget->item(idx)->data(Qt::UserRole).toString() );

         while (query.next()) {
             cbProtocol->setCurrentIndex( query.value(1).toInt()-1 );
             leName->setText( query.value(2).toString() );
             leHost->setText( query.value(3).toString() );
             spPort->setValue( query.value(4).toInt() );
             leUser->setText( query.value(5).toString() );
             lePwd->setText( query.value(6).toString() );
             leInbox->setText( query.value(7).toString() );
             deleteAccountAction->setText( tr("Delete account '%1' : sure ?").arg(query.value(2).toString()) );
         }

         query.finish();//db.close();

         if (spPort->value() != 143)
             checkBoxPort->setChecked(true);
         else
             checkBoxPort->setChecked(false);

         if (!leInbox->text().isEmpty())
             checkBoxInbox->setChecked(true);
         else
             checkBoxInbox->setChecked(false);
}

void PrefsDialog::listWidgetUpdate(int itemIdx)
{

    listWidget->clear();//INCREDIBLE !!! -> bug sur le clear() avec connect( listWidget, SIGNAL( currentItemChanged ( QListWidgetItem *,  QListWidgetItem * ) )

         QSqlQuery query("SELECT id, name FROM accounts");
         while (query.next()) {
             QListWidgetItem *item = new QListWidgetItem;
             item->setData( Qt::UserRole, query.value(0).toString() );
             item->setText( query.value(1).toString() );
             item->setIcon(QIcon(":images/gaim.png"));

             listWidget->addItem(item);//listWidget->addItem( query.value(0).toString() );
         }
         
		 query.finish();//db.close();

         if ( listWidget->count() < 1 ) // if imap accounts list is empty
         {
             pbAccountRemove->setDisabled(true);
             pbAccountEdit->setDisabled(true);
             gbBasic->setEnabled(false);
         }
         else
         {
             pbAccountRemove->setDisabled(false);
             pbAccountEdit->setDisabled(false);
             listWidget->setCurrentRow(itemIdx);//listWidget->setCurrentItem(listWidget->item(itemIdx));
         }
     //}
}

void PrefsDialog::checkBoxPortChanged(int state)
{
    bool boul=false;

    if (state>0)
        boul = true;

    spPort->setEnabled(boul);
}

void PrefsDialog::checkBoxInboxChanged(int state)
{
    bool boul=false;

    if (state>0)
        boul = true;

    leInbox->setEnabled(boul);
}

void PrefsDialog::cbProtocolChanged(int cbidx)
{
    if (cbidx == 0)
        spPort->setValue(143);
    else if (cbidx == 1)
        spPort->setValue(993);
}

void PrefsDialog::cbSoundChanged(int cbidx)
{
    if (cbidx == 2)
    {
       QString fileName = QFileDialog::getOpenFileName(
               this,
               tr("Open Sound File"),
               QDir::homePath(),
               tr("Sound Files (*.wav)") // tr("Sound Files (*.wav *.mp3 *.ogg)")
               );

        if ( fileName.isEmpty() )
            cbSound->setCurrentIndex(1);
        else if (!QFile::exists(fileName))
            cbSound->setCurrentIndex(1);
        else
        {
            if ( cbSound->count() < 4 )
            {
                cbSound->addItem(fileName);//qDebug() << "SIMPLET";
            }
            else
                cbSound->setItemText(3,fileName);

            cbSound->setCurrentIndex(3);
        }
    }
}
