/***********************************************************************
**
**   waypointlistview.cpp
**
**   This file is part of Cumulus.
**
************************************************************************
**
**   Copyright (c):  2002 by Andr�Somers
**
**   This file is distributed under the terms of the General Public
**   Licence. See the file COPYING for more information.
**
**   $Id: waypointlistview.cpp,v 1.32 2005/02/21 19:50:22 andre Exp $
**
***********************************************************************/

#include "waypointlistview.h"

#include <qlayout.h>
#include <qpushbutton.h>
#include <qlist.h>
#include <qmessagebox.h>
#include <qpe/resource.h>

#include "generalconfig.h"
#include "mapcontents.h"
#include "mapconfig.h"
#include "wpeditdialog.h"
#include "waypointcatalog.h"
#include "cumulusapp.h"

extern MapContents * _globalMapContents;
extern MapConfig * _globalMapConfig;

WaypointListView::WaypointListView(CumulusApp *parent, const char *name ) : QWidget(parent,name)
{
  par=parent;
//  resize(parent->size());
  QBoxLayout *topLayout = new QVBoxLayout( this );
  QBoxLayout *editrow=new QHBoxLayout(topLayout);

  editrow->addStretch(10);
  
  QPushButton * cmdNew = new QPushButton(this);
  cmdNew->setPixmap(Resource::loadPixmap("new"));
  cmdNew->setFlat(true);
  editrow->addWidget(cmdNew);
  
  QPushButton * cmdEdit = new QPushButton(this);
  cmdEdit->setPixmap(Resource::loadPixmap("edit"));
  cmdEdit->setFlat(true);
  editrow->addWidget(cmdEdit);

  QPushButton * cmdDel = new QPushButton(this);
  cmdDel->setPixmap(Resource::loadPixmap("trash"));
  cmdDel->setFlat(true);
  editrow->addWidget(cmdDel);
  //cmdDel->setEnabled(false);

  editrow->addSpacing(6);
  QPushButton * cmdHome = new QPushButton(this);
  cmdHome->setPixmap(Resource::loadPixmap("home"));
  cmdHome->setFlat(true);
  editrow->addWidget(cmdHome);

    
  list= new QListView(this, "waypointlist");
  list->addColumn(tr("Name"),75);
  list->addColumn(tr("Description"),105);
  list->addColumn(tr("ICAO"),40);

  list->setAllColumnsShowFocus(true);

  filter=new ListViewFilter(list, this, "listfilter");
  topLayout->addWidget(filter);

  fillWpList(par->WpCatalog);

  topLayout->addWidget(list,10);
  QBoxLayout *buttonrow=new QHBoxLayout(topLayout);

  QPushButton *cmdClose = new QPushButton(tr("Close"), this);
  buttonrow->addWidget(cmdClose);

  QPushButton *cmdInfo = new QPushButton(tr("Info"), this);
  buttonrow->addWidget(cmdInfo);

  QPushButton *cmdSelect = new QPushButton(tr("Select"), this);
  buttonrow->addWidget(cmdSelect);
  
  connect(cmdNew, SIGNAL(clicked()), this, SLOT(slot_newWP()));
  connect(cmdEdit, SIGNAL(clicked()), this, SLOT(slot_editWP()));
  connect(cmdDel, SIGNAL(clicked()), this, SLOT(slot_deleteWP()));
  connect(cmdHome, SIGNAL(clicked()), this, SLOT(slot_setHome()));
  connect(cmdSelect, SIGNAL(clicked()), this, SLOT(slot_Select()));
  connect(cmdInfo, SIGNAL(clicked()), this, SLOT(slot_Info()));
  connect(cmdClose, SIGNAL(clicked()), this, SLOT(slot_Close()));
}

WaypointListView::~WaypointListView(){
}

/** Retreives the waypoints from the mapcontents, and fills the list. */
void WaypointListView::fillWpList(WaypointCatalog *wpc){
  QList<wayPoint> * wpList = wpc->wpList;
  int n =  wpList->count();
  qDebug("WaypointListView::fillWpList() %d", n);
  list->clear();
  for (int i=0; i < n; i++){
    wayPoint * wp=(wayPoint*)wpList->at(i);
    new _WaypointItem(list, wp);
  }

  if (n>0) {
    list->setCurrentItem(list->firstChild());
  }
  filter->reset();
}

void WaypointListView::showEvent(QShowEvent *){
  list->setFocus();
}

/** This signal is called to indicate that a selection has been made. */
void WaypointListView::slot_Select()
{
  wayPoint * wp=getSelectedWaypoint();
  if (wp) {
    emit newWaypoint(getSelectedWaypoint());
    emit done();
  }
  filter->off();
}

/** This slot is called if the info button has been clicked */
void WaypointListView::slot_Info(){
  if (getSelectedWaypoint()!=0) 
  emit info(getSelectedWaypoint());
}

/** @ee This slot is called if the listview is closed without selecting */
void WaypointListView::slot_Close ()
{
  filter->off();
  emit done();
}

