/**********************************************************************************************
    Copyright (C) 2009 Oliver Eichler oliver.eichler@gmx.de

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

**********************************************************************************************/

#include "CDlgGpsSetup.h"
#include "IGps.h"
#include "CCanvas.h"
#include <QtGui>

CDlgGpsSetup::CDlgGpsSetup(QWidget * parent)
: QDialog(parent)
{
    setupUi(this);
    setupKeys(this);
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::Dialog);
    setAttribute(Qt::WA_DeleteOnClose, false);
    showFullScreen();

    pushKey1->setText(tr("ok"));
    connect(pushKey1, SIGNAL(clicked()), this, SLOT(slotKey1()));
    pushKey2->setText(tr("cancel"));
    connect(pushKey2, SIGNAL(clicked()), this, SLOT(slotKey2()));
    pushKey3->setText(tr(""));
    connect(pushKey3, SIGNAL(clicked()), this, SLOT(slotKey3()));
    pushKey4->setText(tr(""));
    connect(pushKey4, SIGNAL(clicked()), this, SLOT(slotKey4()));

#ifdef WINCE
    for(int i=0; i < 10; ++i) {
        comboPort->addItem(QString("COM %1").arg(i), QString("com%1:").arg(i));
    }
    radioSerial->hide();
    radioBluetooth->hide();
    comboBTDevices->hide();
    pushBTRefresh->hide();
#else
    comboPort->addItem(QString("/dev/gps"), QString("/dev/gps"));
    comboPort->setEnabled(false);
    spacerKeyboard->changeSize(20,0,QSizePolicy::Fixed,QSizePolicy::Fixed);
#endif
    comboRate->addItem(tr("4800"), 4800);
    comboRate->addItem(tr("9600"), 9600);
    comboRate->addItem(tr("19200"), 19200);
    comboRate->addItem(tr("38400"), 38400);
    comboRate->addItem(tr("57600"), 57600);

    comboSource->addItem(tr("None / Off"), IGps::eNoGps);
    comboSource->addItem(tr("NMEA"), IGps::eNMEA);
    comboSource->addItem(tr("NMEA/Mtk"), IGps::eNMEAMtk);
#ifdef WINCE
    comboSource->addItem(tr("Wince/GPSD"), IGps::eGpsd);
#endif

    QSettings cfg;
    IGps::dev_e dev = (IGps::dev_e)cfg.value("gps/device",IGps::eSerial).toInt();
    IGps::src_e src = (IGps::src_e)cfg.value("gps/source",IGps::eNMEA).toInt();
    QString port    = cfg.value("gps/port","").toString();
    int rate        = cfg.value("gps/rate",9600).toInt();
    QString name    = cfg.value("gps/name","").toString();
    QString mac     = cfg.value("gps/mac","").toString();

    comboPort->setCurrentIndex(comboPort->findData(port));
    comboRate->setCurrentIndex(comboRate->findData(rate));
    comboSource->setCurrentIndex(comboSource->findData(src));
    comboBTDevices->addItem(name, mac);

    connect(radioBluetooth, SIGNAL(toggled(bool)), this, SLOT(slotChangeBluetooth(bool)));
    radioBluetooth->setChecked(dev == IGps::eBluetooth);

    proc = new QProcess(this);
    connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotFinished(int, QProcess::ExitStatus)));
    connect(pushBTRefresh, SIGNAL(clicked()), this, SLOT(slotRefresh()));

}


CDlgGpsSetup::~CDlgGpsSetup()
{

}


void CDlgGpsSetup::slotKey1()
{
    QString port    = comboPort->itemData(comboPort->currentIndex()).toString();
    int rate        = comboRate->itemData(comboRate->currentIndex()).toInt();
    IGps::src_e src = (IGps::src_e)comboSource->itemData(comboSource->currentIndex()).toInt();
    IGps::dev_e dev = radioSerial->isChecked() ? IGps::eSerial : IGps::eBluetooth;

    QString mac, name;
    int idx = comboBTDevices->currentIndex();
    if(idx != -1) {
        name = comboBTDevices->itemText(idx);
        mac  = comboBTDevices->itemData(idx, Qt::UserRole).toString();
    }
    if(dev == IGps::eBluetooth && mac.isEmpty()) {
        QMessageBox::warning(this,"Error...", tr("You must select a Bluetooth device from the list."), QMessageBox::Ok,QMessageBox::Ok);
        return;
    }

    CCanvas::self().setGPS(src, port, rate, dev, name, mac);

    done(0);
}


void CDlgGpsSetup::slotKey2()
{

    done(-1);
}


void CDlgGpsSetup::slotKey3()
{
}


void CDlgGpsSetup::slotKey4()
{
}


void CDlgGpsSetup::slotChangeBluetooth(bool on)
{
    pushBTRefresh->setEnabled(on);
    comboBTDevices->setEnabled(on);
}


void CDlgGpsSetup::slotRefresh()
{
    pushBTRefresh->setEnabled(false);
    proc->start("/etc/QLandkarte/scan");
}


void CDlgGpsSetup::slotFinished( int /*exitCode*/, QProcess::ExitStatus /*exitStatus*/)
{
    pushBTRefresh->setEnabled(true);

    int idx     = comboBTDevices->currentIndex();
    QString mac = comboBTDevices->itemData(idx, Qt::UserRole).toString();

    comboBTDevices->clear();

    QRegExp re("\\s*([0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2})\\s*(\\S.*)");
    QString     out   = proc->readAll();
    QStringList lines = out.split("\n");
    QString     line;
    foreach(line, lines) {
        if(re.exactMatch(line.toUtf8())) {
            comboBTDevices->addItem(QString("%2").arg(re.cap(2)), re.cap(1));
        }
    }

    idx = comboBTDevices->findData(mac, Qt::UserRole);
    if(idx != -1) {
        comboBTDevices->setCurrentIndex(idx);
    }

}
