#include <QChart>
#include <QChartView>
#include <QBarSet>
#include <QBarCategoryAxis>
#include <QValueAxis>
#include <QBarSeries>
#include <QSqlQuery>
#include <QDateTime>
#include <QDebug>
#include <QComboBox>
#include <QStringListModel>
#include <QGraphicsLayout>
#include <QMessageBox>
#include "StatisticsWidget.h"
#include "ui_StatisticsWidget.h"
#include "core/debug.h"
#include "models/SqlListModel.h"
#include "data/Gridsquare.h"
#include "core/QSOFilterManager.h"

MODULE_IDENTIFICATION("qlog.ui.statisticswidget");

void StatisticsWidget::mainStatChanged(int idx)
{
     FCT_IDENTIFICATION;

     qCDebug(function_parameters) << idx;

     setSubTypesCombo(idx);
     refreshGraph();
}

void StatisticsWidget::refreshWidget()
{
    FCT_IDENTIFICATION;

    pendingRefresh = true;
    mapRenderDirty = true;

    if ( !isVisible() || !initialized )
        return;

    refreshCombos();
    pendingRefresh = false;
    refreshGraph();
}

void StatisticsWidget::refreshGraph()
{
     FCT_IDENTIFICATION;

     if ( !isVisible() )
         return;

     QStringList genericFilter;

     genericFilter << " 1 = 1 "; //just initialization - use only in case of empty Options

     if ( ui->myCallCombo->currentIndex() != 0 )
         genericFilter << " (station_callsign = '" + ui->myCallCombo->currentText() + "') ";

     if ( ui->myGridCombo->currentIndex() != 0 )
     {
         if ( ui->myGridCombo->currentText().isEmpty() )
             genericFilter << " (my_gridsquare is NULL) ";
         else
             genericFilter << " (my_gridsquare = '" + ui->myGridCombo->currentText() + "') ";
     }

     if ( ui->myRigCombo->currentIndex() != 0 )
     {
         if ( ui->myRigCombo->currentText().isEmpty() )
             genericFilter << " (my_rig is NULL) ";
         else
             genericFilter << " (my_rig = '" + ui->myRigCombo->currentText() + "') ";
     }

     if ( ui->myAntennaCombo->currentIndex() != 0 )
     {
         if ( ui->myAntennaCombo->currentText().isEmpty() )
             genericFilter << " (my_antenna is NULL) ";
         else
             genericFilter << " (my_antenna = '" + ui->myAntennaCombo->currentText() + "') ";
     }

     if ( ui->bandCombo->currentIndex() != 0 &&  ! ui->bandCombo->currentText().isEmpty() )
         genericFilter << " (band = '" + ui->bandCombo->currentText() + "') ";

     if ( ui->useDateRangeCheckBox->isChecked() )
         genericFilter << " (datetime(start_time) BETWEEN datetime('" + ui->startDateEdit->dateTime().toString("yyyy-MM-dd HH:mm:ss")
                          + "') AND datetime('" + ui->endDateEdit->dateTime().toString("yyyy-MM-dd HH:mm:ss") + "') ) ";

     if ( ui->userFilterCombo->currentIndex() > 0 )
         genericFilter <<  QSOFilterManager::instance()->getWhereClause(ui->userFilterCombo->currentText());

     qCDebug(runtime) << "main " << ui->statTypeMainCombo->currentIndex()
                      << " secondary " << ui->statTypeSecCombo->currentIndex();

     /****************/
     /* QSO Per .... */
     /****************/
     if ( ui->statTypeMainCombo->currentIndex() == 0 )
     {
         QString stmt;

         switch ( ui->statTypeSecCombo->currentIndex() )
         {

         case 0: // Year
         case 1: // Month
         case 2: // Day in Week
         case 3: // Hour
         {
             QString startGenerator = "1";
             QString endGenerator = "12";
             QString formatGenerator = "%m";
             QString XYMapping = "col1, SUM(cnt)";

             if ( ui->statTypeSecCombo->currentIndex() == 0 )
             {
                 if ( ui->useDateRangeCheckBox->isChecked() )
                 {
                     startGenerator = ui->startDateEdit->date().toString("yyyy");
                     endGenerator = ui->endDateEdit->date().toString("yyyy");
                 }
                 else
                 {
                    startGenerator = "CAST(MIN(start_time) as INTEGER) from contacts";
                    endGenerator = " (select strftime('%Y', DATE()))";
                 }
                 formatGenerator = "%Y";
             }
             else if ( ui->statTypeSecCombo->currentIndex() == 1 )
             {
                 startGenerator = "1";
                 endGenerator = "12";
                 formatGenerator = "%m";
             }
             else if ( ui->statTypeSecCombo->currentIndex() == 2 )
             {
                 startGenerator = "0";
                 endGenerator = "6";
                 formatGenerator = "%w";
                 XYMapping = "case col1 when 0 THEN '" + tr("Sun") + "' "
                             "WHEN 1 THEN '" + tr("Mon") + "' "
                             "WHEN 2 THEN '" + tr("Tue") + "' "
                             "WHEN 3 THEN '" + tr("Wed") + "' "
                             "WHEN 4 THEN '" + tr("Thu") + "' "
                             "WHEN 5 THEN '" + tr("Fri") + "' "
                             "ELSE '" + tr("Sat") + "' END, "
                             "SUM(cnt) ";
             }
             else if ( ui->statTypeSecCombo->currentIndex() == 3 )
             {
                 startGenerator = "0";
                 endGenerator = "23";
                 formatGenerator = "%H";
             }

             stmt = "WITH RECURSIVE cnt(incnt) AS ( "
                    " SELECT " + startGenerator + " "
                    " UNION ALL "
                    " SELECT incnt + 1 "
                    " FROM cnt "
                    " WHERE incnt < " + endGenerator + " "
                    " ) "
                    " SELECT " + XYMapping + " "
                    " FROM "
                    " ( "
                    "   SELECT  incnt as col1, 0 as cnt from cnt "
                    "   UNION ALL "
                    "   SELECT CAST(strftime('" + formatGenerator +"', start_time) as INTEGER) as col1, count(1) as cnt "
                    "   FROM contacts "
                    "   WHERE " + genericFilter.join(" AND ") + " "
                    "   GROUP BY col1 "
                    " ) "
                    " GROUP BY col1 "
                    " ORDER BY col1";
         }
             break;
         case 4:  // Mode
             stmt = "SELECT IFNULL(mode, '" + tr("Not specified") + "'), COUNT(1) FROM contacts WHERE "
                     + genericFilter.join(" AND ") + " GROUP BY mode ORDER BY mode";
             break;
         case 5:  // Band
             stmt = "SELECT IFNULL(band, '" + tr("Not specified") + "'), cnt "
                    " FROM (SELECT c.band, b.start_freq, COUNT(1) AS cnt FROM contacts c LEFT JOIN bands b ON c.band = b.name"
                    " WHERE "
                    + genericFilter.join(" AND ")
                    + " GROUP BY band, start_freq) ORDER BY start_freq";
             break;
         case 6:  // Continent
             stmt = "SELECT IFNULL(cont, '" + tr("Not specified") + "'), COUNT(1) FROM contacts WHERE "
                    + genericFilter.join(" AND ")
                    + " GROUP BY cont ORDER BY cont";
             break;
         case 7:  // Prop Mode
             stmt = "SELECT IFNULL(prop_mode, '" + tr("Not specified") + "'), COUNT(1) FROM contacts WHERE "
                    + genericFilter.join(" AND ") + " GROUP BY prop_mode ORDER BY prop_mode";
             break;
         }

         qCDebug(runtime) << stmt;

         QSqlQuery query(stmt);

         drawBarGraphs(ui->statTypeMainCombo->currentText()
                       + " "
                       + ui->statTypeSecCombo->currentText(),
                       query);
     }
     /************/
     /* Percents */
     /************/
     else if ( ui->statTypeMainCombo->currentIndex() == 1 )
     {
         QString stmt;

         switch ( ui->statTypeSecCombo->currentIndex() )
         {

         case 0:  // Confirmed/Not Confirmed
             stmt = "SELECT (1.0 * COUNT(1)/(SELECT COUNT(1) AS total_cnt FROM contacts WHERE "
                    + genericFilter.join(" AND ") +")) * 100 FROM contacts WHERE "
                    + genericFilter.join(" AND ")
                    + " AND (eqsl_qsl_rcvd = 'Y' OR lotw_qsl_rcvd = 'Y' OR qsl_rcvd = 'Y')";
             break;
         }

         QSqlQuery query(stmt);

         qCDebug(runtime) << stmt;
         QPieSeries *series = new QPieSeries();

         query.next();

         float confirmed = query.value(0).toInt();
         float notConfirmed = 100.0 - confirmed;

         series->append(tr("Confirmed ") + QString::number(confirmed) + "%", confirmed);
         series->append(tr("Not Confirmed ") + QString::number(notConfirmed) + "%", notConfirmed);
         series->setLabelsVisible(true);

         drawPieGraph(QString(), series);
     }
     /**********/
     /* TOP 10 */
     /**********/
     else if ( ui->statTypeMainCombo->currentIndex() == 2 )
     {
         QString stmt;

         switch ( ui->statTypeSecCombo->currentIndex() )
         {
         case 0:  // Countries
             stmt = "SELECT translate_to_locale(COALESCE(d.name, c.dxcc)) as dxcc_display, COUNT(1) AS cnt "
                    "FROM ( SELECT * FROM contacts WHERE " + genericFilter.join(" AND ") + ") c LEFT JOIN dxcc_entities_clublog d ON c.dxcc = d.id "
                    "GROUP BY dxcc_display ORDER BY cnt DESC LIMIT 10";
             break;
         case 1:  // Big squares
             stmt = "SELECT SUBSTR(gridsquare,1,4), COUNT(1) AS cnt FROM contacts WHERE gridsquare IS NOT NULL GROUP by SUBSTR(gridsquare,1,4) ORDER BY cnt DESC LIMIT 10";
             break;
         }

         qCDebug(runtime) << stmt;

         QSqlQuery query(stmt);

         drawBarGraphs(ui->statTypeMainCombo->currentText()
                       + " "
                       + ui->statTypeSecCombo->currentText(),
                       query);

     }
     /*************/
     /* Histogram */
     /*************/
     else if ( ui->statTypeMainCombo->currentIndex() == 3 )
     {
         QString stmt;

         switch ( ui->statTypeSecCombo->currentIndex() )
         {
         case 0:  // Distance
             QString distCoef = QString::number(Gridsquare::localeDistanceCoef(locale));
             stmt = QString("WITH hist AS ( "
                    " SELECT CAST((distance * %1)/500.00 AS INTEGER) * 500 as dist_floor, "
                    " COUNT(1) AS count "
                    " FROM contacts "
                    " WHERE " + genericFilter.join(" AND ") + " AND distance IS NOT NULL "
                    " GROUP BY 1 "
                    " ORDER BY 1 "
                    " ) "
                    //" SELECT dist_floor || ' - ' || (dist_floor + 500) as dist_range, count "
                    "SELECT dist_floor as dist_range, count "
                    " FROM hist "
                    " ORDER BY 1").arg(distCoef);
             break;
         }

         qCDebug(runtime) << stmt;

         QSqlQuery query(stmt);

         drawBarGraphs(ui->statTypeMainCombo->currentText()
                       + " "
                       + ui->statTypeSecCombo->currentText(),
                       query);
     }
     /***************/
     /* Show on Map */
     /***************/
     else if ( ui->statTypeMainCombo->currentIndex() == 4 )
     {
         ui->stackedWidget->setCurrentIndex(1);

         QStringList confirmed("1=2 ");

         if ( ui->eqslCheckBox->isChecked() )
             confirmed << " eqsl_qsl_rcvd = 'Y' ";

         if ( ui->lotwCheckBox->isChecked() )
             confirmed << " lotw_qsl_rcvd = 'Y' ";

         if ( ui->paperCheckBox->isChecked() )
             confirmed << " qsl_rcvd = 'Y' ";

         const QString currentRenderKey = currentMapRenderKey(genericFilter);
         if ( !mapRenderKey.isEmpty()
              && !mapRenderDirty
              && currentRenderKey == mapRenderKey )
         {
             mapController->invalidateSize();
             return;
         }

         QString innerCase = " CASE WHEN (" + confirmed.join("or") + ") THEN 1 ELSE 0 END ";
         QString stmtMyLocations = "SELECT DISTINCT my_gridsquare FROM contacts WHERE " + genericFilter.join(" AND ");
         QSqlQuery myLocations(stmtMyLocations);

         qCDebug(runtime) << stmtMyLocations;

         drawMyLocationsOnMap(myLocations);

         QString stmt;

         switch ( ui->statTypeSecCombo->currentIndex() )
         {
         case 0: // QSOs
         case 1: // Confirmed & WorkedGrids
             stmt = "SELECT callsign, gridsquare, my_gridsquare, SUM(confirmed) FROM (SELECT callsign, gridsquare, my_gridsquare,"
                        + innerCase +" AS confirmed FROM contacts WHERE gridsquare is not NULL AND "
                        + genericFilter.join(" AND ") +" ) GROUP BY callsign, gridsquare, my_gridsquare";
             break;
         case 2: // ODX
             QString unit;
             Gridsquare::distance2localeUnitDistance(0, unit, locale);
             QString distCoef = QString::number(Gridsquare::localeDistanceCoef(locale));
             QString sel = QString("SELECT callsign || '<br>' || CAST(ROUND(distance * %1,0) AS INT) || ' %2', gridsquare, my_gridsquare, ").arg(distCoef, unit);

             stmt = sel + innerCase + " AS confirmed FROM contacts WHERE "
                        + genericFilter.join(" AND ") + " AND distance = (SELECT MAX(distance) FROM contacts WHERE "
                        + genericFilter.join(" AND ") + ")";
             break;
         }

         QSqlQuery query(stmt);
         qCDebug(runtime) << stmt;

         switch ( ui->statTypeSecCombo->currentIndex() )
         {
         case 0:
         case 2:
             drawPointsOnMap(query);
             break;

         case 1:
             drawFilledGridsOnMap(query);
             break;
         }

         mapRenderKey = currentRenderKey;
         mapRenderDirty = false;
         mapController->invalidateSize();
     }
}

