/***********************************************************************
**
**   waypointcatalog.cpp
**
**   This file is part of KFLog2, modified for Cumulus.
**
************************************************************************
**
**   Copyright (c):  2001 by Harald Maier, 2002 André Somers
**
**   This file is distributed under the terms of the General Public
**   Licence. See the file COPYING for more information.
**
**   $Id: waypointcatalog.cpp,v 1.11 2005/02/26 20:24:20 axel Exp $
**
***********************************************************************/
#include "targets.h"
#include <pwd.h>
#include <unistd.h>

#include <qapplication.h>
#include <qobject.h>
#include <qpe/global.h>
#include <qdatastream.h>
#include <qdatetime.h>
#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qregexp.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qtextstream.h>

#include "waypointcatalog.h"
#include "airport.h"
#include "mapcontents.h"
#include "generalconfig.h"

extern MapContents* _globalMapContents;

WaypointCatalog::WaypointCatalog()
  : modified(false), onDisc(false)
{
  GeneralConfig *conf = GeneralConfig::instance();
  path = conf->getWaypointFile();
  showAll = true;
  showAirports = showGliderSites = showOtherSites = showObstacle = showLandmark = showOutlanding =
  showStation = false;
  wpList = _globalMapContents->getWaypointList();
  areaLat1 = areaLat2 = areaLong1 = areaLong2 = radiusLat = radiusLong = 1;
}

WaypointCatalog::~WaypointCatalog()
{
}

/** read a catalog from file */
bool WaypointCatalog::read(QString &catalog)
{
  GeneralConfig *conf = GeneralConfig::instance();

  bool ok = false;
  QString wpName="";
  QString wpDescription="";
  QString wpICAO="";
  Q_INT8 wpType;
  Q_INT32 wpLatitude;
  Q_INT32 wpLongitude;
  Q_INT16 wpElevation;
  double wpFrequency=0.;
  Q_INT8 wpLandable;
  Q_INT16 wpRunway;
  Q_INT16 wpLength;
  Q_INT8 wpSurface;
  QString wpComment="";
  Q_UINT8 wpImportance;

  Q_UINT32 fileMagic;
  Q_INT8 fileType;
  Q_UINT16 fileFormat;

  qDebug("Read waypoint catalog from %s", catalog.latin1() );

  // file location: /home/root/Applications/cumulus/cumulus.kwp

  QFile f(catalog);

  if (f.exists()) {
    if (f.open(IO_ReadOnly)) {

      QDataStream in(&f);
      in.setVersion(2);

      //check if the file has the correct format
      in >> fileMagic;
      if (fileMagic != KFLOG_FILE_MAGIC) {
        qWarning("Waypoint file not recognized as KFLog filetype.");
        return false;
      }

      in >> fileType;
      if (fileType != FILE_TYPE_WAYPOINTS) {
        qWarning("Waypoint file is a KFLog file, but not for waypoints.");
        return false;
      }

      in >> fileFormat;
      if (fileFormat != FILE_FORMAT_ID && fileFormat != FILE_FORMAT_ID_2) {
        qWarning("Waypoint file does not have the correct format. It returned %d, where %d was expected.", fileFormat, FILE_FORMAT_ID);
        return false;
      }
    //from here on, we assume that the file has the correct format.

      while(!in.eof()) {
        // read values from file
          in >> wpName;
          in >> wpDescription;
          in >> wpICAO;
          in >> wpType;
          in >> wpLatitude;
          in >> wpLongitude;
          in >> wpElevation;
          in >> wpFrequency;
          in >> wpLandable;
          in >> wpRunway;
          in >> wpLength;
          in >> wpSurface;
          in >> wpComment;
          if (fileFormat>=FILE_FORMAT_ID_2) {
            in >> wpImportance;
          } else {
            wpImportance=1; //normal importance
          };

       //create new waypoint object and set the correct properties
          wayPoint *w = new wayPoint;

          w->name = wpName;
          w->description = wpDescription;
          w->icao = wpICAO;
          w->type = wpType;
          w->origP.setLat(wpLatitude);
          w->origP.setLon(wpLongitude);
          w->elevation = wpElevation;
          w->frequency = wpFrequency;
          w->isLandable = wpLandable;
          w->runway =wpRunway;
          w->length = wpLength;
          w->surface = wpSurface;
          w->comment = wpComment;
          w->importance = wpImportance;
          //qDebug("Waypoint read: %s (%s - %s)",w->name.latin1(),w->description.latin1(),w->icao.latin1());

          wpList->append(w);
          if (conf->getHomeWp()->origP == w->origP)
          {
	    qDebug("Found homesite: %s",wpName.latin1());
	    wayPoint * wp=new wayPoint(*w); //copy
	    conf->setHomeWp(wp);
	  }
        }

        ok = true;
    }
    else {
      //KMessageBox::error(0, QObject::tr("<B>%1</B><BR>permission denied!").arg(catalog), QObject::tr("Error occurred!"));
    }
  }
  else {
    qWarning("WaypointCatalog::read(): Waypoint catalog not found.");
    Global::statusMessage( QObject::tr("Waypoint catalog not found!") );
  }

  qDebug("WaypointCatalog::read(): %d items read", wpList->count());
  return ok;
}


/** No descriptions */
bool WaypointCatalog::write()
{
  bool ok = true;
  QString wpName="";
  QString wpDescription="";
  QString wpICAO="";
  Q_INT8 wpType;
  Q_INT32 wpLatitude;
  Q_INT32 wpLongitude;
  Q_INT16 wpElevation;
  double wpFrequency;
  Q_INT8 wpLandable;
  Q_INT16 wpRunway;
  Q_INT16 wpLength;
  Q_INT8 wpSurface;
  QString wpComment="";
  Q_UINT8 wpImportance;

  wayPoint *w;
  QFile f;
  QString fName = path;
  QListIterator<wayPoint> it(*wpList);

  if (!onDisc)
    {
      GeneralConfig *conf = GeneralConfig::instance();
      fName = conf->getWaypointFile();
    }

 f.setName(fName);
  if (f.open(IO_WriteOnly)) {
    qDebug("WaypointCatalog::write(): fileName=%s", fName.latin1() );
     QDataStream out(& f);
    // write fileheader
    out << Q_UINT32(KFLOG_FILE_MAGIC);
    out << Q_INT8(FILE_TYPE_WAYPOINTS);
    out << Q_UINT16(FILE_FORMAT_ID_2); //use the new format with importance field.

    for (w = it.current(); w != 0; w = ++it) {
      wpName=w->name;
      wpDescription=w->description;
      wpICAO=w->icao;
      wpType=w->type;
      wpLatitude=w->origP.lat();
      wpLongitude=w->origP.lon();
      wpElevation=w->elevation;
      wpFrequency=w->frequency;
      wpLandable=w->isLandable;
      wpRunway=w->runway;
      wpLength=w->length;
      wpSurface=w->surface;
      wpComment=w->comment;
      wpImportance=w->importance;

      out << wpName;
      out << wpDescription;
      out << wpICAO;
      out << wpType;
      out << wpLatitude;
      out << wpLongitude;
      out << wpElevation;
      out << wpFrequency;
      out << wpLandable;
      out << wpRunway;
      out << wpLength;
      out << wpSurface;
      out << wpComment;
      out << wpImportance;
    }

    f.close();
    path = fName;
    modified = false;
    onDisc = true;
  }
  else {
    qWarning("WaypointCatalog::write(): File Open Error");
    Global::statusMessage( QObject::tr("Can't save Waypoint catalog!") );
  }

  qDebug("WaypointCatalog::write(): %d items written", wpList->count());
  return ok;
}



