/**********************************************************************************************
    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 "CDlgWptEdit.h"
#include "CDlgWptIcon.h"
#include "CWpt.h"
#include "CWptDB.h"
#include "WptIcons.h"
#include "GeoMath.h"
#include "CCanvas.h"
#include "CDlgMenu.h"

#include <proj_api.h>

#include <QtGui>

CDlgWptEdit::CDlgWptEdit(CWpt& wpt, QWidget * parent)
: QDialog(parent)
, wpt(wpt)
, imgIdx(-1)
{
    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("delete"));
    connect(pushKey3, SIGNAL(clicked()), this, SLOT(slotKey3()));
    pushKey4->setText(tr("goto"));
    connect(pushKey4, SIGNAL(clicked()), this, SLOT(slotKey4()));

    connect(toolIcon, SIGNAL(clicked()), this, SLOT(slotSelectIcon()));

    connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabChanged(int)));
#ifdef WINCE

#else
    spacerKeyboard->changeSize(20,0,QSizePolicy::Fixed,QSizePolicy::Fixed);
#endif

}

CDlgWptEdit::~CDlgWptEdit()
{

}

int CDlgWptEdit::exec()
{
    toolIcon->setIcon(getWptIconByName(wpt.icon));
    toolIcon->setObjectName(wpt.icon);
    lineName->setText(wpt.name);

    QString position;
    GPS_Math_Deg_To_Str(wpt.lon, wpt.lat, position);
    linePosition->setText(position);
    if(wpt.ele != WPT_NOFLOAT){
        lineAltitude->setText(QString::number(wpt.ele));
    }
    if(wpt.prx != WPT_NOFLOAT){
        lineProximity->setText(QString::number(wpt.prx));
    }
    labelTimestamp->setText(QDateTime::fromTime_t(wpt.timestamp).toString());

    textComment->setText(wpt.comment);

    if(wpt.images.count()){
        imgIdx = 0;
        showImage(imgIdx);
    }

    return QDialog::exec();
}

void CDlgWptEdit::showImage(int idx)
{
    if(idx < 0 || idx >= wpt.images.size()){
        return;
    }

    CWpt::image_t& img = wpt.images[idx];

    QSize s1 = lblImages->size();
    QSize s2 = img.pixmap.size();

    qDebug() << s1 << s2;

    qreal ratio1 = (qreal)s1.width()/(qreal)s1.height();
    qreal ratio2 = (qreal)s2.width()/(qreal)s2.height();

    qDebug() << ratio1 <<ratio2;

    if(ratio1 < 1){
        // viewport is portrait
        if(ratio2 < 1){
            if(ratio1 > ratio2){
                lblImages->setPixmap(img.pixmap.scaledToHeight(s1.height(),Qt::SmoothTransformation));
            }
            else{
                lblImages->setPixmap(img.pixmap.scaledToWidth(s1.width(),Qt::SmoothTransformation));
            }
        }
        else{
            if(ratio1 < ratio2){
                lblImages->setPixmap(img.pixmap.scaledToWidth(s1.width(),Qt::SmoothTransformation));
            }
            else{
                lblImages->setPixmap(img.pixmap.scaledToHeight(s1.height(),Qt::SmoothTransformation));
            }
        }
    }
    else{
        // viewport is landscape
        if(ratio2 < 1){
            lblImages->setPixmap(img.pixmap.scaledToHeight(s1.height(),Qt::SmoothTransformation));
        }
        else{
            lblImages->setPixmap(img.pixmap.scaledToWidth(s1.width(),Qt::SmoothTransformation));
        }
    }

    qDebug() << lblImages->pixmap()->size();
}

bool CDlgWptEdit::eventFilter(QObject *obj, QEvent *event)
{
    return IKeys::eventFilter(obj, event);
}


void CDlgWptEdit::slotKey1()
{
    wpt.icon    = toolIcon->objectName();
    wpt.name    = lineName->text();
    wpt.comment = textComment->toPlainText();

    qreal lon, lat;
    if(!GPS_Math_Str_To_Deg(linePosition->text(), lon, lat)){
        return;
    }

    wpt.lon = lon;
    wpt.lat = lat;

    if(lineAltitude->text().isEmpty()){
        wpt.ele = WPT_NOFLOAT;
    }
    else{
        wpt.ele = lineAltitude->text().toFloat();
    }

    if(lineProximity->text().isEmpty()){
        wpt.prx = WPT_NOFLOAT;
    }
    else{
        wpt.prx = lineProximity->text().toFloat();
    }

    QString errmsg;

    if(!CWptDB::self().add(wpt, errmsg)){
        QMessageBox::critical(this, tr("Error..."), tr("Database error: %1").arg(errmsg), QMessageBox::Abort, QMessageBox::Abort);
    }
    done(0);
}


void CDlgWptEdit::slotKey2()
{
        done(-1);
}


void CDlgWptEdit::slotKey3()
{
    if(tabWidget->currentIndex() == 2){
        if(imgIdx == -1) return;

        imgIdx--;
        if(imgIdx < 0){
            imgIdx = wpt.images.count() - 1;
        }

        showImage(imgIdx);

    }
    else{

        QMessageBox::StandardButton res = QMessageBox::question(this, tr("Delete waypoint..."), tr("Really delete: %1").arg(wpt.name), QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Ok);
        if(res != QMessageBox::Ok){
            return;
        }

        QString errmsg;
        if(!CWptDB::self().del(wpt.key(), errmsg)){
            QMessageBox::critical(this, tr("Error..."), tr("Database error: %1").arg(errmsg), QMessageBox::Abort, QMessageBox::Abort);
            return;
        }
        done(0);
    }
}


void CDlgWptEdit::slotKey4()
{
    if(tabWidget->currentIndex() == 2){
        if(imgIdx == -1) return;

        imgIdx++;

        if(imgIdx == wpt.images.count()){
            imgIdx = 0;
        }

        showImage(imgIdx);

    }
    else{

        qreal lon = wpt.lon * DEG_TO_RAD;
        qreal lat = wpt.lat * DEG_TO_RAD;

        CCanvas::self().setUsrPos(lon,lat);

        done(0);

        CDlgMenu * main = CDlgMenu::self();
        if(main){
            main->close();
        }
    }
}

void CDlgWptEdit::slotSelectIcon()
{
    CDlgWptIcon dlg(*toolIcon, this);
    dlg.exec();
}

void CDlgWptEdit::slotTabChanged(int idx)
{
    if(idx == 2){
        pushKey3->setText(tr(""));
        pushKey4->setText(tr(""));
        pushKey3->setIcon(QIcon(":/icons/prev_dialog32x32"));
        pushKey4->setIcon(QIcon(":/icons/next_dialog32x32"));
        showImage(imgIdx);
    }
    else{
        pushKey3->setText(tr("delete"));
        pushKey4->setText(tr("goto"));
        pushKey3->setIcon(QIcon(""));
        pushKey4->setIcon(QIcon(""));

    }
}