void StatisticsWidget::dateRangeCheckBoxChanged(int)
{
    FCT_IDENTIFICATION;

    if ( ui->useDateRangeCheckBox->isChecked() )
    {
        ui->startDateEdit->setEnabled(true);
        ui->endDateEdit->setEnabled(true);
    }
    else
    {
        ui->startDateEdit->setEnabled(false);
        ui->endDateEdit->setEnabled(false);
    }

    refreshGraph();
}

void StatisticsWidget::changeTheme(int theme, bool isDark)
{
    FCT_IDENTIFICATION;

    qCDebug(function_parameters) << theme << isDark;

    mapController->setDarkTheme(isDark);
}

StatisticsWidget::StatisticsWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::StatisticsWidget),
    mapController(new MapPageController(QStringLiteral("statistics"), this))
{
    FCT_IDENTIFICATION;

    ui->setupUi(this);

    ui->myCallCombo->setModel(new QStringListModel(this));
    ui->myGridCombo->setModel(new QStringListModel(this));
    ui->myRigCombo->setModel(new QStringListModel(this));
    ui->myAntennaCombo->setModel(new QStringListModel(this));
    ui->bandCombo->setModel(new QStringListModel(this));
    ui->userFilterCombo->setModel(QSOFilterManager::QSOFilterModel(tr("No User Filter"),
                                                                   ui->userFilterCombo));

    ui->startDateEdit->setDisplayFormat(locale.formatDateTimeShortWithYYYY());
    ui->startDateEdit->setDate(QDate::currentDate().addDays(DEFAULT_STAT_RANGE));
    ui->startDateEdit->setTime(QTime::fromMSecsSinceStartOfDay(0));
    ui->endDateEdit->setDisplayFormat(locale.formatDateTimeShortWithYYYY());
    ui->endDateEdit->setDate(QDate::currentDate());
    ui->endDateEdit->setTime(QTime::fromMSecsSinceStartOfDay(86399999));

    ui->graphView->setRenderHint(QPainter::Antialiasing);
    ui->graphView->setChart(new QChart());

    mapController->attach(ui->mapView,
                          MapLayer::Grid
                          | MapLayer::Path);
}

