#include "profiles.h"
#include "ui_profiles.h"
#include "objects.h"
#include <QMessageBox>
#include <QSettings>
#include <QInputDialog>

profiles::profiles(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::profiles)
{
    m_ui->setupUi(this);
    setWindowTitle("Profile management");
    selectToIdx = -1;

}


void profiles::initialize()
{
    editing = false;
    newProfile = false;
    adjustScreen();
    m_ui->btnNew->setFocus();

    profileList.clear();   
    QSettings settings("beli.ws","emoc");
    int size = settings.beginReadArray("profiles");
    for (int i = 0; i < size; ++i)
    {
        settings.setArrayIndex(i);
        Profile prf;
        prf.additional = settings.value("additional").toString();
        prf.bitrate = settings.value("bitrate").toInt();
        prf.bitrateIdx = settings.value("bitrateIdx").toInt();
        prf.height = settings.value("height").toInt();
        prf.join = settings.value("join").toBool();
        prf.outputFormat = settings.value("outputFormat").toInt();
        prf.profileName = settings.value("profileName").toString();
        prf.sizeIdx = settings.value("sizeIdx").toInt();
        prf.width = settings.value("width").toInt();
        profileList.append(prf);
    }
    settings.endArray();

    loadProfileListView();
    if (selectToIdx > -1)
    {
        m_ui->lstProfiles->setCurrentRow(selectToIdx);
    }
}

void profiles::loadProfileListView()
{
    m_ui->lstProfiles->clear();
    int size = profileList.count();
    Profile p;
    for (int i = 0; i < size; ++i)
    {
        p = profileList.at(i);
        m_ui->lstProfiles->addItem(p.profileName);
    }
}

profiles::~profiles()
{
    saveProfiles();
    delete m_ui;
}

void profiles::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


void profiles::adjustScreen()
{
    m_ui->btnDelete->setEnabled(!editing);
    m_ui->btnEdit->setEnabled(!editing);
    m_ui->btnDelete->setEnabled(!editing);
    m_ui->frame->setEnabled(editing);
    m_ui->lblAdditional->setEnabled(editing);
    m_ui->lblBitrate->setEnabled(editing);
    m_ui->lblHeight->setEnabled(editing && (m_ui->cmbSize->currentIndex()==1));
    m_ui->lblWidth->setEnabled(editing && (m_ui->cmbSize->currentIndex()==1));
    m_ui->lblOutput->setEnabled(editing);
    m_ui->lblSize->setEnabled(editing);
    m_ui->edtAdditional->setEnabled(editing);
    m_ui->chkJoin->setEnabled(editing);
    m_ui->cmbBitrate->setEnabled(editing);
    m_ui->cmbFormat->setEnabled(editing);
    m_ui->cmbSize->setEnabled(editing);
    m_ui->btnCancel->setEnabled(editing);
    m_ui->btnSave->setEnabled(editing);
    m_ui->btnClose->setEnabled(!editing);
    m_ui->lstProfiles->setEnabled(!editing);
    m_ui->btnNew->setEnabled(!editing);

    m_ui->edtName->setEnabled(editing && newProfile);
    m_ui->lblProfile->setEnabled( m_ui->edtName->isEnabled());
}

void profiles::on_btnClose_clicked()
{
    close();
}

void profiles::on_btnCancel_clicked()
{
    editing = false;
    newProfile = false;
    adjustScreen();
}

void profiles::on_btnNew_clicked()
{
    newProfile = true;
    editing = true;
    adjustScreen();
    m_ui->chkJoin->setChecked(false);
    m_ui->cmbBitrate->setCurrentIndex(0);
    m_ui->cmbFormat->setCurrentIndex(0);
    m_ui->cmbSize->setCurrentIndex(0);
    m_ui->edtAdditional->setText("");
    m_ui->edtName->setText("");
    m_ui->spnBitrate->setValue(0);
    m_ui->spnHeight->setValue(0);
    m_ui->spnWidth->setValue(0);
    m_ui->cmbFormat->setFocus();
}

Profile profiles::getProfileDataFromScreen()
{
    Profile prf;
    prf.additional = m_ui->edtAdditional->text();
    prf.bitrate = m_ui->spnBitrate->value();
    prf.bitrateIdx = m_ui->cmbBitrate->currentIndex();
    prf.height = m_ui->spnHeight->value();
    prf.width = m_ui->spnWidth->value();
    prf.join = m_ui->chkJoin->isChecked();
    prf.outputFormat = m_ui->cmbFormat->currentIndex();
    prf.profileName = m_ui->edtName->text();
    prf.sizeIdx = m_ui->cmbSize->currentIndex();

    if (prf.bitrate < 0)
        prf.bitrate = 0;
    if (prf.bitrateIdx < 0)
        prf.bitrateIdx = 0;
    if (prf.sizeIdx < 0)
        prf.sizeIdx = 0;
    if (prf.width < 0)
        prf.width = 0;
    if (prf.height < 0)
        prf.height = 0;
    if (prf.outputFormat < 0)
        prf.outputFormat = 0;

    return prf;
}

void profiles::showError(QString text, QString info)
{
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Critical);
    msgBox.setText(text);
    msgBox.setInformativeText(info);
    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.setDefaultButton(QMessageBox::Ok);
    msgBox.exec();
}

void profiles::on_cmbBitrate_currentIndexChanged(int index)
{
    if (index == 0)
    {
        m_ui->spnBitrate->setValue(0);
    }
    adjustScreen();
}

void profiles::on_cmbSize_currentIndexChanged(int index)
{
    if (index == 0)
    {
        m_ui->spnHeight->setValue(0);
        m_ui->spnWidth->setValue(0);
    }
    adjustScreen();
}

