#include "dossiers.h"
#include "CApp.h"
#include <QDir>
#include <QTextDocument>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QDebug>

DossiersEnCours::DossiersEnCours(QWidget * parent)
{
    setupUi(this);
    m_resources = CApp::pCApp()->pathAppli()+"Ressources";
    setCombo();
    setWindowFlags(Qt::WindowStaysOnTopHint );
    displayFile(dossiersBox->currentText());
    connect(quitButton,SIGNAL(pressed()),this,SLOT(close()));
    connect(deleteButton,SIGNAL(pressed()),this,SLOT(deleteFile()));
    //connect(dossiersBox,SIGNAL(highlighted(const QString &)),this,SLOT(displayFile(const QString &)));
    //connect(dossiersBox,SIGNAL(currentIndexChanged(const QString &)),this,SLOT(displayFile(const QString &)));
    connect(dossiersBox,SIGNAL(activated(const QString &)),this,SLOT(displayFile(const QString &)));
}

DossiersEnCours::~DossiersEnCours(){}

void DossiersEnCours::setCombo()
{
    if (dossiersBox->count()>0)
    {
          dossiersBox->clear();
        }
    QDir dir(m_resources+"/dossiers_a_traiter");
    if (!dir.exists())
    {
          QMessageBox::warning(0,trUtf8("Erreur"),m_resources+"/dossiers_a_traiter"+trUtf8("n'existe pas.'"),QMessageBox::Ok);
        }
    dir.setFilter(QDir::Files);
    QStringList fileslist;
    fileslist = dir.entryList();
    int i = 0;
    foreach(QString file,fileslist){
        QString simplifiedNameFile = file;
        if (file.contains(QDir::separator()))
        {
              simplifiedNameFile = file.split(QDir::separator()).last();
            }
         m_hashIntFiles.insert(i,simplifiedNameFile);
        dossiersBox->addItem(simplifiedNameFile);
        }
}

void DossiersEnCours::deleteFile()
{
    QString filename = m_resources+QDir::separator()+"dossiers_a_traiter"+QDir::separator()+dossiersBox->currentText();
    QFile file(filename);
    if (file.remove())
    {
          QMessageBox::information(0,trUtf8("Info"),trUtf8("Le fichier a été effacé : ")+file.fileName(),QMessageBox::Ok);
          setCombo();
          displayFile(dossiersBox->currentText());
        }
}

void DossiersEnCours::displayFile(const QString & fileName)
{
    QStringList textlist;
    QString text;
    QFile file(m_resources+QDir::separator()+"dossiers_a_traiter"+QDir::separator()+fileName);
    if (!file.open(QIODevice::ReadWrite|QIODevice::Text))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open file : " << fileName ;
          return;
        }
    QTextStream stream(&file);
    while (!stream.atEnd())
    {
        QString line = stream.readLine();
        textlist << line;
        }
    text = textlist.join("\n");
    QTextDocument *doc = new QTextDocument;
    doc->setPlainText(text);
    textEdit->setDocument(doc);
}