StatisticsWidget::~StatisticsWidget()
{
    FCT_IDENTIFICATION;
    delete ui;
}

bool StatisticsWidget::event(QEvent *event)
{
    if (event->type() == QEvent::Show)
    {
        if ( !initialized )
            initializeWidget();
        else if ( pendingRefresh )
            refreshWidget();
        else if ( ui->stackedWidget->currentWidget() == ui->mapPage )
            mapController->invalidateSize();
    }
    return QWidget::event(event);  // Propagate the event further
}

void StatisticsWidget::drawBarGraphs(const QString &title, QSqlQuery &query)
{
    FCT_IDENTIFICATION;

    if ( query.lastQuery().isEmpty() ) return;

    QChart *chart = ui->graphView->chart();

    if ( chart != nullptr )
        chart->deleteLater();

    chart = new QChart();
    QBarSet* set = new QBarSet(title, chart);
    QBarCategoryAxis* axisX = new QBarCategoryAxis(chart);
    QBarSeries* series = new QBarSeries(chart);
    QValueAxis *axisY = new QValueAxis(chart);

    while ( query.next() )
    {
        axisX->append(query.value(0).toString());
        *set << query.value(1).toInt();
    }

    series->append(set);
    chart->addSeries(series);
    chart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);

    axisY->setTickCount(10);
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);
    axisY->applyNiceNumbers();
    axisY->setLabelFormat("%d");

    series->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
    series->setLabelsVisible(true);

    chart->setTitle(title);
    chart->legend()->hide();
    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->layout()->setContentsMargins(0, 0, 0, 0);
    chart->setBackgroundRoundness(0);

    ui->stackedWidget->setCurrentIndex(0);
    ui->graphView->setChart(chart);
}

