#include "result.h"
#include "constants.h"
#include <QTextDocument>
#include <QMessageBox>
#include <QDebug>
#include <QPrintDialog>
#include <QPrinter>
#include <QFile>
#include <QTextStream>

using namespace Constants;

Result::Result(QObject * parent)
{
    setupUi(this);
    setWindowModality(Qt::NonModal);
    numberOfResultsLabel->setText("");
    m_model = new QStandardItemModel(0,FieldsModelResults_MaxParam,this);
    tableView->setModel(m_model);
    connect(deleteButton,SIGNAL(pressed()),this,SLOT(deleteLineOfResultsModel()));
    connect(printButton,SIGNAL(pressed()),this,SLOT(printTable()));
}

Result::~Result(){}

void Result::setResults(QHash<QString,QString> hashResults)
{
    enum NameFirstname
    {
        HASH_NAME=0,
        HASH_FIRSTNAME
        };
    QStringList listOffNames;
    QStringList listOffFirstnames;    
    QStringList listOffIds;
    QFile file(qApp->applicationDirPath()+"/../resources/fichieroff");
    if (!file.open(QIODevice::ReadOnly))
    {
    	qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open fileoff" ;
        }
    QTextStream stream(&file);
    while (!stream.atEnd())
    {
    	QString line = stream.readLine();
    	QStringList l;
    	l = line.split(";",QString::SkipEmptyParts);
    	listOffNames << l[NAME_RESULTS];
    	listOffFirstnames << l[FIRSTNAME_RESULTS];
    	listOffIds << l[ID_RESULTS];    	
        }
    QString results;
    for (int i = 0; i < hashResults.count(); ++i)
    {
          QString id = hashResults.keys()[i];
          QString nameFirstname = hashResults.values()[i];
          QStringList namelist = nameFirstname.split(";");
          QString name;
          QString firstname;
          if (namelist.size()>1)
          {
                name = namelist[HASH_NAME];
                firstname = namelist[HASH_FIRSTNAME];
              }
           if (listOffNames.contains(name)&& listOffFirstnames.contains(firstname)&& listOffIds.contains(id))
           {
           	continue;
               }
           QStandardItem * itName = new QStandardItem(id);
           QStandardItem * itFirstName = new QStandardItem(name);
           QStandardItem * itId = new QStandardItem(firstname);
           QList<QStandardItem*> list;
           list << itName << itFirstName << itId;
           m_model->appendRow(list);
           m_listOfReturnedId << id;
        }
    QString numberOfResults = trUtf8("Nombre de dossiers = ")+QString::number(m_listOfReturnedId.count());
    numberOfResultsLabel->setText(numberOfResults);
}

void Result::deleteLineOfResultsModel()
{
    QModelIndex index = tableView->currentIndex();
    int row = index.row();
    QString ident;
    qDebug() << __FILE__ << QString::number(__LINE__) << " deleterow =" << QString::number(row) ;
    QFile file(qApp->applicationDirPath()+"/../resources/fichieroff");
    if (!file.open(QIODevice::ReadWrite|QIODevice::Append))
    {
    	qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open fileoff" ;
        }
    QTextStream stream(&file);
    for (int i = 0; i < IndexNomPrenomFields_MaxParam; i += 1)
    {
    	ident += m_model->data(m_model->index(row,i),Qt::DisplayRole).toString()+";";
    }
    if (!ident.isEmpty())
    {
    	stream << ident+"\n";
        }
    m_model->removeRows(row,1,QModelIndex());
    if (!m_model->submit())
    {
          QMessageBox::warning(0,trUtf8("Warning"),trUtf8("Unable to delete row."),QMessageBox::Ok);
        }
}

QStringList Result::getListOfId()
{
    return m_listOfReturnedId;
}

void Result::printTable()
{
    QString htmlDocument = "<html><body><font size=3>";
    htmlDocument += "<TABLE BORDER=1>";
    htmlDocument += "<CAPTION><font color = red size = 6>"+trUtf8("Liste des patients concernés")+"</font></CAPTION>";
    htmlDocument += "<TR>";
    htmlDocument += "<TH><font color = blue><bold>"+tr("Nom")+"</bold></font></TH>";
    htmlDocument += "<TH><font color = blue><bold>"+tr("Prénom")+"</bold></font></TH>";
    htmlDocument += "<TH><font color = blue><bold>"+tr("ID")+"</bold></font></TH>";
    htmlDocument += "</TR>";
    for (int row = 0; row < m_model->rowCount(); ++row)
    {
          htmlDocument += "<TR>";
          for (int col = 0; col < FieldsModelResults_MaxParam; ++col)
          {
              htmlDocument += "<TD>";
              htmlDocument += m_model->data(m_model->index(row,col),Qt::DisplayRole).toString();
              htmlDocument += "</TD>";
              }
           htmlDocument += "</TR>";
        }
    htmlDocument += "</TABLE>";
    htmlDocument += "<BR/>";
    htmlDocument += tr("nombre = ")+QString::number(m_model->rowCount());
    htmlDocument += "</font></body></html>";
    QTextDocument *doc = new QTextDocument(this);
    doc->setHtml(htmlDocument);
    QPrinter *printer = new QPrinter;
    QPrintDialog *printdialog = new QPrintDialog(printer,this);
    printdialog               ->setWindowTitle(tr("Imprimer"));
    printdialog               ->exec();
    doc->print(printer);
}
