committing work in progress
[ptas] / zouba / src / locations.cpp
1 #include "locations.h"
2
3 #include <QDebug>
4 #include <QHash>
5 #include <QSettings>
6 #include <QString>
7 #include <QStringList>
8 #include <QCoreApplication>
9
10 QHash<QString,Location *> Locations::locationHash;
11 bool Locations::initialised = false;
12
13 Locations::Locations()
14 {
15     if ( !initialised ) {
16         restoreLocations();
17         initialised = true;
18     }
19 }
20
21 Locations::~Locations()
22 {
23 }
24
25 bool Locations::addLocation( Location *location )
26 {
27   bool succeeded=false;
28
29   // if it's valid now, save the setting
30   if ( location->isValid() ) {
31     saveLocation( location );
32   }
33
34   if ( !locationHash.contains( location->label() ) ) {
35     qDebug() << "Adding location" << location->label();
36     locationHash[ location->label() ] = location;
37     succeeded = true;
38   } else {
39     qDebug() << "FAILED to add location" << location->label();
40   }
41
42   return succeeded;
43 }
44
45 void Locations::restoreLocations()
46 {
47   QSettings settings;
48
49   settings.beginGroup( "Locations" );
50   QStringList labels = settings.childGroups();
51
52   for( int i=0; i<labels.size(); ++i ) {
53     QString label = labels[i];
54     settings.beginGroup( label );
55     QString x       = settings.value( "x" ).toString();
56     QString y       = settings.value( "y" ).toString();
57     QString address = settings.value( "address" ).toString();
58     settings.endGroup();
59
60     qDebug() << "restoring" << label;
61     Location *location = new Location( x, y, label );
62     location->setAddress( address );
63
64     locationHash[ label ] = location;
65   }
66
67   settings.endGroup();
68 }
69
70 void Locations::saveLocation( Location *location )
71 {
72   qDebug() << "Saving location" << location->label();
73   QSettings settings;
74   settings.beginGroup( "Locations" );
75   settings.beginGroup( location->label() );
76   settings.setValue( "address", location->address() );
77   settings.setValue( "x", location->x() );
78   settings.setValue( "y", location->y() );
79   settings.endGroup();
80   settings.endGroup();
81 }
82
83 void Locations::saveLocation()
84 {
85   Location *location = qobject_cast<Location*>(sender());
86
87   saveLocation( location );
88 }
89
90 Location *Locations::location( const QString &label )
91 {
92   qDebug() << "requesting location" << label;
93   Location *retVal = 0;
94
95   if ( locationHash.contains( label ) ) {
96     qDebug() << "found location" << label;
97     retVal = locationHash[ label ];
98   } else {
99     qDebug() << "didn't find location" << label;
100   }
101
102   return retVal;
103 }