void StatisticsWidget::drawPieGraph(const QString &title, QPieSeries *series)
{
    FCT_IDENTIFICATION;

    QChart *chart = ui->graphView->chart();

    if ( chart != nullptr )
        chart->deleteLater();

    chart = new QChart();

    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->addSeries(series);
    chart->legend()->hide();
    chart->setTitle(title);

    ui->stackedWidget->setCurrentIndex(0);
    ui->graphView->setChart(chart);
}

void StatisticsWidget::drawMyLocationsOnMap(QSqlQuery &query)
{
    FCT_IDENTIFICATION;

    if ( query.lastQuery().isEmpty() )
        return;

    QList<MapPoint> locationIcons;
    QList<MapCoordinate> rawLocationsPoint;

    while ( query.next() )
    {
        const QString &loc = query.value(0).toString();
        const Gridsquare stationGrid = Gridsquare::mapDisplayGrid(loc);

        if ( stationGrid.isValid() )
        {
            double lat = stationGrid.getLatitude();
            double lon = stationGrid.getLongitude();
            locationIcons << MapPoint(stationGrid.getGrid(), lat, lon, QStringLiteral("homeIcon"));
            rawLocationsPoint << MapCoordinate(lat, lon);
        }
    }

    mapController->clearGridLayers();
    mapController->drawHomePoints(locationIcons);
    mapController->redrawGridLayer();
    mapController->panToBoundsLongitudeCenter(rawLocationsPoint);
}

