#include "comptatrieemainwindow.h"
#include "../grand_livre/grandlivre.h"
#include "../frenchTax/frenchTax.h"
#include "../recettestriees/recettestriees.h"
#include "../depensestriees/depensestriees.h"
#include "../etatdesdus/etatdesdus.h"
#include "../../setup/wiz1.h"
#include "../../notes/notes.h"
#include "../../comptabilite_interfaces_src/immobilisations/immobilisations.h"
#include "../../comptabilite_interfaces_src/immobilisations/NouvelleImmobilisation.h"
#include "../../comptabilite_interfaces_src/parametrages/parametrages.h"
#include "../../comptabilite_interfaces_src/depensedialog/depensedialog.h"
#include "../../comptabilite_interfaces_src/depensedialog/utilisateurdialog.h"
#include "../../comptabilite_interfaces_src/recettedialog/recettedialog.h"
#include "../../comptabilite_interfaces_src/recettedialog/modifierrecette.h"
#include "../../comptabilite_interfaces_src/recettedialog/rafraichirdialog.h"
#include "../../comptabilite_interfaces_src/bank/deposit.h"

#include <common/icore.h>
#include <common/settings.h>
#include <common/commandlineparser.h>
#include <common/constants.h>
#include <common/databasemanager.h>
#include <common/position.h>
#include <common/configure/help.h>
#include <common/configure/utilisateur.h>

#include <QProcess>
#include <QString>
#include <QDir>
#include <QApplication>
#include <QMessageBox>
#include <QDebug>

using namespace Common;
using namespace Constants;

static inline Common::Settings *settings() {return Common::ICore::instance()->settings();}
static inline Common::CommandLine *commandLine() {return Common::ICore::instance()->commandLine();}
static inline Common::DatabaseManager *databaseManager() {return Common::ICore::instance()->databaseManager();}
static inline Common::Position *position() {return Common::ICore::instance()->position();}
static inline QString patientUUID() {return commandLine()->value(Common::CommandLine::CL_PatientUUID).toString();}

static inline QString getProcessFullPath(const QString &process)
{
#ifdef Q_OS_MAC
    return settings()->applicationBundlePath() + QDir::separator() + process + ".app/Contents/MacOs/" + process;
#else
    return settings()->applicationBundlePath() + QDir::separator() + process;
#endif
}

comptatriee::comptatriee() :
        mFile(0),
        mAnalyse(0),
        mInterfaces(0),
        mSettings(0),
        mHelp(0),
        m_fermer(0),
        m_tridesrecettes(0),
        m_etatsdesdus(0),
        m_recettes(0),
        m_depenses(0),
        m_grandLivre(0),
        m_immobilisations(0),
        m_setup(0),
        m_parametres(0),
        m_error(0),
        m_bankAndUsers(0),
        m_bankDeposits(0),
        m_notes(0)
{
    setupUi(this);
    qDebug() << __FILE__ << QString::number(__LINE__) ;
    position()->centralPosition(this,width(),height());
    QBrush brush(QImage(settings()->iconPath()+"/la_comptabilite.png"));
    qDebug() << __FILE__ << " " << settings()->iconPath()+"/la_comptabilite.png";
    mdiArea->setBackground(brush);
    createMenus();
    createActions();
    connectActions();

    // TESTS
    //databaseManager()->connectDrTux(DatabaseManager::Driver_MySQL);
    databaseManager()->connectAccountancy();
    // FIN TESTS
}

comptatriee::~comptatriee()
{
    // Qt deletes all QObjects/QWidgets for you if you define a parent to all QObjects
}

void comptatriee::lancerrecettestriees()
{
  recettestriees * recettesTriees = new recettestriees;
                   recettesTriees ->execRec();
}

void comptatriee::lancerdepensestriees(){
  depensestriees *d = new depensestriees;
                  d-> execRec();
}

void comptatriee::lanceretatdesdus()
{ QString name = "";
  QString firstname = "";
  QString guid = "";
  QString user = "";
  etatdesdus *etat  = new etatdesdus(name,firstname,guid,user);
              etat -> show();
}

void comptatriee::lancerecettes()
{
  recettedialog *r = new recettedialog();
                 r-> show();
}
void comptatriee::lancedepenses()
{
   depensedialog *widget = new depensedialog();
                   widget-> show();
}

