added refresh on statusbar click
[qtmeetings] / src / BusinessLogic / Engine.cpp
1 #include "Engine.h"
2 #include "Room.h"
3 #include "Meeting.h"
4 #include "ConnectionSettings.h"
5 #include "Configuration.h"
6 #include "DisplaySettings.h"
7 #include "CommunicationManager.h"
8 // #include "DeviceManager.h"
9 #include "Clock.h"
10 #include "ErrorMapper.h"
11 #include "UIManager.h"
12
13 #include <QApplication>
14 #include <QTimer>
15 #include <QList>
16 #include <QtDebug>
17
18 QTime Engine::endOfTheDay = QTime( 23, 59, 0, 0); // end of the day is 11:59pm
19 const int IDLE_TIME_MULTIPLIER = 60000; // Multiplies milliseconds to minutes
20
21 // Macro to help deleting objects. This could be global.
22 #define QT_DELETE(X) \
23         if ( X != 0 ) \
24         { \
25                 delete X; \
26                 X = 0; \
27         }
28
29
30 Engine::Engine() :
31                 iClock( 0 ), iConfiguration( 0 ), iCommunication( 0 ),
32                 iWindowManager( 0 ), iUIManager( 0 )
33 {
34         qDebug() << "Engine::Engine()";
35         iCommunicationFailed = true;
36         
37         initConfiguration();
38         initDevice();
39         initCommunication();
40         initUserInterface();
41         
42         //initialize idle time counter
43         iIdleTimeCounter = new QTimer();
44         iIdleTimeCounter->setSingleShot( true);
45         iIdleTimeCounter->setInterval(IDLE_TIME_MULTIPLIER * iConfiguration->displaySettings()->screensaver() );
46         iIdleTimeCounter->start();
47
48         // create application clock
49         iClock = new Clock;
50         connect( iClock, SIGNAL( tick( QDateTime ) ), this, SLOT( tick( QDateTime )/*checkStatusOfAllRooms()*/ ) );
51         // connect( iClock, SIGNAL( tick( QDateTime ) ), iWindowManager, SLOT( distributeDateTimeInfo( QDateTime ) ) );
52
53         // Create auto refresh timer
54         iAutoRefresh = new QTimer;
55
56         iAutoRefresh->setInterval(Configuration::instance()->getRefreshinterval() * 1000);
57
58         iAutoRefresh->start();
59         connect( iAutoRefresh, SIGNAL( timeout() ), iAutoRefresh, SLOT( start() ) );
60         connect( iAutoRefresh, SIGNAL( timeout() ), this, SLOT( updateRoomInfo() ) );
61
62         connect(iWindowManager, SIGNAL(closeClicked()), this, SLOT(closeApplication()));
63
64         // connect( iAutoRefresh, SIGNAL( timeout() ), this, SLOT( fetchMeetings() ) );
65         
66         if( iDevice->currentOperationMode() == DeviceManager::KioskMode )
67         {
68                 iWindowManager->setFullscreen();
69         }
70
71         connectSignals();
72         connect( Configuration::instance(), SIGNAL( configurationChanged() ), this, SLOT( configurationChanged() ) );
73         // QTimer::singleShot( 0, this, SLOT( fetchMeetings() ) );
74
75         // TODO: continue implementation
76 }
77
78 Engine::~Engine()
79 {
80         qDebug() << "Engine::~Engine()";
81         while ( !iMeetings.isEmpty() )
82                 delete iMeetings.takeFirst();
83         
84         if ( iIdleTimeCounter != 0 )
85         {
86                 iIdleTimeCounter->stop();
87                 delete iIdleTimeCounter;
88                 iIdleTimeCounter = 0;
89         }
90         QT_DELETE( iClock );
91         QT_DELETE( iDevice );
92
93         QT_DELETE( iUIManager );
94         QT_DELETE( iWindowManager );
95 }
96
97 void Engine::closeApplication()
98 {
99         qDebug() << "Engine::closeApplication()";
100         // closes application after 1 second
101         QTimer::singleShot( 1000, QApplication::instance(), SLOT( quit() ));
102 }
103
104 Room* Engine::defaultRoom()
105 {
106         qDebug() << "Engine::defaultRoom()";
107         return iConfiguration->defaultRoom();
108 }
109
110 void Engine::checkStatusOfAllRooms()
111 {
112         // TODO: Check if date has changed
113         // iterate trough on the rooms
114         for (int i = 0; i < iConfiguration->rooms().count(); i++)
115         {
116                 // and check the status
117                 roomStatusInfoNeeded( iConfiguration->rooms().at(i) );
118         }
119 }
120
121 int Engine::indexOfMeetingAt(Room *aRoom, QDateTime aAt)
122 {
123 //      qDebug() << "Engine::indexOfMeetingAt( Room *, QDateTime )";
124         for ( int i = 0; i < iMeetings.count(); i++ )
125         {
126                 // exchange server ensures that there is only one meeting in a room at a specified time
127                 if (aRoom->equals(iMeetings.at( i )->room() ) && iMeetings.at( i )->startsAt() <= aAt && iMeetings.at( i )->endsAt() >= aAt)
128                 {
129                         return i;
130                 }
131         }
132         return -1;
133 }
134
135 int Engine::indexOfMeetingAfter(Room *aRoom, QDateTime aAfter)
136 {
137 //      qDebug() << "Engine::indexOfMeetingAfter( Room *, QDateTime )";
138         // seeks for the next meeting on the SAME DAY
139         int min = -1;
140         for (int i = 0; i < iMeetings.count(); i++)
141         {
142                 // if the meeting is in the same room, on the same day but after the specified time
143                 if (aRoom->equals(iMeetings.at( i )->room() ) && iMeetings.at( i )->startsAt().date() == aAfter.date() && iMeetings.at( i )->startsAt() > aAfter)
144                 {
145                         // if there was not any meeting find yet or the previously found is a later one then the (i)th
146                         if (min == -1 || iMeetings.at( min )->startsAt() > iMeetings.at( i )->startsAt() )
147                         {
148                                 min = i;
149                         }
150                 }
151         }
152         return min;
153 }
154
155 void Engine::roomStatusInfoNeeded(Room *aRoom)
156 {
157 //      qDebug() << "Engine::roomStatusInfoNeeded( Room * )";
158         if ( aRoom == 0 )
159         {
160                 return;
161         }
162
163         int indexOfCurrentMeeting = indexOfMeetingAt(aRoom, iClock->datetime() );
164         int indexOfNextMeeting = indexOfMeetingAfter(aRoom, iClock->datetime() );
165
166         // if there is no meeting, then status is Free; otherwise Busy
167         Room::Status status = (indexOfCurrentMeeting == -1 ) ? Room::FreeStatus : Room::BusyStatus;
168         // if room is Busy, then check end time, otherwise...
169         QTime until = (status == Room::BusyStatus ) ? iMeetings.at( indexOfCurrentMeeting )->endsAt().time() :
170         // ...if there is meeting following on the same day then check end time, otherwise end is the of the working day
171         ( ( indexOfNextMeeting != -1 ) ? iMeetings.at( indexOfNextMeeting )->startsAt().time() : Engine::endOfTheDay );
172
173         //currently works only for default room
174         if ( aRoom->equals( *(iCurrentRoom) ) )
175         {
176                 emit roomStatusChanged( status, until );
177         }
178 }
179
180 void Engine::fetchMeetingDetails( Meeting *aMeeting )
181 {
182         qDebug() << "Engine::fetchMeetingDetails( Meeting* )";
183         iCommunication->fetchMeetingDetails( *aMeeting );
184 }
185
186 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
187 {
188         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
189         QTime c = QTime::currentTime();
190         iLastCommunication.setHMS( c.hour(), c.minute(), c.second() );
191
192         qDebug() << "Error length: "<< iCommunicationError.length();
193         qDebug() << "Error: "<< iCommunicationError;
194
195         if( iCommunicationError.length() == 0 )
196         {
197                 iCommunicationFailed = false;
198                 iUIManager->connectionEstablished();
199         }
200
201         for ( int i = 0; i < iMeetings.count(); ++i ) 
202         {
203                 // TODO: Check if these are current week's meetings and do not overwrite those
204                 Meeting* m = iMeetings.takeAt( i );
205                 delete m;
206         }
207         iMeetings.clear();
208         for ( int i = 0; i < aMeetings.count(); ++i ) {
209                 Meeting* m = new Meeting( *( aMeetings.at( i ) ) );
210                 iMeetings.append( m );
211         }
212
213         // refresh room status info
214         roomStatusInfoNeeded( iCurrentRoom /*defaultRoom()*/ );
215 }
216
217 void Engine::errorHandler( int aCode, const QString &aAddInfo )
218 {       
219         iCommunicationFailed = true;
220
221         if( aCode >= 100 && aCode < 150 )
222         {
223                 if ( iUIManager != 0 )
224                         {
225                                 iUIManager->connectionLost();
226                         }
227         }
228         if ( iWindowManager != 0 )
229         {
230                 iCommunicationError = ErrorMapper::codeToString( aCode, aAddInfo );
231                 //iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
232         }
233 }
234
235 bool Engine::connected()
236 {
237         return !iCommunicationFailed;
238 }
239
240 QTime Engine::lastUpdated()
241 {
242         return iLastCommunication;
243 }
244
245 QString Engine::errorMessage()
246 {
247         return iCommunicationError;
248 }
249
250 void Engine::fetchMeetings( const int aWeek, const int aYear, const Room *aIn )
251 {
252         qDebug()
253                         << "Engine::fetchMeetings( const int aWeek, const int aYear, const Room * )";
254         iCommunicationError = "";
255         iCommunication->fetchMeetings(aWeek, aYear, *aIn);
256 }
257
258 void Engine::cancelFetchMeetingDetails()
259 {
260         iCommunication->cancelFetchMeetingDetails();
261 }
262
263 void Engine::shownWeekChanged( QDate aFrom )
264 {
265         qDebug() << "[Engine::shownWeekChanged] <Invoked>";
266         iCommunicationError = "";
267         iCommunication->fetchMeetings( aFrom.weekNumber(), aFrom.year(), *iCurrentRoom/*defaultRoom()*/ );
268 }
269
270 void Engine::changeDeviceMode()
271 {
272         connect( iDevice, SIGNAL( changeModeFailed() ), this, SLOT( changeModeFailed() ) );
273         iAutoRefresh->stop(); // Stop the meeting update
274         iDevice->changeMode();
275 }
276
277 void Engine::changeModeFailed()
278 {
279         qDebug() << "Engine::progressBarCancelled()";
280         iAutoRefresh->start(); //we start the metting updating
281 }
282
283 void Engine::initUserInterface()
284 {
285         qDebug() << "[Engine::initUserInterface] <Invoked>";
286         
287         // Initialize the window manager and connect what ever signals can be connected
288         iWindowManager = new WindowManager;
289         // Create the UIManager which internally handles most of the UI actions
290         iUIManager = new UIManager( this, iWindowManager );
291         
292         connect( iWindowManager, SIGNAL( eventDetected() ), this, SLOT( handleViewEvent() ) );
293         connect( iWindowManager, SIGNAL( previousViewRestored() ), iUIManager, SLOT( previousViewRestored() ) );
294         connect( iWindowManager, SIGNAL( dialogActivated() ), this, SLOT( dialogActivated() ) );
295         connect( iWindowManager, SIGNAL( dialogDeactivated() ), this, SLOT( dialogDeactivated() ) );
296         
297         // Show the UI
298         iWindowManager->setWindowState( Qt::WindowMaximized );
299         iWindowManager->show();
300         iUIManager->showMainView();
301         
302         // This triggers the meeting fetching
303         iUIManager->currentRoomChanged( this->iCurrentRoom );
304         
305         qDebug() << "[Engine::initUserInterface] <Finished>";
306 }
307
308 void Engine::handleViewEvent()
309 {
310         if ( iIdleTimeCounter != 0 && iIdleTimeCounter->isActive())
311         {
312                 // Restart the idle time counter when view event is received
313                 iIdleTimeCounter->stop();
314                 iIdleTimeCounter->start();
315         }
316 }
317
318 void Engine::initConfiguration()
319 {
320         iConfiguration = Configuration::instance();
321         if ( iConfiguration == 0 )
322         {
323                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
324         }
325         iCurrentRoom = iConfiguration->defaultRoom();
326 }
327
328 void Engine::connectSignals()
329 {
330         // Connect engine objects signals to UIManager
331         connect( iClock, SIGNAL( tick( QDateTime ) ), iUIManager, SLOT( updateTime( QDateTime ) ) );
332         connect( iIdleTimeCounter, SIGNAL( timeout() ) , iUIManager, SLOT( roomStatusIndicatorRequested() ) );
333         
334         iUIManager->connectDeviceManager( iDevice );
335         iUIManager->connectCommunicationManager( iCommunication );
336 }
337
338 void Engine::initCommunication()
339 {
340         // initialize communication
341         iCommunication = new CommunicationManager(/* *(iConfiguration->connectionSettings()) */);
342         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
343                         this, SLOT( errorHandler( int ) ) );
344         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
345                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
346 }
347
348 void Engine::initDevice()
349 {
350         // create device manager
351         iDevice = new DeviceManager( iConfiguration->startupSettings() );
352         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
353         iDevice->initDeviceManager();
354 }
355
356 void Engine::dialogActivated()
357 {
358         if ( iIdleTimeCounter != 0 )
359         {
360                 iIdleTimeCounter->stop();
361         }
362 }
363
364 void Engine::dialogDeactivated()
365 {
366         if ( iIdleTimeCounter != 0 )
367         {
368                 iIdleTimeCounter->start();
369         }
370 }
371
372 void Engine::previousViewRestored()
373 {
374         if ( iIdleTimeCounter != 0 )
375         {
376                 iIdleTimeCounter->start();
377         }
378 }
379
380 void Engine::stopIdleTimeCounter()
381 {
382         if ( iIdleTimeCounter != 0 )
383         {
384                 iIdleTimeCounter->stop();
385         }
386 }
387
388 void Engine::startIdleTimeCounter()
389 {
390         if ( iIdleTimeCounter != 0 )
391         {
392                 iIdleTimeCounter->start();
393         }
394 }
395
396 void Engine::currentRoomChanged(Room *aRoom)
397 {
398         qDebug() << "[Engine::currentRoomChanged] <invoked>";
399         iCurrentRoom = aRoom;
400         roomStatusInfoNeeded( iCurrentRoom );
401 }
402
403 void Engine::tick( QDateTime aCurrentDateTime )
404 {
405         // Called once every second
406         checkStatusOfAllRooms();
407         if( aCurrentDateTime.date() !=  iCurrentDate)
408         {
409                 // Check if week has changed and fetch meetings for this week
410                 if( aCurrentDateTime.date().weekNumber() != iCurrentDate.weekNumber()
411                         || aCurrentDateTime.date().year() != iCurrentDate.year() )
412                 {
413                         qDebug() << "[Engine::tick] detected week change, fetching meetings";
414                         fetchMeetings( aCurrentDateTime.date().weekNumber(), aCurrentDateTime.date().year(), iCurrentRoom );
415                 }
416         }
417         iCurrentDate = aCurrentDateTime.date();
418 }
419
420
421 void Engine::updateRoomInfo()
422 {
423         qDebug() << "ENGINE::: updateMeetings";
424         iUIManager->currentRoomChanged( iCurrentRoom );
425 }
426
427 void Engine::configurationChanged()
428 {
429         iAutoRefresh->setInterval(Configuration::instance()->getRefreshinterval() * 1000);
430 }