void StatisticsWidget::drawPointsOnMap(QSqlQuery &query)
{
    FCT_IDENTIFICATION;

    if ( query.lastQuery().isEmpty() )
        return;

    QList<MapPoint> stations;
    QList<MapPath> shortPaths;

    qulonglong count = 0;

    while ( query.next() )
    {
        const Gridsquare stationGrid = Gridsquare::mapDisplayGrid(query.value(1).toString());
        const Gridsquare myStationGrid = Gridsquare::mapDisplayGrid(query.value(2).toString());
        if ( stationGrid.isValid() )
        {
            count++;
            double lat = stationGrid.getLatitude();
            double lon = stationGrid.getLongitude();

            if ( myStationGrid.isValid() )
            {
                // do not wrap the points
                double delta = lon - myStationGrid.getLongitude();
                if ( delta > 180 )
                    lon -= 360;
                if ( delta < -180 )
                    lon += 360;

                shortPaths << MapPath(MapCoordinate(myStationGrid.getLatitude(),
                                                    myStationGrid.getLongitude()),
                                      MapCoordinate(lat, lon));
            }

            stations << MapPoint(query.value(0).toString(),
                                 lat,
                                 lon,
                                 (query.value(3).toInt()) > 0 ? QStringLiteral("greenIconSmall")
                                                               : QStringLiteral("yellowIconSmall"));
        }
    }

    if ( count > 50000 )
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, tr("Statistics"), tr("Over 50000 QSOs. Display them?"),
                                      QMessageBox::Yes|QMessageBox::No);

        if ( reply != QMessageBox::Yes )
        {
            stations.clear();
            shortPaths.clear();
        }
    }

    mapController->clearGridLayers();
    mapController->drawPointsAndShortPathsBusy(stations, shortPaths, tr("Rendering QSOs..."));
    mapController->redrawGridLayer();
}

