#include "slackpackimpl.h"
#include "preferencesdialog.h"

PreferencesDialog *prfDlg;

QString userprocOut;
Q3Process *userproc;

QString FileNamePath; //Declares "FileNamePath"
QString InstallPkg; //Declares installpkg system command
QString InstallPkgCom; //connects "InstallPkgPath" with the file that the console out will be redirected.
QString RemovePkg; //Declares removepkg system command
QString RemovePkgCom; //connects "RemovePkgPath" with the file that the console out will be redirected.
QString ConvRpm2Tgz; //Declares rpm2tgz system command
QString ConvRpm2TgzArgs; //get rpm2tgz args from preferences dialog
QString ConvRpm2TgzCom; //connects "ConvRpm2TgzPath" with the file that the console out will be redirected.
QString ConvDeb2Tgz; //Declares deb2tgz system command
QString ConvDeb2TgzArgs; //get deb2tgz args from preferences dialog
QString ConvDeb2TgzCom;
QString MakePkg; //Declares MakePkg system command
QString MakePkgArgs; //get makepkg args from preferences dialog
QString PkgName; //package name created through the MakePkg dialogs
QString MakePkgCom; //connects "MakePkgCom" with the file that the console out will be redirected
QString DirectoryPath; //Declares "DirectoryPath"
QString MakePkgDlgAppText; //Declares "MakePkgDlgAppText"
QString MakePkgDlgAppVer; //Declares "MakePkgDlgAppVer"
QString MakePkgDlgAppArch; //Declares "MakePkgDlgAppArch"
QStringList MakePkgDlgAppArchList; //Declares "MakePkgDlgAppArchList"
QString MakePkgDlgAppFormat; //Declares "MakePkgDlgAppFormat"
QStringList MakePkgDlgAppFormatList; //Declares "MakePkgDlgAppFormatList"


QString cd; //the command
QString cdPath; //includes directory path
QString cdCom;  //appends 'cd' command with dir path

QString pkgName; //var to save selected package name

QString RemSelPkg; //Declares removepkg system command
QString RemSelPkgCom; //adds the path to the file that the output will be redirected, this is the final command
QString UpgradePkg; //Declares upgradepkg system command
QString UpgradeOldPkgName; //connects "UpgradePkg" with the name of the old package.
QString UpgradeNewPkgPath; //connects "UpgradePkg" with the path for the new package
QString UpgradePkgCom; //connects "UpgradePkgPath" with the file that the console out will be redirected.

QString fileText;

QDialog *aboutDlg;
QDirModel *listModel;
QTextEdit *consoleDlgBox;
QProgressDialog *progress;
/*decleare processes*/
QProcess *installproc;
QProcess *removeproc;
QProcess *makepkgproc;
QProcess *rpm2tgzproc;
QProcess *deb2tgzproc;
QProcess *remselproc;
QProcess *upgradeproc;
QProcess *pkgDescProc;
/*console output/pkg info, widgets*/
QLabel *pkgdesclbl;
QLabel *pkgfilelistlbl;
QLabel *consoleOutlbl;
QTextBrowser *pkgdescText;
QTextBrowser *pkgfilelistText;
QTextBrowser *consoleOutText;
QToolButton *pkgsaveBtn;
QToolButton *pkgcopyBtn;
QVBoxLayout *vbox;
QHBoxLayout *hbox;
//
SlackpackImpl::SlackpackImpl( QWidget * parent, Qt::WFlags f) 
	: QMainWindow(parent, f)
{
	statusBar()->showMessage(tr("Loading..."));
	setupUi(this);

        /** create progress dialog for processes **/
        progress = new QProgressDialog("", "", 0, 0);
        progress->setCancelButton(0);

        /** check if user is root **/
	userproc = new Q3Process(this);
	userproc->addArgument("whoami");

        connect( userproc, SIGNAL(readyReadStdout()),
                this, SLOT(checkIfRoot()) );

	userproc->start();



    /** create the pkginfo widgets**/
    //create labels
    pkgdesclbl = new QLabel();
    pkgdesclbl->setText("Package Description");
    pkgdesclbl->setFont(QFont("SansSerif", 12, QFont::Bold));
    pkgdesclbl->setGeometry(10,10,111,16);

    pkgfilelistlbl = new QLabel();
    pkgfilelistlbl->setText("File List");
    pkgfilelistlbl->setFont(QFont("SansSerif", 12, QFont::Bold));
    pkgfilelistlbl->setGeometry(10,230,71,16);

    consoleOutlbl = new QLabel();
    consoleOutlbl->setText("Console Output");
    consoleOutlbl->setFont(QFont("SansSerif", 12, QFont::Bold));
    consoleOutlbl->setGeometry(10,230,71,16);

    //create textboxes
    pkgdescText = new QTextBrowser();
    pkgdescText->setGeometry(20,30,301,192);
    pkgdescText->setFrameStyle(0);

    pkgfilelistText = new QTextBrowser();
    pkgfilelistText->setGeometry(20,20,341,521);
    pkgfilelistText->setFrameStyle(0);

    consoleOutText = new QTextBrowser();
    consoleOutText->setGeometry(20,30,301,192);
    consoleOutText->setFrameStyle(0);

    //create buttons
    pkgsaveBtn = new QToolButton();
    pkgsaveBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    pkgsaveBtn->setIcon(QIcon("/usr/share/slackpack/images/save.png"));
    pkgsaveBtn->setText("Save Output to file");
    connect(pkgsaveBtn,SIGNAL(clicked()),this,SLOT(saveAction()));

    pkgcopyBtn = new QToolButton();
    pkgcopyBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    pkgcopyBtn->setIcon(QIcon("/usr/share/slackpack/images/editcopy.png"));
    pkgcopyBtn->setText("Copy to clipboard");
    connect(pkgcopyBtn,SIGNAL(clicked()),this,SLOT(copyAction()));

     vbox = new QVBoxLayout;
     vbox->addWidget(pkgdesclbl);
     vbox->addWidget(pkgdescText);
     vbox->addWidget(pkgfilelistlbl);
     vbox->addWidget(pkgfilelistText);
     vbox->addWidget(consoleOutlbl);
     vbox->addWidget(consoleOutText);

     hbox = new QHBoxLayout(vbox);
     hbox->addWidget(pkgsaveBtn);
     hbox->addWidget(pkgcopyBtn);

     pkginfoBox->setLayout(vbox);

    //show package info widgets
     pkgdesclbl->show();
     pkgdescText->show();
     pkgfilelistlbl->show();
     pkgfilelistText->show();
     //hide console output widgets until action triggers show()
     consoleOutlbl->hide();
     consoleOutText->hide();
     pkgsaveBtn->hide();
     pkgcopyBtn->hide();


     statusBar()->showMessage(tr("Ready!"), (5000));

}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
        if (role == Qt::DecorationRole) {
                return QIcon("/usr/share/slackpack/images/package.png");
        }
        return QDirModel::data(index, role);
        
}