void comptatriee::lanceImmobilisations()
{
  immobilisations *widget = new immobilisations;
                   widget->show();
}


void comptatriee::lanceGrandLivre(){
  grandlivre *livre = new grandlivre;
              livre-> show();
}

void comptatriee::lanceFrenchTax(){
  frenchTax *frt = new frenchTax;
             frt -> show();
}

void comptatriee::lanceSetup()
{
  wiz1 *wiz = new wiz1;
        wiz-> show();
}

void comptatriee::lanceParametrages()
{
  parametrages *param = new parametrages(this);
                param-> show();
}

void comptatriee::lanceHelp(){
    qDebug() << __FILE__ << QString::number(__LINE__) << " lance helpWidget";
    helpWidget *aide = new helpWidget(this);
    aide -> show();
    }
    
void comptatriee::showBankAndUsers(){
    utilisateur *u = new utilisateur(this);
    u->show();
}

void comptatriee::showBankDeposits(){
    Deposits *d = new Deposits(0);
    d->show();
}

void comptatriee::showNotes(){
    Notes *n = new Notes(0);
    n->show();
}

void comptatriee::showErrors(){
    QString errorAllString;
    QFile f(settings()->applicationBundlePath()+"/errorLog.txt");
    qDebug() << __FILE__ << QString::number(__LINE__) << " " << settings()->applicationBundlePath()+"/errorLog";
    if(!f.open(QIODevice::ReadOnly)){
        QMessageBox::warning(0,trUtf8("Error"),trUtf8("Error log file cannot be opened."),QMessageBox::Ok);
        }
    QTextStream s(&f);
    s.setCodec("UTF8");
    while(!s.atEnd()){
        errorAllString += s.readLine()+"\n";
        }
    QDialog *d = new QDialog(this,Qt::Dialog|Qt::WindowCloseButtonHint);
    d->setMinimumSize(600,650);
    QDialogButtonBox *b = new QDialogButtonBox(QDialogButtonBox::Close,Qt::Horizontal,d);
    QTextEdit *e = new QTextEdit(d);
    e->setMinimumSize(500,600);
    e->setPlainText(errorAllString);
    QVBoxLayout *mainLayout = new QVBoxLayout;
     mainLayout->addWidget(e);
     mainLayout->addWidget(b);
     d->setLayout(mainLayout);
     connect(b,SIGNAL(rejected()),d,SLOT(reject()));
     if(!d->exec()){delete d;}
}

void comptatriee::createMenus()
{
    mFile = menuBar()->addMenu(tr("&File"));
    mAnalyse = menuBar()->addMenu(tr("&Analyse"));
    mInterfaces = menuBar()->addMenu("&Programmes");
    mSettings = menuBar()->addMenu(trUtf8("&Settings"));
    mHelp = menuBar()->addMenu(trUtf8("&Help"));
}