void StatisticsWidget::drawFilledGridsOnMap(QSqlQuery &query)
{
    FCT_IDENTIFICATION;


    if ( query.lastQuery().isEmpty() ) return;

    QStringList confirmedGrids;
    QStringList workedGrids;

    while ( query.next() )
    {
        const Gridsquare grid = Gridsquare::mapDisplayGrid(query.value(1).toString());

        if ( !grid.isValid() )
            continue;

        const QString gridString = grid.getGrid();

        if ( query.value(3).toInt() > 0 )
        {
            if ( !confirmedGrids.contains(gridString) )
                confirmedGrids << gridString;
            workedGrids.removeAll(gridString);
        }
        else if ( !confirmedGrids.contains(gridString)
                  && !workedGrids.contains(gridString) )
        {
            workedGrids << gridString;
        }
    }

    mapController->setGridLayers(confirmedGrids, workedGrids);
    mapController->drawPointsBusy(QList<MapPoint>(), QString());
    mapController->drawShortPathsBusy(QList<MapPath>(), QString());
    mapController->redrawGridLayer();
}

void StatisticsWidget::refreshCombos()
{
    FCT_IDENTIFICATION;

    refreshCombo(ui->myCallCombo, QLatin1String("SELECT DISTINCT UPPER(station_callsign) FROM contacts ORDER BY station_callsign"));
    refreshCombo(ui->myRigCombo, QLatin1String("SELECT DISTINCT my_rig FROM contacts ORDER BY my_rig"));
    refreshCombo(ui->myAntennaCombo, QLatin1String("SELECT DISTINCT my_antenna FROM contacts ORDER BY my_antenna"));
    refreshCombo(ui->bandCombo, QLatin1String("SELECT DISTINCT band FROM contacts c, bands b WHERE c.band = b.name ORDER BY b.start_freq;"));
    refreshCombo(ui->myGridCombo, QLatin1String("SELECT DISTINCT UPPER(my_gridsquare) FROM contacts ORDER BY my_gridsquare"));
    SqlListModel *sqlModel = qobject_cast<SqlListModel*>(ui->userFilterCombo->model());
    if ( sqlModel ) sqlModel->refresh();
}