/** Returns a pointer to the currently highlighted waypoint. */
wayPoint * WaypointListView::getSelectedWaypoint()
{
  qDebug("WaypointListView::getSelectedWaypoint");
  QListViewItem* li = list->selectedItem();
  _WaypointItem* wpi = static_cast<_WaypointItem*>(li);
  if (!wpi)
    return 0;
    
  return wpi->wp;
}

/** Called when a new waypoint needs to be made. */
void WaypointListView::slot_newWP(){
  WPEditDialog * dlg=new WPEditDialog(this, "wpeditor", 0);
  connect(dlg, SIGNAL(wpListChanged(wayPoint *)), this, SLOT(slot_wpAdded(wayPoint *)));

  dlg->show();
  
}

/** Called when the selected waypoint needs must be opened in the editor */
void WaypointListView::slot_editWP(){
  wayPoint * wp=getSelectedWaypoint();
  if (wp) {
    WPEditDialog * dlg=new WPEditDialog(this, "wpeditor", getSelectedWaypoint());
    connect(dlg, SIGNAL(wpListChanged(wayPoint *)), this, SLOT(slot_wpEdited(wayPoint *)));

    dlg->show();
  }

}

/** Called when the selected waypoint should be deleted from the catalog */
void WaypointListView::slot_deleteWP(){

  if (getSelectedWaypoint()==0)
    return;
  
  int answer= QMessageBox::warning(this,tr("Delete?"),tr("Delete highlighted\nwaypoint?"),
      QMessageBox::Ok,
      QMessageBox::Cancel | QMessageBox::Escape | QMessageBox::Default);
 
  if (answer == 1) { //ok was chosen
    //first, make sure our waypointlist filter is won't interfere
    filter->restoreListViewItems();

    //next, obtain a reference to the waypoint
    wayPoint * wp=getSelectedWaypoint();

    emit deleteWaypoint(wp); // cancel the selected waypoint
    
    //remove from catalog
    WaypointCatalog * cat=par->WpCatalog;//(CumulusApp*)parent->WaypointCatalog;
    cat->wpList->remove(wp);
    cat->write();
    
    //remove from waypointlist in MapContents
    _globalMapContents->getWaypointList()->removeRef(wp);

    
    //remove from listView
    delete list->selectedItem();
    par->viewMap->_theMap->quickDraw();
    filter->reset(true);
  }
}

/** Called if a waypoint has been edited. */
void WaypointListView::slot_wpEdited(wayPoint * wp){
  if (wp!=0) {
    QListViewItem * li;
    li=list->selectedItem();
    if( li )
    {
      li->setText(0, wp->name);
      li->setText(1, wp->description);
      li->setText(2, wp->icao);
      li->setPixmap(0, _globalMapConfig->getPixmap(wp->type,false,true));
      list->sort();
      filter->reset();
    
      WaypointCatalog * cat=par->WpCatalog;//(CumulusApp*)parent->WaypointCatalog;
      cat->write();
      par->viewMap->_theMap->quickDraw();
    }
    else 
      qDebug("WaypointListView::slot_wpEdited() has empty list");
    
  }
}

/** Called if a waypoint has been added. */
void WaypointListView::slot_wpAdded(wayPoint * wp){
    qDebug("WaypointListView::slot_wpAdded");
  if (wp!=0) {
    wayPoint* newwp=new wayPoint(*wp);
    new _WaypointItem(list, newwp);
    list->sort();
    filter->reset();
    
    // qDebug("WaypointListView::slot_wpAdded(): name=%s",wp->name.latin1());

    WaypointCatalog * cat=par->WpCatalog;
    cat->wpList->append(newwp);
    cat->write();

    par->viewMap->_theMap->quickDraw();
  }
}

void WaypointListView::slot_setHome() {
  wayPoint * _wp = getSelectedWaypoint();
  if (_wp==0)
  {
    return;
  }

  int answer= QMessageBox::warning(this,tr("Set homesite?"),
      tr("Do you want to use waypoint\n%1\nas your homesite?").arg(_wp->name),
      QMessageBox::Ok | QMessageBox::Default,
      QMessageBox::Cancel | QMessageBox::Escape );
  if (answer == 1)
  { //ok was chosen

      // Save new data as home position
    GeneralConfig *conf = GeneralConfig::instance();
    wayPoint * w = new wayPoint(*_wp);
    conf->setHomeWp(w);
 //   conf->setHomeLat(_wp->origP.lat());
 //   conf->setHomeLon(_wp->origP.lon());
    conf->save();

    QPoint newPos( _wp->origP.lat(), _wp->origP.lon() );
    emit newHomePosition( &newPos );
  }
}

WaypointListView::_WaypointItem::_WaypointItem(QListView* lv, wayPoint* waypoint):
    QListViewItem(lv), 
    wp(waypoint)
{
    if (!wp)
        return;
        
    setText(0, wp->name);
    setText(1, wp->description);
    setText(2, wp->icao);
    setPixmap(0, _globalMapConfig->getPixmap(wp->type,false,true));
}