void comptatriee::createActions()
{
    /** \todo Translate tr text to english */
    m_fermer = mFile->addAction(QIcon(settings()->iconPath()+"/stop.png"),trUtf8("&Quit"));
    m_fermer->setShortcut(QKeySequence::Close);

    m_tridesrecettes = mAnalyse->addAction(QIcon(settings()->iconPath()+"/gear.png"),trUtf8("Trier les rece&ttes"));
    m_tridesdepenses = mAnalyse->addAction(QIcon(settings()->iconPath()+"/gear.png"),trUtf8("Trier les depen&ses"));
    m_etatsdesdus = mAnalyse->addAction(QIcon(settings()->iconPath()+"/gear.png"),trUtf8("Etat des d&us"));
    m_grandLivre = mAnalyse->addAction(QIcon(settings()->iconPath()+"/edit.png"),trUtf8("Grand &Livre"));
    m_frenchTax = mAnalyse->addAction(QIcon(settings()->iconPath()+"/edit.png"),trUtf8("C&onstruire 2035"));
    m_frenchTax->setStatusTip("Construit et imprime la 2035");
    m_recettes = mInterfaces->addAction(QIcon(settings()->iconPath()+"/recette.png"),trUtf8("&Recettes"));
    m_depenses = mInterfaces->addAction(QIcon(settings()->iconPath()+"/depense.png"),trUtf8("&Dépenses"));
    m_immobilisations = mInterfaces->addAction(QIcon(settings()->iconPath()+"/immobilisations.png"),trUtf8("&Immobilisations"));
    m_bankAndUsers = mInterfaces->addAction(QIcon(settings()->iconPath()+"/immobilisations.png"),trUtf8("&Bank and User"));
    m_bankDeposits = mInterfaces->addAction(QIcon(settings()->iconPath()+"/immobilisations.png"),trUtf8("Bank &Deposits"));
    m_notes = mInterfaces->addAction(QIcon(settings()->iconPath()+"/edit.png"),trUtf8("&Notes personnelles."));
    m_setup = mSettings->addAction(QIcon(settings()->iconPath()+"/setup.png"),trUtf8("Set&up for MedinTux"));
    m_setup->setStatusTip("Lance le setup d'installation des boutons de menu dans MedinTux");
    m_setup->setIconText("Lance");
    m_parametres = mSettings->addAction(QIcon(settings()->iconPath()+"/param.tiff"),trUtf8("Pa&ramétrages"));
    m_parametres->setStatusTip("Lance le logiciel de paramétrage de la Comptabilité.");
    m_help = mHelp->addAction(QIcon(settings()->iconPath()+"/param.tiff"),trUtf8("Help"));
    m_help->setStatusTip("Lance la fenêtre d'aide de la comptabilité.");
    m_error = mHelp->addAction(QIcon(settings()->iconPath()+"/param.tiff"),trUtf8("Show debug"));
    m_error->setStatusTip("Lance la fenêtre de visualisation des message de debug.");

}

void comptatriee::connectActions()
{
    connect(m_fermer        ,  SIGNAL(triggered()), this, SLOT(close()));
    connect(m_tridesrecettes,  SIGNAL(triggered()), this, SLOT(lancerrecettestriees()));
    connect(m_tridesdepenses,  SIGNAL(triggered()), this, SLOT(lancerdepensestriees()));
    connect(m_etatsdesdus,     SIGNAL(triggered()), this, SLOT(lanceretatdesdus()));
    connect(m_recettes,        SIGNAL(triggered()), this, SLOT(lancerecettes()));
    connect(m_depenses,        SIGNAL(triggered()), this, SLOT(lancedepenses()));
    connect(m_grandLivre,      SIGNAL(triggered()), this, SLOT(lanceGrandLivre()));
    connect(m_immobilisations, SIGNAL(triggered()), this, SLOT(lanceImmobilisations()));
    connect(m_bankAndUsers,SIGNAL(triggered()),this,SLOT(showBankAndUsers()));
    connect(m_setup          , SIGNAL(triggered()), this, SLOT(lanceSetup()));
    connect(m_parametres     , SIGNAL(triggered()), this, SLOT(lanceParametrages()));
    connect(m_frenchTax     ,  SIGNAL(triggered()), this, SLOT(lanceFrenchTax()));
    connect(m_help          ,  SIGNAL(triggered()), this, SLOT(lanceHelp()));
    connect(m_error         ,  SIGNAL(triggered()), this, SLOT(showErrors()));
    connect(m_notes,SIGNAL(triggered()),this,SLOT(showNotes()));
    connect(m_bankDeposits,SIGNAL(triggered()),this,SLOT(showBankDeposits()));
}

void comptatriee::errorMessage(QString & error){
    QMessageBox::warning(0,trUtf8("Error"),trUtf8("Error while start process :")+error,QMessageBox::Ok);
}





// UNNEEDED IF YOU WORK WITH QDIR INSTEAD OF QSTRING...
//QString comptatriee::adapteCheminWindows(QString & chemin){
//    QString str           = chemin;
//    QString nouveauChemin = "";
//    QStringList listStr   = str.split("/");
//    for(int i = 0;i < listStr.size();i++){
//        QString partie    = listStr[i];
//        if(listStr[i].contains(" ")){
//            partie = "\""+listStr[i]+"\"";
//        }
//        QString apres = "\\";
//        if(i == listStr.size()-1){
//            apres     = ".exe";
//        }
//        nouveauChemin += partie+apres;
//    }
//
//    return nouveauChemin;
//}