void SlackpackImpl::preferencesAction()
{
    PreferencesDialog prfDlg;
    prfDlg.exec();
}
void SlackpackImpl::checkIfRoot()
{
	//check if root else exit program
	userprocOut.append(userproc->readStdout());

        if(!userprocOut.contains("root"))
	 {

                QMessageBox errorBox;
                errorBox.setText("Not root!.");
                errorBox.setInformativeText("when you're running Slackpack as a normal user you can\nonly browse installed packages on the system.");
                errorBox.setStandardButtons(QMessageBox::Abort|QMessageBox::Ok);
                errorBox.setIcon(QMessageBox::Critical);
                 int ret = errorBox.exec();
                      switch (ret)
                      {
             case QMessageBox::Abort:
                exit(0);
             case QMessageBox::Ok:
                //disable root only features
                installbutton->setEnabled(false);
                removebutton->setEnabled(false);
                makepkgbutton->setEnabled(false);
                actionInstall->setEnabled(false);
                actionRemove->setEnabled(false);
                remselbutton->setEnabled(false);
                upgradebutton->setEnabled(false);
             default:
                // should never be reached
                  break;
                    }
	 }
}

/** save/copy actions **/
void SlackpackImpl::saveAction()
{

           //open file dialog to choose new package.
   FileNamePath = QFileDialog::getSaveFileName(
                    "",
                    "Text File (*.txt)",
                    this,
                    "save file dialog",
                    "Save console output to file" );

        //check if user selected a pkg
        if ( FileNamePath.isEmpty() )
        {
//if filenamepath is empty, user pressed cancel
        return;
        }

    QFile outputsaveFile (FileNamePath ); //the console output file
    outputsaveFile.open ( IO_WriteOnly ); //open the file
    outputsaveFile.write(fileText);
    outputsaveFile.close();

    statusBar()->showMessage(tr("Saved output to",FileNamePath), (5000));

}

void SlackpackImpl::copyAction()
{
 QClipboard *clipboard = QApplication::clipboard();
 clipboard->setText(fileText);
 statusBar()->showMessage(tr("Copied to clipboard!"), (5000));
}