void StatisticsWidget::setSubTypesCombo(int mainTypeIdx)
{
    FCT_IDENTIFICATION;

    ui->statTypeSecCombo->blockSignals(true);

    ui->statTypeSecCombo->clear();

    ui->lotwCheckBox->setEnabled(false);
    ui->eqslCheckBox->setEnabled(false);
    ui->paperCheckBox->setEnabled(false);

    switch ( mainTypeIdx )
    {
    /* QSOs per */
    case 0:
    {
        ui->statTypeSecCombo->addItem(tr("Year"));
        ui->statTypeSecCombo->addItem(tr("Month"));
        ui->statTypeSecCombo->addItem(tr("Day in Week"));
        ui->statTypeSecCombo->addItem(tr("Hour"));
        ui->statTypeSecCombo->addItem(tr("Mode"));
        ui->statTypeSecCombo->addItem(tr("Band"));
        ui->statTypeSecCombo->addItem(tr("Continent"));
        ui->statTypeSecCombo->addItem(tr("Propagation Mode"));
    }
    break;

    /* Percents */
    case 1:
    {
        ui->statTypeSecCombo->addItem(tr("Confirmed / Not Confirmed"));
    }
    break;

    /* TOP 10 */
    case 2:
    {
        ui->statTypeSecCombo->addItem(tr("Countries"));
        ui->statTypeSecCombo->addItem(tr("Big Gridsquares"));
    }
    break;

    /* Histogram */
    case 3:
    {
        QString unit;
        Gridsquare::distance2localeUnitDistance(0, unit, locale);
        ui->statTypeSecCombo->addItem(tr("Distance") + QString(" [%1]").arg(unit));
    }
    break;

    /* Show on Map */
    case 4:
    {
        ui->statTypeSecCombo->addItem(tr("QSOs"));
        ui->statTypeSecCombo->addItem(tr("Confirmed/Worked Grids"));
        ui->statTypeSecCombo->addItem(tr("ODX"));
        ui->lotwCheckBox->setEnabled(true);
        ui->eqslCheckBox->setEnabled(true);
        ui->paperCheckBox->setEnabled(true);
    }
    break;
    }

    ui->statTypeSecCombo->blockSignals(false);
}

void StatisticsWidget::refreshCombo(QComboBox * combo,
                                    const QString &sqlQeury)
{
    FCT_IDENTIFICATION;

    QString currSelection = combo->currentText();

    combo->blockSignals(true);
    combo->setModel(new SqlListModel(sqlQeury,tr("All"), this));
    combo->setCurrentText(currSelection);
    combo->blockSignals(false);
}

void StatisticsWidget::initializeWidget()
{
    FCT_IDENTIFICATION;

    // We will not initialize the combos in the constructor. The constructor should
    // stay fast, so the first real show populates them and sets default selections.
    refreshCombos();
    ui->statTypeMainCombo->blockSignals(true);
    ui->statTypeMainCombo->setCurrentIndex(0);
    ui->statTypeMainCombo->blockSignals(false);
    setSubTypesCombo(ui->statTypeMainCombo->currentIndex());
    ui->myRigCombo->blockSignals(true);
    ui->myRigCombo->setCurrentIndex(0);
    ui->myRigCombo->blockSignals(false);
    ui->myAntennaCombo->blockSignals(true);
    ui->myAntennaCombo->setCurrentIndex(0);
    ui->myAntennaCombo->blockSignals(false);
    ui->userFilterCombo->blockSignals(true);
    ui->userFilterCombo->setCurrentIndex(0);
    ui->userFilterCombo->blockSignals(false);

    initialized = true;
    pendingRefresh = false;
    refreshGraph();
}

QString StatisticsWidget::currentMapRenderKey(const QStringList &genericFilter) const
{
    QStringList key;

    key << QString::number(ui->statTypeMainCombo->currentIndex())
        << QString::number(ui->statTypeSecCombo->currentIndex())
        << genericFilter.join(QLatin1String(" AND "))
        << QString::number(ui->eqslCheckBox->isChecked())
        << QString::number(ui->lotwCheckBox->isChecked())
        << QString::number(ui->paperCheckBox->isChecked());

    return key.join(QLatin1Char('\n'));
}
