/***************************************************************************
 *   Copyright (C) 2009 by Emil Beli                                       *
 *   beli0135@gmail.com                                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 3 of the License, or     *
 *   any later version.			                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   License at: http://www.gnu.org/licenses/gpl.html                      *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QDesktopServices>
#include <QUrl>
#include "translation.cpp"
#include "config.h"
#include "ui_config.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);
    connect(ui->btnSource,SIGNAL(clicked()),this,SLOT(onBtnSrcClick()));
    connect(ui->btnDest,SIGNAL(clicked()),this,SLOT(onBtnDestClick()));
    connect(ui->cmbRes,SIGNAL(currentIndexChanged(int)),this,SLOT(onCmbChange()));
    connect(ui->btnStart,SIGNAL(clicked()),this,SLOT(startProcessing()));
    connect(ui->hSlider,SIGNAL(valueChanged(int)),this,SLOT(qualityChanged()));

    this->version = "1.2 R1";
    this->versionId = 121;

    this->currentDestDir = QDir::homePath();
    this->currentSrcDir = QDir::homePath();

    QString s;
    ui->lblQuality->setText(translateMsg(13)+": "+ s.setNum(ui->hSlider->value()));
    LANGUAGE = 1;
    loadSettings();   

    formTranslate();
}

MainWindow::~MainWindow()
{
    this->setCursor(Qt::ArrowCursor);
    saveSettings();
    delete ui;
}

void MainWindow::loadSettings()
{
   QSettings settings("beli.ws","baires");
   ui->edtSource->setText(settings.value("SourceDirectory").toString());
   ui->edtDest->setText(settings.value("DestinationDirectory").toString());
   ui->edtPrefix->setText(settings.value("Prefix").toString());
   ui->spnHeight->setValue(settings.value("SpnHeight").toInt());
   ui->spnWidth->setValue(settings.value("SpnWidth").toInt());
   ui->hSlider->setValue(settings.value("Quality").toInt());


   if (settings.contains("cmbRes"))
   {
       ui->cmbRes->clear();
       QString rezs = settings.value("cmbRes").toString();
       QStringList list = rezs.split(";");
       for (int i=0;i<list.count();++i)
       {
           ui->cmbRes->addItem(list[i]);
       }
   }
   else
   {
       ui->cmbRes->addItem("1024x768");
       ui->cmbRes->addItem("800x600");
       ui->cmbRes->addItem("Custom");
   }
   int idx = settings.value("ResComboIdx").toInt();
   if (idx > ui->cmbRes->count()-1)
   {
       idx = 0;
   }
   ui->cmbRes->setCurrentIndex(idx);

   if (ui->cmbRes->currentText() == "")
   {
       ui->cmbRes->setCurrentIndex(0);
   }

   if (settings.contains("Language"))
   {
        LANGUAGE = settings.value("Language").toInt();
   }
   if (ui->edtPrefix->text() == "")
   {
       ui->edtPrefix->setText("rz_");
   }

   if (ui->hSlider->value() <= 10)
   {
       ui->hSlider->setValue(75);
   }

   if (settings.contains("Types"))
   {
       this->fileTypes = settings.value("Types").toString();  
   }
   else
   {
       this->fileTypes = "*.jpg;*.jpeg";
   }

   if (!settings.contains("VersionId"))
   {      
     this->fileTypes += ";*.jpeg";
   }
   else
   {
     //here, for further versions ( > 112), set new settings, if any
   }

   if ((settings.contains("x"))  && (settings.contains("y")))
   {
       move(settings.value("x").toInt(), settings.value("y").toInt());
   }

   if (settings.contains("Downsize"))
   {
       ui->chkDownsize->setChecked(settings.value("Downsize").toBool());
   }

   if (settings.contains("ForceAspect"))
   {
       ui->chkFoceAspect->setChecked(settings.value("ForceAspect").toBool());
   }



   bool isCustom = (ui->cmbRes->currentText() == "Custom");
   setCustomEnabled(isCustom);

}

void MainWindow::saveSettings()
{
    QSettings settings("beli.ws","baires");
    settings.setValue("SourceDirectory",ui->edtSource->text());
    settings.setValue("DestinationDirectory",ui->edtDest->text());
    settings.setValue("Prefix",ui->edtPrefix->text());
    settings.setValue("ResComboIdx",ui->cmbRes->currentIndex());
    settings.setValue("SpnHeight",ui->spnHeight->value());
    settings.setValue("SpnWidth",ui->spnWidth->value());
    settings.setValue("Quality",ui->hSlider->value());
    settings.setValue("Language",LANGUAGE);
    settings.setValue("Types",this->fileTypes);
    settings.setValue("x",this->geometry().x());
    settings.setValue("y",this->geometry().y());
    settings.setValue("VersionId",this->versionId);
    settings.setValue("Downsize",ui->chkDownsize->isChecked());
    settings.setValue("ForceAspect",ui->chkFoceAspect->isChecked());


    QString cmbVals = "";
    QString item;
    int max = ui->cmbRes->count();
    int curIdx = ui->cmbRes->currentIndex();
    for ( int index = 0; index < max; index++ )
    {
        if (index>0)
        {
            cmbVals += ";";
        }
        item = ui->cmbRes->itemText(index);
        cmbVals += item;
    }
    settings.setValue("cmbRes",cmbVals);
    ui->cmbRes->setCurrentIndex(curIdx);

    settings.sync();
}

void MainWindow::onBtnSrcClick()
{
   QDir dir(ui->edtSource->text());
   QString dirName;

   if ((ui->edtSource->text() == "") || (!dir.exists()))
   {
       dirName = this->currentSrcDir;
   }
   else
   {
       dirName = ui->edtSource->text();
   }
   const char *c_str2 = translateMsg(25).toLatin1().data();
    QString newDirectory = QFileDialog::getExistingDirectory(this, tr(c_str2), dirName);
    if (newDirectory == "")
    {
        newDirectory = this->currentSrcDir;
    }
    ui->edtSource->setText(newDirectory);
    this->currentSrcDir = newDirectory;
    if (ui->edtDest->text() == "")
    {
        ui->edtDest->setText(newDirectory);
        ui->edtDest->setFocus();
    }
}

void MainWindow::onBtnDestClick()
{
   QDir dir(ui->edtDest->text());
   QString dirName;

   if ((ui->edtDest->text() == "") || (!dir.exists()))
   {
       dirName = this->currentDestDir;
   }
   else
   {
       dirName = ui->edtDest->text();
   }
    const char *c_str2 = translateMsg(25).toLatin1().data();
    QString newDirectory = QFileDialog::getExistingDirectory(this, tr(c_str2), dirName);
    if (newDirectory == "")
    {
        newDirectory = this->currentDestDir;
    }
    ui->edtDest->setText(newDirectory);
    this->currentSrcDir = newDirectory;
}

void MainWindow::onCmbChange()
{
    bool en = (ui->cmbRes->currentText() == "Custom");
    setCustomEnabled(en);
}

void MainWindow::qualityChanged()
{
    QString s;
    ui->lblQuality->setText(translateMsg(13)+": "+ s.setNum(ui->hSlider->value()));
}

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

void MainWindow::startProcessing()
{
    abort = false;

    QString srcPath,destPath;
    srcPath = ui->edtSource->text();
    destPath = ui->edtDest->text();

    // Verification
    QDir dirS(srcPath);
    if ((srcPath == "") || (!dirS.exists()))
    {
      this->showError(translateMsg(20),translateMsg(21));
      return;
    }
    QDir dirD(destPath);
    if ((destPath == "") || (!dirD.exists()))
    {
      this->showError(translateMsg(22),translateMsg(21));
      return;
    }
    if ((srcPath == destPath) && (ui->edtPrefix->text() == ""))
    {
      this->showError(translateMsg(23),translateMsg(24));
      return;
    }

    //fill the list with image files
    QDir directory(srcPath);
    QStringList filters;

    QString x = this->fileTypes;
    filters = x.split( ";", QString::SkipEmptyParts );

    directory.setNameFilters(filters);

    QStringList allFiles = directory.entryList(QDir::Files | QDir::NoSymLinks);

    if (srcPath[srcPath.count()] != '/')
    {
        srcPath = srcPath + '/';
    }

    if (destPath[destPath.count()] != '/')
    {
        destPath = destPath + '/';
    }

    //calculate width and height
    Qt::AspectRatioMode aspect = Qt::KeepAspectRatio;
    int iWidth;
    int iHeight;

    if (ui->cmbRes->currentText() == "Custom")
    {
        iWidth = ui->spnWidth->value();
        iHeight = ui->spnHeight->value();
        aspect = Qt::IgnoreAspectRatio;
    }
    else
    {
        QStringList list = QString(ui->cmbRes->currentText()).split("x");
        iWidth = QString(list[0]).toInt();
        iHeight = QString(list[1]).toInt();
    }


    int rWidth;
    int rHeight;
    int val = 0;
    QImage destImg;

    ui->progressBar->setValue(0);
    ui->progressBar->setMaximum(allFiles.count());

    ui->btnAbort->setEnabled(true);
    ui->btnStart->setEnabled(false);

    //process images
    this->setCursor(Qt::BusyCursor);
    foreach (QString file, allFiles)
    {
        QApplication::processEvents();
        if (this->abort)
        {
         this->setCursor(Qt::ArrowCursor);
         showError(translateMsg(32),translateMsg(33));
         break;
        }

        val++;
        ui->progressBar->setValue(val);
        QImage *image = new QImage(srcPath + file);


        if (ui->chkFoceAspect->isChecked() && (ui->cmbRes->currentText() == "Custom"))
        {
            iHeight = int((iWidth * image->height()) / image->width()) ;
            aspect = Qt::KeepAspectRatio;
        }


        if (((ui->chkDownsize->isChecked()) && ((image->width()+image->height()) > (iWidth+iHeight))) || (!ui->chkDownsize->isChecked()))
        {
            if ((image->width() / image->height()) < 1)
            {
                rWidth = iHeight;
                rHeight = iWidth;
            }
            else
            {
                rWidth = iWidth;
                rHeight = iHeight;
            }
            destImg =  image->scaled(rWidth, rHeight, aspect, Qt::SmoothTransformation);
            destImg.save(destPath +ui->edtPrefix->text()+file, 0, ui->hSlider->value());
        }
        delete image;

    }
    this->setCursor(Qt::ArrowCursor);
    ui->btnAbort->setEnabled(false);
    ui->btnStart->setEnabled(true);
}

void MainWindow::on_actionE_xit_triggered()
{
    this->close();
}

void MainWindow::on_actionOnline_Help_triggered()
{
  QString ext = "";
  if (LANGUAGE == 1)
  {
      ext = "en";
  }
  else if (LANGUAGE == 2)
  {
      ext = "sr";
  }
  else if (LANGUAGE == 3)
  {
      ext = "br";
  }
  else if (LANGUAGE == 4)
  {
      ext = "de";
  }
  else if (LANGUAGE == 5)
  {
      ext="it";
  }
  else if (LANGUAGE == 6)
  {
      ext="hu";
  }
  else if (LANGUAGE == 7)
  {
      ext="fr";
  }
  else if (LANGUAGE == 8)
  {
      ext="ru";
  }

  QUrl url("http://www.beli.ws/apps/baires/help/baires_"+ext+".html");
  QDesktopServices::openUrl(url);
}

void MainWindow::on_action_About_triggered()
{
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Information) ;
    msgBox.setText("Baires - Batch Image Resizer");
    QString info = translateMsg(15)+"\n\n";
    info+= translateMsg(16);
    info+=this->version ;
    info+="\n"+translateMsg(17)+"Emil Beli\n";
    info+=translateMsg(18)+"beli0135@gmail.com\n\n";
    info+=translateMsg(19)+"GNU/GPL v3\n";
    info+="\nDeutsch: Thomas Spahni";
    info+="\nItaliano: Lorenzo Cogotti";
    info+="\nMagyar: Andras Dosztal";
    info+=QString("\nFran")+QChar(0x00E7)+QString("ais: Jean-Baka Domelevo Entfellner and");
    info+="\n              Jean-Christophe Helary for Traduc.org";
    info+="\nRuski: Gnakov";

    msgBox.setInformativeText(info);
    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.setDefaultButton(QMessageBox::Ok);
    msgBox.exec();
}


void MainWindow::formTranslate()
{
    qualityChanged();
    ui->menu_File->setTitle(translateMsg(1));
    ui->menu_Help->setTitle(translateMsg(2));
    ui->actionE_xit->setText(translateMsg(3));
    ui->actionOnline_Help->setText(translateMsg(4));
    ui->action_About->setText(translateMsg(5));
    ui->btnDest->setText(translateMsg(6));
    ui->btnSource->setText(translateMsg(6));
    ui->lblSource->setText(translateMsg(7));
    ui->lblDest->setText(translateMsg(8));
    ui->lblResizeto->setText(translateMsg(9));
    ui->lblWidth->setText(translateMsg(10));
    ui->lblHeight->setText(translateMsg(11));
    ui->lblPrefix->setText(translateMsg(12));
    ui->btnStart->setText(translateMsg(14));
    ui->actionSe_ttings->setText(translateMsg(26));
    ui->btnAbort->setText(translateMsg(34));
    ui->btnAdd->setToolTip(translateMsg(35));
    ui->chkDownsize->setText(translateMsg(36));
    ui->chkFoceAspect->setText(translateMsg(37));
}

void MainWindow::on_actionSe_ttings_triggered()
{
    saveSettings();
    config cfg;
    cfg.setWindowTitle(translateMsg(26));
    cfg.m_ui->lblLanguage->setText(translateMsg(27));
    cfg.m_ui->btnRemove->setText(translateMsg(30));
    cfg.m_ui->groupBox->setTitle(translateMsg(28));
    cfg.m_ui->lblRemove->setText(translateMsg(29));
    cfg.m_ui->cmbLanguage->setCurrentIndex(LANGUAGE-1);

    QString item;
    int max = ui->cmbRes->count();
    cfg.m_ui->listSize->clear();
    for ( int index = 0; index < max; index++ )
    {
       item = ui->cmbRes->itemText(index);
       if ((item != "1024x768") && (item != "800x600") && (item != "Custom"))
       {
           cfg.m_ui->listSize->addItem(item);
       }
    }
    cfg.m_ui->chkBmp->setChecked(false);
    cfg.m_ui->chkJpg->setChecked(false);
    cfg.m_ui->chkPng->setChecked(false);
    cfg.m_ui->chkTif->setChecked(false);
    QStringList filters = this->fileTypes.split( ";", QString::SkipEmptyParts );
    for (int i=0; i <  filters.count(); i++)
    {
        if (filters[i] == "*.jpg")
        {
            cfg.m_ui->chkJpg->setChecked(true);
        }
        if (filters[i] == "*.bmp")
        {
            cfg.m_ui->chkBmp->setChecked(true);
        }
        if (filters[i] == "*.png")
        {
            cfg.m_ui->chkPng->setChecked(true);
        }
        if (filters[i] == "*.tif")
        {
            cfg.m_ui->chkTif->setChecked(true);
        }
    }
    cfg.exec();
    loadSettings();
    formTranslate();
}

void MainWindow::on_btnAdd_clicked()
{
    int w = ui->spnWidth->value();
    int h = ui->spnHeight->value();
    QString size = QString::number(w)+"x"+QString::number(h);
    QString item;
    bool found = false;
    int max = ui->cmbRes->count();

    for ( int index = 0; index < max; index++ )
    {
       item = ui->cmbRes->itemText(index);
       if (item == size)
       {
           found = true;
           break;
       }
    }
    if (!found)
    {
        ui->cmbRes->addItem(size);
        ui->cmbRes->setCurrentIndex(ui->cmbRes->count()-1);
        setCustomEnabled(false);
    }
}

void MainWindow::setCustomEnabled(bool enable)
{
    ui->spnHeight->setEnabled(enable);
    ui->spnWidth->setEnabled(enable);
    ui->lblHeight->setEnabled(enable);
    ui->lblWidth->setEnabled(enable);
    ui->btnAdd->setEnabled(enable);
    ui->chkFoceAspect->setEnabled(enable);
    if (ui->chkFoceAspect->isEnabled())
    {
        ui->lblHeight->setEnabled(!ui->chkFoceAspect->isChecked());
        ui->spnHeight->setEnabled(!ui->chkFoceAspect->isChecked());
    }
}

void MainWindow::on_btnAbort_clicked()
{
    this->abort = true;
}

void MainWindow::on_chkFoceAspect_clicked()
{
    if (ui->chkFoceAspect->isEnabled())
    {
        ui->lblHeight->setEnabled(!ui->chkFoceAspect->isChecked());
        ui->spnHeight->setEnabled(!ui->chkFoceAspect->isChecked());
    }
}
