// [RAN 2014-06-02] Fixed switch statements.

#include "mainwindow.h"
#include "ui_mainwindow.h"


/// \fn MainWindow::MainWindow()
/// \~English
/// \brief Constructor
/// \~Spanish
/// \brief Constructor
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    filterMethod = 0 ;
}

/// \fn MainWindow::~MainWindow()
/// \~English
/// \brief Destructor
/// \~Spanish
/// \brief Destructor
MainWindow::~MainWindow()
{
    delete ui;
}


/// \fn void MainWindow::on_Filter_Box_currentIndexChanged(int index)
/// \~English
/// \brief Changes the ID of the filtering function chosen by the user
/// \~Spanish
/// \brief Cambia el ID de la funcion de filtro escogida por el usaurio
void MainWindow::on_Filter_Box_currentIndexChanged(int index)
{
    filterMethod = index ;
    ui->lineEdit->clear();   
}

/// \fn void MainWindow::on_actionLoad_Network_Data_triggered()
/// \~English
/// \brief Loads a network flow file into the GUI.
/// \~Spanish
/// \brief Carga un archivo de fluidos de red a la inteface de usuario.
void MainWindow::on_actionLoad_Network_Data_triggered()
{
    QString fname = QFileDialog::getOpenFileName(this, tr("Choose a file"), QDir::currentPath());
    if (!fname.isEmpty())
    {
        if(!ReadFile(fname.toStdString(), netdata)){
            QMessageBox::information(this, tr("Choose a correct path"),tr("Cannot load %1.").arg(fname));
            netdata.clear();
        }
        FillTable();
    }
}

/// \fn void MainWindow::on_actionAbout_triggered()
/// \~English
/// \brief Displays a short about of the app
/// \~Spanish
/// \brief Despliega un sobre corto de la aplicacion
void MainWindow::on_actionAbout_triggered()
{
    //display a message box
    QMessageBox::about(this, tr("About Network Filter"),
    tr("Network Traffic Analyzer"
       "\n\nThe program is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY "
       "OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE."));
}

/// \fn void MainWindow::on_actionExit_triggered()
/// \~English
/// \brief Exits the app
/// \~Spanish
/// \brief Sale de la aplicacion
void MainWindow::on_actionExit_triggered()
{
    QApplication::quit();
}


/// \fn void MainWindow::FillTable()
/// \~English
/// \brief Refresh the GUI packet list.
/// \~Spanish
/// \brief Rellena la lista de paquetes de la interface de usuarios.
void MainWindow::FillTable()
{
    numPackets = 0;
    numOctects = 0;

    ui->table->setRowCount(0);
    for(unsigned int i=0; i<netdata.size(); i++){

        if (!netdata[i].isEnabled()){
            continue ;
        }
        ui->table->insertRow(ui->table->rowCount());
        numPackets += netdata[i].getPackets() ;
        numOctects += netdata[i].getOctects() ;
        // cout << netdata[i].getSrcPort() << endl ;
        ui->table->setItem(ui->table->rowCount()-1,0, new QTableWidgetItem(QString::fromStdString(netdata[i].getSrcAddr()))) ;
        ui->table->setItem(ui->table->rowCount()-1,1, new QTableWidgetItem(QString::fromStdString(netdata[i].getDstAddr()))) ;
        ui->table->setItem(ui->table->rowCount()-1,2, new QTableWidgetItem(QString::number(netdata[i].getSrcPort()))) ;
        ui->table->setItem(ui->table->rowCount()-1,3, new QTableWidgetItem(QString::number(netdata[i].getDstPort()))) ;
        ui->table->setItem(ui->table->rowCount()-1,4, new QTableWidgetItem(QString::number(netdata[i].getOctects()))) ;
        ui->table->setItem(ui->table->rowCount()-1,5, new QTableWidgetItem(QString::number(netdata[i].getPackets()))) ;

    }


    ui->Octets_Label->setText("Octets: "+QString::number(numOctects));
    ui->Packets_Label->setText("Packets: "+QString::number(numPackets));

    if(ui->table->rowCount()>0)
    {
        ui->Octets_Average_Label->setText("Octets Average: "+QString::number(float(numOctects/ui->table->rowCount())));
        ui->Packets_Average_Label->setText("Packets Average: "+QString::number(float(numPackets/ui->table->rowCount())));
    }
    else
    {
        ui->Octets_Average_Label->setText("Octets Average: ERROR! ");
        ui->Packets_Average_Label->setText("Packets Average: ERROR! ");
    }
}

//================================================================================================================

/// \fn void MainWindow::on_runFilter_clicked()
/// \~English
/// \brief Invokes a filtering funtion that filter by the field chosen by the user.
/// \~Spanish
/// \brief Invoca una funcion de filtrar por el campo escogido por el usuario.
void MainWindow::on_runFilter_clicked()
{
    //cout << "FILTER" << filterMethod <<endl ;
    if(ui->lineEdit->text().length() < 1)
        return ;
    switch(filterMethod){
        case 0:
            FilterBySrcAddr(netdata, ui->lineEdit->text().toStdString());
            break ;
        case 1:
            FilterByDstAddr(netdata, ui->lineEdit->text().toStdString());
            break ;
        case 2:
            FilterBySrcPort(netdata, ui->lineEdit->text().toInt()) ;
            break ;
        case 3:
            FilterByDstPort(netdata, ui->lineEdit->text().toInt()) ;
            break ;
        default:
            break ;

    } ;
    FillTable() ;
}

/// \fn void MainWindow::on_clearButton_clicked()
/// \~English
/// \brief Removes any applied filter to the list of packets.
/// \~Spanish
/// \brief Remueve cualquier filtro aplicado a la lista de paquetes.
void MainWindow::on_clearButton_clicked()
{
    for(unsigned int i = 0; i < netdata.size(); i++)
        netdata[i].enable() ;
    FillTable() ;
}


/// \fn void MainWindow::on_sortButton_clicked()
/// \~English
/// \brief Invokes a sorting funtion that sorts by the field chosen by the user.
/// \~Spanish
/// \brief Invoca una funcion de ordenar por el campo escogido por el usuario.
void MainWindow::on_sortButton_clicked()
{

    switch(filterMethod){
        case 0:
            SortBySrcAddr(netdata);
            break ;
        case 1:
            SortByDstAddr(netdata);
            break ;
        case 2:
            SortBySrcPort(netdata) ;
            break ;
        case 3:
            SortByDstPort(netdata) ;
            break ;
        default:
            break ;

    } ;
    FillTable() ;
}


/// \fn void MainWindow::on_openFile_clicked()
/// \~English
/// \brief Open a file network flow packets.
/// \~Spanish
/// \brief Abre un archivo con paquetes de fluidos de red.
void MainWindow::on_openFile_clicked()
{
    on_actionLoad_Network_Data_triggered() ;
}


/// \fn void MainWindow::on_saveFile_clicked()
/// \~English
/// \brief Saves the network packets as appears in the window.
/// \~Spanish
/// \brief Guarda los paquetes de network como aparecen en la pantalla.
void MainWindow::on_saveFile_clicked()
{
    QString fname = QFileDialog::getSaveFileName(this, tr("Choose a file"), QDir::currentPath()) ;


    if (!fname.isEmpty())
    {
        if(!SaveFile(fname.toStdString(), netdata))
            QMessageBox::information(this, tr("Choose a correct path"),tr("Cannot save %1.").arg(fname));
    }
}
