/****************************************************************************
** qhpimp - un entorno gráfico a los comandos hplip
**---------------------------------------------------------------------------
** qhimp - main.cpp, qhpimp.cpp, qhpimp.h, qhpimp.qrc, qhpimp.ui
**===========================================================================
** FJA - neocipres@gmail.com                Abril de 2011   (17/04/2011)
**===========================================================================
** This file may be used under the terms of the GNU General Public
** License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "qhpimp.h"
#include "ui_qhpimp.h"
#include <QMessageBox>


qhpimp::qhpimp(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::qhpimp)
{
    ui->setupUi(this);
    proc = new QProcess(ui->centralWidget);
    comando = QString::null;

    connect(ui->actionAcerca_de_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(ui->actionAcerca_de_qHPLIP, SIGNAL(triggered()), this, SLOT(acercade()));
    connect(ui->actionHp_info, SIGNAL(triggered()), this, SLOT(ayudaInfo()));
    connect(ui->actionHp_levels, SIGNAL(triggered()), this, SLOT(ayudaLevels()));
    connect(ui->actionHp_probe, SIGNAL(triggered()), this, SLOT(ayudaProbe()));
    connect(ui->actionHp_check, SIGNAL(triggered()), this, SLOT(ayudaCheck()));
    connect(ui->actionHp_testpage, SIGNAL(triggered()), this, SLOT(ayudaTestpage()));
    connect(ui->actionKill, SIGNAL(triggered()), this, SLOT(matarProc()));

    connect(ui->pBInfo, SIGNAL(clicked()), this, SLOT(ejecutarInfo()));
    connect(ui->pBLevels, SIGNAL(clicked()), this, SLOT(ejecutarLevels()));
    connect(ui->pBProbe, SIGNAL(clicked()), this, SLOT(ejecutarProbe()));
    connect(ui->pBCheck, SIGNAL(clicked()), this, SLOT(ejecutarCheck()));
    connect(ui->pBTestpage, SIGNAL(clicked()), this, SLOT(ejecutarTestpage()));
    connect(ui->pBAceptar, SIGNAL(clicked()), this, SLOT(aceptar()));

    connect(proc, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout()));
    connect(proc, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr()));
    connect(proc, SIGNAL(error(QProcess::ProcessError )), this, SLOT(tipoError(QProcess::ProcessError )));
}

qhpimp::~qhpimp()
{
    if (proc->pid() != 0) proc->kill();
    delete ui;
}

void qhpimp::ayudaInfo()
{
    QStringList args;
    args << "-h";
    ejecutar("hp-info", args);
}

void qhpimp::ayudaLevels()
{
    QStringList args;
    args << "-h";
    ejecutar("hp-levels", args);
}

void qhpimp::ayudaCheck()
{
    QStringList args;
    args << "-h";
    ejecutar("hp-check", args);
}

void qhpimp::ayudaProbe()
{
    QStringList args;
    args << "-h";
    ejecutar("hp-probe", args);
}

void qhpimp::ayudaTestpage()
{
    QStringList args;
    args << "-h";
    ejecutar("hp-testpage", args);
}

void qhpimp::ejecutar(QString cmd, QStringList args)
{
    comando = cmd;
    ui->tESalida->clear();
    if (proc->state() == 0) proc->start(cmd, args, QIODevice::ReadOnly);
    else ui->statusBar->showMessage(QString("El proceso %1 no puede ejecutarse, hay otro proceso corriendo.").arg(comando), 5000);

}

void qhpimp::readFromStdout()
{
    QByteArray datos = proc->readAllStandardOutput();
    QString linea = QString::null;
    linea.append(QString::fromUtf8(datos));
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);

    ui->tESalida->append(linea);
}

void qhpimp::readFromStderr()
{
    QByteArray datos = proc->readAllStandardError();
    QString linea = QString::null;
    linea.append(QString::fromUtf8(datos));
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);
    linea.remove(QString(""), Qt::CaseInsensitive);

    ui->tESalida->append("<b>"+linea+"</b>");
}

void qhpimp::tipoError(QProcess::ProcessError error)
{
    QString cadE;

    switch (error) {
    case QProcess::FailedToStart:
        cadE = QString::fromUtf8("El proceso %1 ha fallado al iniciarse.\nPuede que no exista, o no se tengan los permisos suficientes").arg(comando);
        break;
    case  QProcess::Crashed:
        cadE = QString::fromUtf8("Después de un inicio correcto,\nel proceso %1 se ha roto.").arg(comando);
        break;
    case  QProcess::Timedout:
        cadE = "The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.";
        break;
    case QProcess::WriteError:
        cadE = "An error occurred when attempting to write to the process.\nFor example, the process may not be running, or it may have closed its input channel.";
        break;
    case QProcess::ReadError:
        cadE = "An error occurred when attempting to read from the process.\nFor example, the process may not be running.";
        break;
    case QProcess::UnknownError:
        cadE = QString::fromUtf8("Un error desconocido en el proceso %1.").arg(comando);
        break;
    }
    QMessageBox::warning( ui->centralWidget,
                          tr("Error - comandos hplip"),
                          tr("Error: ")+QString::number(error)+". "+cadE,
                          tr("Aceptar") );

}

void qhpimp::ejecutarInfo()
{
    ui->lEComando->setText("hp-info");
    ui->lEArgumentos->setText("-u");
}

void qhpimp::ejecutarLevels()
{
    ui->lEComando->setText("hp-levels");
    ui->lEArgumentos->setText("-a#");
}

void qhpimp::ejecutarProbe()
{
    ui->lEComando->setText("hp-probe");
    ui->lEArgumentos->setText("-bcups");
}

void qhpimp::ejecutarCheck()
{
    ui->lEComando->setText("hp-check");
    ui->lEArgumentos->setText("-c");
}

void qhpimp::ejecutarTestpage()
{
    ui->lEComando->setText("hp-testpage");
    ui->lEArgumentos->setText("-u");
}

void qhpimp::aceptar()
{
    QString cmd = ui->lEComando->text();
    QStringList args = (QStringList() << ui->lEArgumentos->text().split(" "));
    ejecutar(cmd, args);
}

void qhpimp::matarProc()
{
    proc->kill();
}

void qhpimp::acercade()
{
    QString separador = QString::null;
    separador.fill('=', 37);
    QString nomAp = "<p><b><BIG><BIG>qHPImp</BIG></BIG></b></p>";
    QString desAp1 = "<p><b>"+QString::fromUtf8("Entorno gráfico a los comandos hplip")+"</b></p>";
    QString desAp2 = "<p>"+QString::fromUtf8("<a href= http://hplipopensource.com>HPLIP</a> es el paquete de software opensource de HP para impresoras, scanners y multifunciones. Incluye drivers y herramientas de configuración.")+"</p>";
    QString autor =  "<p><b>FJA</b> - neocipres@gmail.com</p>";
    QString version = QString::fromUtf8("<p>Versión: 0.9.7</p>");
    QString modificado = "<p>Abril de 2011  -  Modificado el 17 de Abr/2011</p>";
    QString licencia = QString::fromUtf8("<p>Distribuido de acuerdo a los términos de la <a href= http://www.viti.es/gnu/licenses/gpl.html>licencia GNU/GPL</a></p>");
    QString  gnu = "<p><a href= http://www.gnu.org/home.es.html>Proyecto GNU</a></p>";
    QMessageBox::about(ui->centralWidget, "Acerca de ...",nomAp+desAp1+desAp2+separador+autor+modificado+separador+version+licencia+gnu);
}