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