void SlackpackImpl::currentChanged()
{

    if(tabWidget->currentIndex())
    {
        setCursor(Qt::WaitCursor);//set wait cursor

        statusBar()->showMessage(tr("Working..."));
        listModel = new MyModel;
        listModel->index("/var/log/packages");
        
        QProgressDialog progress("Listing Packages", "Cancel", 0, listModel->rowCount(), this);
        progress.setWindowModality(Qt::WindowModal);
        progress.show();
            for (int i = 0; i < listModel->rowCount(); i++) {
                progress.setValue(i);

                if (progress.wasCanceled())
                   break;

        treeView->setModel(listModel);
        treeView->setRootIndex(listModel->index("/var/log/packages"));
        treeView->hideColumn(1);
        treeView->hideColumn(2);
        treeView->hideColumn(3);
      }
        progress.setValue(listModel->rowCount());

        connect(treeView, SIGNAL(clicked(QModelIndex)),this,SLOT(packageInfo()));
        unsetCursor(); //restores cursor
        statusBar()->showMessage(tr("Done"), (5000));

}



}
void SlackpackImpl::packageInfo()
{

   /** Get selected package name, and create `cat` command to get file information **/
   QString pkgAbsoluteName;
   QString pkgName;
   QModelIndexList indexes = treeView->selectionModel()->selectedIndexes();

   foreach (QModelIndex index, indexes)
        {
           pkgAbsoluteName = listModel->fileInfo( index ).fileName();
        }


    pkgName = pkgAbsoluteName;

    /** get package description**/
    QString pkgDescCom = "cat /var/log/packages/";
    pkgDescCom.append(pkgAbsoluteName).append(" | grep ");
    QString pkgDescription = pkgDescCom.append(pkgAbsoluteName.remove(pkgAbsoluteName.indexOf("-"),100)).append(": >/tmp/pkgDescFile");

    /** run cat command, save output to file read selected file paste the contents and then delete it! **/
    system(pkgDescription);

    QString pkgDescriptionText;
    QFile pkgDescFile ( "/tmp/pkgDescFile" ); //the console output file
    pkgDescFile.open ( IO_ReadOnly ); //open the file
    QTextStream pkgDesc ( &pkgDescFile );
    pkgDescriptionText = ( pkgDesc.read() );

    pkgDescFile.close();
    system("rm /tmp/pkgDescFile");

    /** get package file list **/
    QString pkgFileListCom = "cat /var/log/packages/";
    pkgFileListCom.append(pkgName).append(" | grep ./");
    QString pkgFileList = pkgFileListCom.append(" >/tmp/pkgFileListFile");

    /** run cat command, save output to file read selected file paste the contents and then delete it! **/
    system(pkgFileList);

    QString pkgFileListText;
    QFile pkgFileListFile ( "/tmp/pkgFileListFile" ); //the console output file
    pkgFileListFile.open ( IO_ReadOnly ); //open the file
    QTextStream pkgFList ( &pkgFileListFile );
    pkgFileListText = ( pkgFList.read() );

    pkgFileListFile.close();
    system("rm /tmp/pkgFileListFile");

    pkgdescText->setText(pkgDescriptionText);
    pkgfilelistText->setText(pkgFileListText);



}

void SlackpackImpl::contentsMenuAction()
{
system("khelpcenter help:slackpack");
}

void SlackpackImpl::reportBugsMenuAction()
{
QDesktopServices::openUrl(QUrl("http://sourceforge.net/tracker/?func=add&group_id=214969&atid=1031791"));
}

void SlackpackImpl::aboutMenuAction()
{
	QString aboutText; //declares text used in the about page
	QString timelineText; //declares text used in the timeline page
	QString licenseText;//declares text used in the license page
	QString thankstoText;//declares text used in the Thanks To page


//READ THE ABOUT FILE AND COPY TEXT INTO aboutText var
	QFile ABOUTfile ( "/usr/share/slackpack/ABOUT" ); //the console output file
	ABOUTfile.open ( IO_ReadOnly ); //open the file
	QTextStream abouts ( &ABOUTfile );
	aboutText = ( abouts.read() );


//READ THE THANKS TO FILE AND COPY TEXT INTO thankstoText var
	QFile ThanksTofile ( "/usr/share/slackpack/ThanksTo" ); //the console output file
	ThanksTofile.open ( IO_ReadOnly ); //open the file
	QTextStream thanks ( &ThanksTofile );
	thankstoText = ( thanks.read() );

//READ THE LICENSE (COPYING) FILE AND COPY TEXT INTO licenseText var
	QFile COPYINGfile ( "/usr/share/slackpack/COPYING" ); //the console output file
	COPYINGfile.open ( IO_ReadOnly ); //open the file
	QTextStream license ( &COPYINGfile );
	licenseText = ( license.read() );

//READ THE ChangeLog FILE AND COPY TEXT INTO timelineText var
	QFile Changelogfile ( "/usr/share/slackpack/ChangeLog" ); //the console output file
	Changelogfile.open ( IO_ReadOnly ); //open the file
	QTextStream timeline ( &Changelogfile );
	timelineText = ( timeline.read() );

        /** Create the dialog **/
           aboutDlg = new QDialog(this);
           aboutDlg->setMinimumSize(438,353);
           aboutDlg->setMaximumSize(438,353);
           aboutDlg->setCaption("About Dialog");

           QLabel *logolbl = new QLabel(aboutDlg);
           logolbl->setMinimumSize(91,101);
           logolbl->setGeometry(3,-2,91,101);
           logolbl->setPixmap(QPixmap("/usr/share/slackpack/images/hi90-app-slackpack.png"));

           QLabel *programNameVerlbl = new QLabel(aboutDlg);
           programNameVerlbl->setMinimumSize(161,21);
           programNameVerlbl->setGeometry(88,18,161,21);
           programNameVerlbl->setFont(QFont("SansSerif", 12, QFont::Bold));
           programNameVerlbl->setText("Slackpack 1.1.8");

           QLabel *copyMsglbl = new QLabel(aboutDlg);
           copyMsglbl->setMinimumSize(321,31);
           copyMsglbl->setGeometry(100,40,321,31);
           copyMsglbl->setTextFormat(Qt::RichText);
           copyMsglbl->setText("&copy;2009, Pavloudis Zisis<br>under the terms of General Public License version 2");

           QPushButton *closeBtn = new QPushButton(aboutDlg);
           closeBtn->setGeometry(365,325,71,25);
           closeBtn->setText("Close");
           connect(closeBtn, SIGNAL(clicked()), this, SLOT(closeAboutDlg()));


           /*** create tabs and the tabwidget for about dialog ***/
           //create aboutTab
           QWidget *aboutTab = new QWidget();
           QTextBrowser *aboutTextTabWidget = new QTextBrowser(aboutTab);
           aboutTextTabWidget->setOpenExternalLinks(TRUE);
           aboutTextTabWidget->setMinimumSize(415,191);
           aboutTextTabWidget->setGeometry(0,0,415,191);
           aboutTextTabWidget->setReadOnly(TRUE);
           aboutTextTabWidget->setText(aboutText);

           //create timelineTab
           QWidget *timelineTab = new QWidget();
           QTextBrowser *timelineTextTabWidget = new QTextBrowser(timelineTab);
           timelineTextTabWidget->setOpenExternalLinks(TRUE);
           timelineTextTabWidget->setMinimumSize(415,191);
           timelineTextTabWidget->setGeometry(0,0,415,191);
           timelineTextTabWidget->setReadOnly(TRUE);
           timelineTextTabWidget->setText(timelineText);

           //create thanksTab
           QWidget *thanksTab = new QWidget();
           QTextBrowser *thanksTextTabWidget = new QTextBrowser(thanksTab);
           thanksTextTabWidget->setOpenExternalLinks(TRUE);
           thanksTextTabWidget->setMinimumSize(415,191);
           thanksTextTabWidget->setGeometry(0,0,415,191);
           thanksTextTabWidget->setReadOnly(TRUE);
           thanksTextTabWidget->setText(thankstoText);

           //create licenseTab
           QWidget *licenseTab = new QWidget();
           QTextBrowser *licenseTextTabWidget = new QTextBrowser(licenseTab);
           licenseTextTabWidget->setOpenExternalLinks(TRUE);
           licenseTextTabWidget->setMinimumSize(415,191);
           licenseTextTabWidget->setGeometry(0,0,415,191);
           licenseTextTabWidget->setReadOnly(TRUE);
           licenseTextTabWidget->setText(licenseText);

           //create tabwidget and add tabs
           QTabWidget *aboutdlgtabwidget = new QTabWidget(aboutDlg);
           aboutdlgtabwidget->setMinimumSize(421,221);
           aboutdlgtabwidget->setGeometry(10,101,421,221);
           aboutdlgtabwidget->insertTab(1, aboutTab, "About");
           aboutdlgtabwidget->insertTab(2, timelineTab, "Timeline");
           aboutdlgtabwidget->insertTab(3, thanksTab, "Thanks to");
           aboutdlgtabwidget->insertTab(4, licenseTab, "License");

           
           aboutDlg->show();



}