// main save profile function
void profiles::on_btnSave_clicked()
{
    Profile prf = getProfileDataFromScreen();

    if (prf.profileName == "")
    {
        showError("Incomplete profile settings","Profile name must be chosen");
        return;
    }
    else if (newProfile)
    {
        Profile p;
        for (int i=0; i<profileList.count(); i++)
        {
            p = profileList.at(i);
            if (prf.profileName == p.profileName)
            {
                showError("Invalid profile settings","Profile name already exists");
                return;
            }
        }
    }

    if ((prf.bitrateIdx == 0) && (!prf.join) && (prf.outputFormat == 0) && (prf.sizeIdx == 0) && (prf.additional == ""))
    {
        showError("Incomplete profile settings","Nothing chosen to be done with this profile");
        return;
    }

    if ((prf.bitrateIdx > 0) && (prf.bitrate == 0))
    {
        showError("Invalid profile settings", "Choosing SET, bitrate must be > 0");
        return;
    }

    if ((prf.sizeIdx > 0) && ((prf.width == 0) || (prf.height == 0)))
    {
        showError("Invalid profile settings", "Choosing SET, Width and Height must be > 0");
        return;
    }

    if (newProfile)
    {
        profileList.append(prf);
        m_ui->lstProfiles->addItem(prf.profileName);
    }
    else
    {
        Profile p;
        for (int i=0; i<profileList.count(); ++i)
        {
            p = profileList.at(i);
            if (prf.profileName == p.profileName)
            {
                profileList.replace(i,prf);
                break;
            }
        }
    }

    editing = false;
    newProfile = false;
    adjustScreen();
}

void profiles::saveProfiles()
{
    QSettings settings("beli.ws","emoc");
    settings.beginWriteArray("profiles");
    settings.endArray();
    settings.beginWriteArray("profiles");
    for (int i = 0; i < profileList.count(); ++i)
    {
        Profile prof = profileList.at(i);
        settings.setArrayIndex(i);
        settings.setValue("additional",prof.additional);
        settings.setValue("bitrate",prof.bitrate);
        settings.setValue("bitrateIdx",prof.bitrateIdx);
        settings.setValue("height",prof.height);
        settings.setValue("join",prof.join);
        settings.setValue("outputFormat",prof.outputFormat);
        settings.setValue("profileName",prof.profileName);
        settings.setValue("sizeIdx",prof.sizeIdx);
        settings.setValue("width",prof.width);
    }
    settings.endArray();
    settings.sync();
}


void profiles::on_btnDelete_clicked()
{
    if (m_ui->lstProfiles->selectedItems().count() == 0)
    {
        showError("Item deletion", "You have to select an item to be deleted");
        return;
    }

    int r = QMessageBox::question(this, tr("Confirmation"),
                        tr("Do you wish to delete selected profile?"),
                        QMessageBox::Yes | QMessageBox::No);
    if (r == QMessageBox::No)
    {
        return;
    }

    Profile p;
    QString item =  m_ui->lstProfiles->currentItem()->text();
    for (int i=0; i<profileList.count(); i++)
    {
       p = profileList.at(i);
       if (item == p.profileName)
       {
         profileList.removeAt(i);
         break;
       }
    }
    loadProfileListView();
}

void profiles::on_btnEdit_clicked()
{
    if (m_ui->lstProfiles->selectedItems().count() == 0)
    {
        showError("Item deletion", "You have to select an item to be deleted");
        return;
    }

    Profile p;
    QString item =  m_ui->lstProfiles->currentItem()->text();
    for (int i=0; i<profileList.count(); i++)
    {
       p = profileList.at(i);
       if (item == p.profileName)
       {
         m_ui->edtAdditional->setText(p.additional);
         m_ui->spnBitrate->setValue(p.bitrate);
         m_ui->cmbBitrate->setCurrentIndex(p.bitrateIdx);
         m_ui->spnHeight->setValue(p.height);
         m_ui->spnWidth->setValue(p.width);
         m_ui->chkJoin->setChecked(p.join);
         m_ui->cmbFormat->setCurrentIndex(p.outputFormat);
         m_ui->edtName->setText(p.profileName);
         m_ui->cmbSize->setCurrentIndex(p.sizeIdx);

         editing = true;
         adjustScreen();
         break;
       }
    }
}

void profiles::on_btnRename_clicked()
{
    if (m_ui->lstProfiles->selectedItems().count() == 0)
    {
        showError("Renaming item", "You have to select an item to be renamed");
        return;
    }
    QString item =  m_ui->lstProfiles->currentItem()->text();
    bool ok;
    QString r = QInputDialog::getText(this,"Rename profile","Enter new name",QLineEdit::Normal,item,&ok);

    if (ok && (r == ""))
    {
        showError("Rename error", "New name cannot be empty");
        return;
    }
    if (!ok)
    {
        return;
    }

    Profile p;

    for (int i=0; i<profileList.count(); i++)
    {
       p = profileList.at(i);
       if (item == p.profileName)
       {
           p.profileName = r;
           profileList.replace(i,p);
           m_ui->lstProfiles->currentItem()->setText(r);
           break;
       }
   }

}

void profiles::on_cmbFormat_currentIndexChanged(int index)
{
    QString addon = m_ui->edtAdditional->text();
    int whr;
    if (index == 4)
    {
        whr = addon.indexOf("-ar");
        if (whr >= 0)
        {
            return;
        }
        else
        {
            if (addon != "")
                addon += " ";
            addon += "-ar 44100";
        }
    }
    else
    {
        whr = addon.indexOf("-ar 44100");
        addon.replace(whr,9,"");
    }
    m_ui->edtAdditional->setText(addon);
}