void SlackpackImpl::closeAboutDlg()
{
    aboutDlg->close();
}

void SlackpackImpl::quitMenuAction()
{
	exit(1);
}

/**Process Packages Tab**/
void SlackpackImpl::installbutton_clicked() //installs the pkg
{
   //open file dialog to choose new package.
   FileNamePath = QFileDialog::getOpenFileName(
                    "",
                    "Slackware Packages (*.tgz *.txz)",
                    this,
                    "open file dialog",
                    "Select a package to install." );

	//check if user selected a pkg
	if ( FileNamePath.isEmpty() )
	{
//if filenamepath is empty, user pressed cancel
        return;
	}


         setCursor(Qt::WaitCursor);

        statusBar()->showMessage(tr("Working..."));
        fileText.clear();

	consolebox->clear(); //clears any remaing output text in the consolebox from previous action

	InstallPkg = "installpkg "; //system command to install the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
        InstallPkgCom = InstallPkg.append ( FileNamePath ); //adds the path to InstallPkg

        progress->setLabelText("Installing Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        installproc = new QProcess(this);
        installproc->start(InstallPkgCom);
        connect( installproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(installProcessFinished()));
        progress->exec();


    }



void SlackpackImpl::installProcessFinished()
{

        progress->close();
        fileText.append(installproc->readAll());

        /*BEGINING ERROR TESTING >*/
        if ( fileText.contains ( "Cannot install", FALSE ) )
        {

//inform user that there was an error with the installation
                QMessageBox errorBox;
                errorBox.setText("Error Installing the package\nSee the Console Output");
                errorBox.setIcon(QMessageBox::Critical);
                errorBox.exec();

//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
        statusBar()->showMessage(tr("Done"), (5000));
        }
        /*< ENDS ERROR TESTING*/
        else
        {


                consolebox->setText ( fileText );
//inform user that installation is complete
                QMessageBox infoBox;
                infoBox.setText("Installation Complete!");
                infoBox.setIcon(QMessageBox::Information);
                infoBox.exec();
        statusBar()->showMessage(tr("Done!"), (5000));
        }
        unsetCursor(); //restores cursor
}

void SlackpackImpl::removebutton_clicked() //removes package
{

   //open file dialog to choose new package.
   FileNamePath = QFileDialog::getOpenFileName(
                    "",
                    "Slackware Packages (*.tgz *.txz)",
                    this,
                    "open file dialog",
                    "Select a package to remove." );
	//check if user selected a pkg
	if ( FileNamePath.isEmpty() )
	{
//if filenamepath is empty, user pressed cancel
	return;
	}

 QMessageBox qBox;
 qBox.setText("Warning!");
 qBox.setInformativeText("Are you sure you want to remove selected package?");
 qBox.setIcon(QMessageBox::Warning);
 qBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
 int ret = qBox.exec();
            switch (ret) {
   case QMessageBox::No:
       {
         return;
       }
  case QMessageBox::Yes:
       {}
 }
         setCursor(Qt::WaitCursor);
        fileText.clear();

        statusBar()->showMessage(tr("Working..."));
        consolebox->clear(); //clears any remaing output text in the consolebox from previous action

	RemovePkg = "removepkg "; //system command to remove the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
        RemovePkgCom = RemovePkg.append ( FileNamePath ); //adds the path to RemovePkg

        progress->setLabelText("Removing Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        removeproc = new QProcess(this);
        removeproc->start(RemovePkgCom);
        connect( removeproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(removeProcessFinished()));

        progress->exec();

}

void SlackpackImpl::removeProcessFinished()
{
    progress->close();
    fileText.append(removeproc->readAll());

        /*BEGINNING ERROR TESTING >*/
        if ( fileText.contains ( "No such package", FALSE ) )
        {
//inform user that there was an error on removing
                QMessageBox errorBox;
                errorBox.setText("Error Removing the package\nSee the Console Output");
                errorBox.setIcon(QMessageBox::Critical);
                errorBox.exec();

//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
        statusBar()->showMessage(tr("Done"), (5000));
        }
        /*< ENDS ERROR TESTING*/
        else
        {
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
//inform user that package is removed
                QMessageBox infoBox;
                infoBox.setText("Package Removed!");
                infoBox.setIcon(QMessageBox::Information);
                infoBox.exec();
        statusBar()->showMessage(tr("Done!"), (5000));
        }
        unsetCursor(); //restores cursor
  }

void SlackpackImpl::makepkgbutton_clicked()
{
                 setCursor(Qt::WaitCursor);//sets wait cursor

	consolebox->clear(); //clears any remaing output text in the consolebox from previous action
        fileText.clear();

         DirectoryPath = QFileDialog::getExistingDirectory(this, tr("Open, Source Directory"),
                                                           "${HOME}",
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);

        if ( DirectoryPath.isEmpty() )
	{
//if filenamepath is empty, msg box= you must choose a dir first
                QMessageBox errorBox;
                errorBox.setText("You must select a directory contains your application's source code.");
                errorBox.setIcon(QMessageBox::Critical);
                errorBox.exec();

        statusBar()->showMessage(tr("Done"), (5000));
        unsetCursor(); //restores cursor
        return;
	}

//Package Creation Dialogs
//set package name dialog
	bool ok;
	MakePkgDlgAppText = QInputDialog::getText (
	                        "Set package name", "Enter the name of your application:\neg slackpack", QLineEdit::Normal,
	                        QString::null, &ok, this );
	if ( ok )
	{
	}
	else
	{
        unsetCursor(); //restores cursor
         return;
	}

	if ( MakePkgDlgAppText.isEmpty() )
	{
         QMessageBox errorBox;
         errorBox.setText("You must enter the name of your application!");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         unsetCursor(); //restores cursor
         return;
	}

//set version dialog
	MakePkgDlgAppVer = QInputDialog::getText (
	                       "Set package version", "Enter the version of your application:\neg 1.1.0", QLineEdit::Normal,
	                       QString::null, &ok, this );
	if ( ok )
	{
	}
	else
	{
         unsetCursor(); //restores cursor
         return;
	}

	if ( MakePkgDlgAppVer.isEmpty() )
	{
         QMessageBox errorBox;
         errorBox.setText("You must enter the version of your application!");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         unsetCursor(); //restores cursor
         return;
	}

//set arch dialog
	MakePkgDlgAppArchList.append ( "i486" );
	MakePkgDlgAppArchList.append ( "i686" );
	MakePkgDlgAppArchList.append ( "i386" );
	MakePkgDlgAppArchList.append ( "x86_64" );
	MakePkgDlgAppArchList.append ( "S390" );
	MakePkgDlgAppArchList.append ( "noarch" );


	MakePkgDlgAppArch = QInputDialog::getItem (
	                        "Choose package Arch", "Choose Arch for the package:\neg i386", MakePkgDlgAppArchList, 1, TRUE, &ok,
	                        this );
	if ( ok )
	{
	}
	else
	{
         unsetCursor(); //restores cursor
         return;
	}

	if ( MakePkgDlgAppArch.isEmpty() )
	{
         QMessageBox errorBox;
         errorBox.setText("You must select an arch for your application!");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         unsetCursor(); //restores cursor
         return;
	}

 //set package format dialog
        MakePkgDlgAppFormatList.append ( ".tgz" );
        MakePkgDlgAppFormatList.append ( ".txz" );


        MakePkgDlgAppFormat = QInputDialog::getItem (
                                "Choose package Format", "Choose package format:", MakePkgDlgAppFormatList, 1, TRUE, &ok,
                                this );
        if ( ok )
        {
        }
        else
        {
         unsetCursor(); //restores cursor
         return;
        }

        if ( MakePkgDlgAppFormat.isEmpty() )
        {
         QMessageBox errorBox;
         errorBox.setText("You must select a format for your applications package");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         unsetCursor(); //restores cursor
         return;
        }

   prfDlg = new PreferencesDialog();
//if everythink is ok, continue...
        statusBar()->showMessage(tr("Working..."));

  //check to see user selected script
  if(prfDlg->createpkgComboBox->currentIndex() == 0 )//index at 0 = makepkg script
     {
//cd command-go to the dir were the app is
                cd = "cd ";
                cdPath = ( DirectoryPath );
                cdCom = cd.append ( cdPath );
//connects MakePkgDlgAppText-ver-arch and gets the pkg name
                PkgName = ( MakePkgDlgAppText );
                PkgName.append ( "-" );
                PkgName.append ( MakePkgDlgAppVer );
                PkgName.append ( "-" );
                PkgName.append ( MakePkgDlgAppArch );
                PkgName.append ( MakePkgDlgAppFormat );

//create MakePkgCom
                MakePkg = "makepkg "; //system command to create the pkg
                prfDlg = new PreferencesDialog();
                MakePkgArgs = MakePkg.append( prfDlg->createpkgArgsBox->text().append(" ${HOME}/") );
                MakePkgCom = MakePkgArgs.append ( PkgName ); //adds the pkg name to MakePkg

//create the shell script
                QFile createpkg("/tmp/createpkg");
                createpkg.open(QFile::WriteOnly | QFile::Truncate);

                QTextStream shscript(&createpkg);
                shscript <<"#!/bin/bash \n\n";
//Writes on the script the steps for compiling and installing the app from source
                shscript << cdCom << " \n";
                shscript << "./configure --prefix=/tmp/slackpack \n";
                shscript << "make \n";
                shscript << "make install \n\n";
//go to the dir where the app was installed and run makepkg
                shscript << "cd /tmp/slackpack \n";
                shscript << MakePkgCom << "";

                createpkg.close();

//Change shell script's permitions to read-write-execute by the current user using chmod command
                system ( "chmod u=x /tmp/createpkg" );

                setCursor(Qt::WaitCursor);

//Execute the shell script
        progress->setLabelText("Please Wait\nMaking Package...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        makepkgproc = new QProcess(this);
        makepkgproc->start("/tmp/createpkg");
        statusBar()->showMessage(tr("Please wait..."));
        connect( makepkgproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(makepkgProcessFinished()));

        progress->exec();
     }
  else if(prfDlg->createpkgComboBox->currentIndex() == 1)//index at 1 = src2pkg script
     {
       QMessageBox t;
       t.setText("src2pkg");
       t.exec();
     }

}

void SlackpackImpl::makepkgProcessFinished()
{
         progress->close();
         fileText.append(makepkgproc->readAll());
         unsetCursor(); //restores cursor

        //error checking
        if(fileText.contains("ERROR"))
        {
        QMessageBox errorBox;
        errorBox.setText("Error creating package, see console output!");
        errorBox.setIcon(QMessageBox::Critical);
        errorBox.exec();
        consolebox->setText ( fileText );
        return;
        }
//inform user that creation of the package is complete

        QMessageBox infoBox;
        infoBox.setText("Package Created Succesfully at your home directory!");
        infoBox.setIcon(QMessageBox::Information);
        infoBox.exec();

        statusBar()->showMessage(tr("Done!"), (5000));
        consolebox->setText ( fileText );


        //copy created package into user dir.
        QString cpCom;
        QString slackpackTmpDir;

        cpCom = ("cp ");
        slackpackTmpDir = ("/tmp/slackpack/");

        cpCom.append(slackpackTmpDir);
        cpCom.append(PkgName);
        cpCom.append(" ${HOME}");

        system(cpCom);


        //remove temporary files
        system("rm -rf /tmp/slackpack && rm /tmp/createpkg");


        unsetCursor(); //restores cursor
}


void SlackpackImpl::rpm2tgzbutton_clicked()
{
  prfDlg = new PreferencesDialog();
   //open file dialog to choose new package.
   FileNamePath = QFileDialog::getOpenFileName(
                    "",
                    "Red Hat Packages (*.rpm)",
                    this,
                    "open file dialog",
                    "Select an .rpm package to convert." );

	//check if user selected a pkg
	if ( FileNamePath.isEmpty() )
	{
//if filenamepath is empty, user pressed cancel
	return;
	}


                setCursor(Qt::WaitCursor); //set wait cursor
                statusBar()->showMessage(tr("Working..."));
		consolebox->clear(); //clears any remaing output text in the consolebox from previous action
                fileText.clear();

//see user selected script
  if(prfDlg->rpm2tgzComboBox->currentIndex() == 0)//index at 0 = rpm2tgz script
    {
		ConvRpm2Tgz = "rpm2tgz "; //system command to install the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
                ConvRpm2TgzArgs = ConvRpm2Tgz.append(prfDlg->rpm2tgzArgsBox->text().append(" "));
                ConvRpm2TgzCom = ConvRpm2Tgz.append ( FileNamePath ); //adds the path to ConvRpm2Tgz


        progress->setLabelText("Converting Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        rpm2tgzproc = new QProcess(this);
        rpm2tgzproc->start(ConvRpm2TgzCom);
        connect( rpm2tgzproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(rpm2tgzProcessFinished()));

        progress->exec();
    }
  else if(prfDlg->rpm2tgzComboBox->currentIndex() == 1)//index at 1= src2pkg script
    {
                ConvRpm2Tgz = "src2pkg "; //system command to install the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
                ConvRpm2TgzArgs = ConvRpm2Tgz.append(prfDlg->rpm2tgzArgsBox->text().append(" "));
                ConvRpm2TgzCom = ConvRpm2Tgz.append ( FileNamePath ); //adds the path to ConvRpm2Tgz


        progress->setLabelText("Converting Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        rpm2tgzproc = new QProcess(this);
        rpm2tgzproc->start(ConvRpm2TgzCom);
        connect( rpm2tgzproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(rpm2tgzProcessFinished()));

        progress->exec();
    }
}

void SlackpackImpl::rpm2tgzProcessFinished()
{
    progress->close();
    fileText.append(rpm2tgzproc->readAll());

        /*BEGGING ERROR TESTING*/
        if ( fileText.contains ( "ERROR:", FALSE ) )
        {
//inform user that there was an error.
         QMessageBox errorBox;
         errorBox.setText("Error Converting package\nSee the Console Output");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
        consolebox->setText ( fileText );
        statusBar()->showMessage(tr("Done."), (5000));
        }
        else
        {
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
//inform user that the convertion was succesfull
        QMessageBox infoBox;
        infoBox.setText("Package Converted in your home directory!");
        infoBox.setIcon(QMessageBox::Information);
        infoBox.exec();

        statusBar()->showMessage(tr("Done!"), (5000));
        }

        unsetCursor(); //restores cursor
}

void SlackpackImpl::deb2tgzbutton_clicked()
{
   prfDlg = new PreferencesDialog();
   //open file dialog to choose new package.
   FileNamePath = QFileDialog::getOpenFileName(
                    "",
                    "Debian Packages (*.deb)",
                    this,
                    "open file dialog",
                    "Select a .deb package to convert." );

	//check if user selected a pkg
	if ( FileNamePath.isEmpty() )
	{
//if filenamepath is empty, user pressed cancel
	return;
	}


		setCursor(Qt::WaitCursor); //set wait cursor
                statusBar()->showMessage(tr("Working..."));
		consolebox->clear(); //clears any remaing output text in the consolebox from previous action
                fileText.clear();

 //see user selected script
 if(prfDlg->deb2tgzComboBox->currentIndex() == 0)//index at 0= deb2tgz script
   {
		ConvDeb2Tgz = "deb2tgz "; //system command to install the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
                ConvDeb2TgzArgs = ConvDeb2Tgz.append(prfDlg->deb2tgzArgsBox->text().append(" "));
                ConvDeb2TgzCom = ConvDeb2Tgz.append ( FileNamePath ); //adds the path to DebRpm2Tgz

        progress->setLabelText("Converting Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        deb2tgzproc = new QProcess(this);
        deb2tgzproc->start(ConvDeb2TgzCom);
        connect( deb2tgzproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(deb2tgzProcessFinished()));

        progress->exec();
    }
  else if(prfDlg->deb2tgzComboBox->currentIndex() == 1)//index at 1= src2pkg script
   {
      QMessageBox t;
      t.setText("src2pkg");
      t.exec();
   }
}

void SlackpackImpl::deb2tgzProcessFinished()
{
    progress->close();
    fileText.append(deb2tgzproc->readAll());

    /*BEGGING ERROR TESTING*/
        if ( fileText.contains ( "does not have a .deb extension", FALSE ) )
        {
//inform user that there was an error.
         QMessageBox errorBox;
         errorBox.setText("Error Converting package\nSee the Console Output");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();

//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
        statusBar()->showMessage(tr("Done."), (5000));
        }
        else if( fileText.contains ( "ERROR", FALSE ) )
        {
//inform user that there was an error.
         QMessageBox errorBox;
         errorBox.setText("Error Converting package\nSee the Console Output");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();

//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
        statusBar()->showMessage(tr("Done."), (5000));
        }
        else
        {
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
                consolebox->setText ( fileText );
//inform user that the convertion was succesfull
         QMessageBox infoBox;
         infoBox.setText("Package Converted!");
         infoBox.setIcon(QMessageBox::Information);
         infoBox.exec();

         statusBar()->showMessage(tr("Done!"), (5000));
        }
         unsetCursor(); //restores cursor
}

/**List Packages Tab**/
void SlackpackImpl::pkgsearchbutton_clicked()
{
   QString searchText = pkgsearchBox->text();
   treeView->keyboardSearch(searchText);
}

void SlackpackImpl::remselbutton_clicked()
{
   /** get selected item info **/
   QModelIndexList indexes = treeView->selectionModel()->selectedIndexes();
   foreach (QModelIndex index, indexes)
        {
           pkgName = listModel->fileInfo( index ).absoluteFilePath ();
        }

 QMessageBox qBox;
 qBox.setText("Warning!");
 qBox.setInformativeText("Are you sure you want to remove selected package?");
 qBox.setIcon(QMessageBox::Warning);
 qBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
 int ret = qBox.exec();
            switch (ret) {
   case QMessageBox::No:
       {
         return;
       }
  case QMessageBox::Yes:
       {}
 }

        //hide the pkginfo widgets and show the console output widgets
        pkgdesclbl->hide();
        pkgdescText->hide();
        pkgfilelistlbl->hide();
        pkgfilelistText->hide();
        consoleOutlbl->show();
        consoleOutText->show();
        pkgsaveBtn->show();
        pkgcopyBtn->show();

        setCursor(Qt::WaitCursor); //sets wait cursor
        statusBar()->showMessage("Working...");
	consolebox->clear(); //clears any remaing output text in the consolebox from previous action
        fileText.clear();

	RemSelPkg = "removepkg "; //system command to remove the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
        RemSelPkgCom = RemSelPkg.append ( pkgName ); //RemSelPkg and the name of the selected package

        progress->setLabelText("Removing Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        remselproc = new QProcess(this);
        remselproc->start(RemSelPkgCom);
        connect( remselproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(remselProcessFinished()));

        progress->exec();

}

void SlackpackImpl::remselProcessFinished()
{
    progress->close();
    fileText.append(remselproc->readAll());
    consoleOutText->setText(fileText);

        /*BEGINNING ERROR TESTING >*/
        if ( fileText.contains ( "ERROR", FALSE ) )
        {
//inform user that there was an error on removing
         QMessageBox errorBox;
         errorBox.setText("Error Removing package\nSee the Console Output");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE DIALOG BOX
        statusBar()->showMessage("Done.", (5000));
        }
        /*< ENDS ERROR TESTING*/
        else
        {
//inform user that package is removed
         QMessageBox infoBox;
         infoBox.setText("Package Removed!");
         infoBox.setIcon(QMessageBox::Information);
         infoBox.exec();

         statusBar()->showMessage("Done.", (5000));
         unsetCursor(); //restores cursor
        }

        unsetCursor(); //restores cursor

}

void SlackpackImpl::upgradebutton_clicked()
{
	consolebox->clear();
        fileText.clear();

   /** get selected item info **/
   QModelIndexList indexes = treeView->selectionModel()->selectedIndexes();
   foreach (QModelIndex index, indexes)
        {
           pkgName = listModel->fileInfo( index ).absoluteFilePath ();
        }


        /*ERROR TESTING, check if user selected a pkg from list.*/
	if(pkgName.isNull())
	 {
          QMessageBox errorBox;
         errorBox.setText("You must select an already installed package from the list to upgrade!");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         statusBar()->showMessage("Done", (5000));
	 }
	else
	 {
         QMessageBox infoBox;
         infoBox.setText("Please select the newer version of the package.");
         infoBox.setIcon(QMessageBox::Information);
         infoBox.exec();

   //open file dialog to choose new package.
   FileNamePath = QFileDialog::getOpenFileName(
                    "",
                    "Slackware Package (*.tgz *.txz)",
                    this,
                    "open file dialog",
                    "Select a package." );

	if(FileNamePath.isEmpty())
	 {
         QMessageBox errorBox;
         errorBox.setText("You must select the newer version of the package!");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();

         statusBar()->showMessage("Done", (5000));
	 }
	else
	 {
        setCursor(Qt::WaitCursor); //sets wait cursor
        statusBar()->showMessage("Working...");


        //hide the pkginfo widgets and show the console output widgets
        pkgdesclbl->hide();
        pkgdescText->hide();
        pkgfilelistlbl->hide();
        pkgfilelistText->hide();
        consoleOutlbl->show();
        consoleOutText->show();
        pkgsaveBtn->show();
        pkgcopyBtn->show();

	UpgradePkg = "upgradepkg "; //system command to remove the pkg(ATTENTION!: the 'space' after the command is nesecery!!!
	UpgradeOldPkgName = UpgradePkg.append ( pkgName ); //adds the old package name to upgradepkg

        UpgradePkg.append("%");

	UpgradeNewPkgPath = UpgradePkg.append ( FileNamePath ); //adds the path to UpgradePkg
        UpgradePkgCom = UpgradeNewPkgPath;

        progress->setLabelText("Upgrading Package\nPlease Wait...");
        progress->setRange(0,0);
        progress->setWindowModality(Qt::WindowModal);

        upgradeproc = new QProcess(this);
        upgradeproc->start(UpgradePkgCom);
        connect( upgradeproc, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(upgradeProcessFinished()));

        progress->exec();

    }
   }
  }
void SlackpackImpl::upgradeProcessFinished()
{
    progress->close();
    fileText.append(upgradeproc->readAll());
    consoleOutText->setText(fileText);

        /*BEGINNING ERROR TESTING >*/
        if ( fileText.contains ( "Error:  there is no installed package named", FALSE ) )
        {
//inform user that there is no package installed
         QMessageBox errorBox;
         errorBox.setText("Error Upgrading the package\nSee the Console Output");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         statusBar()->showMessage("Done", (5000));
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
        }
        else if ( fileText.contains ( "Skipping package", FALSE ) )
        {
//inform user that package is already upgraded
         QMessageBox errorBox;
         errorBox.setText("Selected package is up-to-date");
         errorBox.setIcon(QMessageBox::Critical);
         errorBox.exec();
         statusBar()->showMessage("Done", (5000));
//PASTE OUTPUT'S FILE CONTENTS INTO THE CONSOLE BOX
        }
        /* ENDS ERROR TESTING*/
        else
        {

//inform user that package is upgraded
         QMessageBox infoBox;
         infoBox.setText("Package Upgraded!");
         infoBox.setIcon(QMessageBox::Information);
         infoBox.exec();

        statusBar()->showMessage("Done!", (5000));
        }

        unsetCursor(); //restores cursor


}


//


