Merged
[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 "WeeklyViewWidget.h"
12 #include "SettingsView.h"
13 #include "RoomStatusIndicatorWidget.h"
14 #include "PasswordDialog.h"
15 #include "MeetingInfoDialog.h"
16
17 #include <QApplication>
18 #include <QTimer>
19 #include <QList>
20 #include <QtDebug>
21
22 QTime Engine::endOfTheDay = QTime( 23, 59, 0, 0 ); // end of the day is 11:59pm
23 const int IDLE_TIME_MULTIPLIER = 60000; // Multiplies milliseconds to minutes
24
25 // Macro to help deleting objects. This could be global.
26 #define QT_DELETE(X) \
27         if ( X != 0 ) \
28         { \
29                 delete X; \
30                 X = 0; \
31         }
32
33
34 Engine::Engine() :
35                 iClock( 0 ), iConfiguration( 0 ), iCommunication( 0 )
36 {
37         qDebug() << "Engine::Engine()";
38         
39         initConfiguration();
40         initDevice();
41         initCommunication();
42         initUserInterface();
43         
44         //initialize idle time counter
45         iIdleTimeCounter = new QTimer();
46         iIdleTimeCounter->setSingleShot( true );
47         // iIdleTimeCounter->setInterval( IDLE_TIME_MULTIPLIER * iConfiguration->displaySettings()->screensaver() );
48         iIdleTimeCounter->setInterval( 10000 );
49         iIdleTimeCounter->start();
50         // connect( iIdleTimeCounter, SIGNAL( timeout() ), iWindowManager, SLOT( showRoomStatus() ) );
51         connect( iIdleTimeCounter, SIGNAL( timeout() ), this, SLOT( idleTimerTimeout() ) );
52
53         // create application clock
54         iClock = new Clock;
55         connect( iClock, SIGNAL( tick( QDateTime ) ), this, SLOT( checkStatusOfAllRooms() ) );
56         // connect( iClock, SIGNAL( tick( QDateTime ) ), iWindowManager, SLOT( distributeDateTimeInfo( QDateTime ) ) );
57
58         iAutoRefresh = new QTimer;
59         iAutoRefresh->setInterval( iConfiguration->connectionSettings()->refreshInterval() * 1000 );
60         iAutoRefresh->start();
61         connect( iAutoRefresh, SIGNAL( timeout() ), iAutoRefresh, SLOT( start() ) );
62 //      connect( iAutoRefresh, SIGNAL( timeout() ), this, SLOT( fetchMeetings() ) );
63         
64         if( iDevice->currentOperationMode() == DeviceManager::KioskMode )
65         {
66                 iWindowManager->setFullscreen();
67         }
68
69         connectSignals();
70         
71         QTimer::singleShot( 0, this, SLOT( fetchMeetings() ) );
72
73         // TODO: continue implementation
74 }
75
76 Engine::~Engine()
77 {
78         qDebug() << "Engine::~Engine()";
79         while ( !iMeetings.isEmpty() )
80                 delete iMeetings.takeFirst();
81         
82         if ( iIdleTimeCounter != 0 )
83         {
84                 iIdleTimeCounter->stop();
85                 delete iIdleTimeCounter;
86                 iIdleTimeCounter = 0;
87         }
88         QT_DELETE( iClock );
89         QT_DELETE( iDevice );
90         
91         QT_DELETE( iRoomStatusIndicator );
92         QT_DELETE( iSettingsView );
93         QT_DELETE( iWeeklyView );
94         QT_DELETE( iPasswordDialog );
95         QT_DELETE( iWindowManager );
96 }
97
98 void Engine::closeApplication()
99 {
100         qDebug() << "Engine::closeApplication()";
101         // closes application after 1 second
102         QTimer::singleShot( 1000, QApplication::instance(), SLOT( quit() ) );
103 }
104
105 Room* Engine::defaultRoom()
106 {
107         qDebug() << "Engine::defaultRoom()";
108         return iConfiguration->defaultRoom();
109 }
110
111 void Engine::checkStatusOfAllRooms()
112 {
113 //      qDebug() << "Engine::checkStatusOfAllRooms()";
114         // iterate trough on the rooms
115         for ( int i = 0; i < iConfiguration->rooms().count(); i++ )
116         {
117                 // and check the status
118                 roomStatusInfoNeeded( iConfiguration->rooms().at( i ) );
119         }
120 }
121
122 int Engine::indexOfMeetingAt( Room *aRoom, QDateTime aAt )
123 {
124 //      qDebug() << "Engine::indexOfMeetingAt( Room *, QDateTime )";
125         for ( int i = 0; i < iMeetings.count(); i++ )
126         {
127                 // exchange server ensures that there is only one meeting in a room at a specified time
128                 if ( aRoom->equals( iMeetings.at( i )->room() )
129                           && iMeetings.at( i )->startsAt() <= aAt
130                           && iMeetings.at( i )->endsAt() >= aAt )
131                 {
132                         return i;
133                 }
134         }
135         return -1;
136 }
137
138 int Engine::indexOfMeetingAfter( Room *aRoom, QDateTime aAfter )
139 {
140 //      qDebug() << "Engine::indexOfMeetingAfter( Room *, QDateTime )";
141         // seeks for the next meeting on the SAME DAY
142         int min = -1;
143         for ( int i = 0; i < iMeetings.count(); i++ )
144         {
145                 // if the meeting is in the same room, on the same day but after the specified time
146                 if ( aRoom->equals( iMeetings.at( i )->room() )
147                           && iMeetings.at( i )->startsAt().date() == aAfter.date()
148                           && iMeetings.at( i )->startsAt() > aAfter )
149                 {
150                         // if there was not any meeting find yet or the previously found is a later one then the (i)th
151                         if ( min == -1
152                                   || iMeetings.at( min )->startsAt() > iMeetings.at( i )->startsAt() )
153                         {
154                                 min = i;
155                         }
156                 }
157         }
158         return min;
159 }
160
161 void Engine::roomStatusInfoNeeded( Room *aRoom )
162 {
163 //      qDebug() << "Engine::roomStatusInfoNeeded( Room * )";
164         if ( aRoom == 0 )
165         {
166                 return;
167         }
168
169         int indexOfCurrentMeeting = indexOfMeetingAt( aRoom, iClock->datetime() );
170         int indexOfNextMeeting = indexOfMeetingAfter( aRoom, iClock->datetime() );
171
172         // if there is no meeting, then status is Free; otherwise Busy
173         Room::Status status = ( indexOfCurrentMeeting == -1 ) ? Room::FreeStatus : Room::BusyStatus;
174         // if room is Busy, then check end time, otherwise...
175         QTime until = ( status == Room::BusyStatus ) ? iMeetings.at( indexOfCurrentMeeting )->endsAt().time() :
176                           // ...if there is meeting following on the same day then check end time, otherwise end is the of the working day
177                           (( indexOfNextMeeting != -1 ) ? iMeetings.at( indexOfNextMeeting )->startsAt().time() : Engine::endOfTheDay );
178
179         //currently works only for deafult room
180 //      if( aRoom->equals( *(defaultRoom() ) ) )
181 //              iWindowManager->roomStatusChanged( aRoom, status, until );
182 }
183
184 void Engine::fetchMeetings()
185 {
186         Room *room = defaultRoom();
187         qDebug() << "Engine::fetchMeetings for " << room->name();
188         fetchMeetings( iClock->datetime(), iClock->datetime().addDays( 7 ), room );
189 }
190
191 void Engine::fetchMeetingDetails( Meeting *aMeeting )
192 {
193         qDebug() << "Engine::fetchMeetingDetails( Meeting* )";
194         iWindowManager->showProgressBar( tr("Please Wait"), true );
195         iWindowManager->updateProgressBar( tr("Fetching Meeting Details...") );
196         connect( iWindowManager,
197                          SIGNAL( progressBarCancelled() ),
198                          this,
199                          SLOT( fetchMeetingDetailsCancelled() )
200                         );
201         iCommunication->fetchMeetingDetails( *aMeeting );
202 }
203
204 bool Engine::isMeetingInList( const QList<Meeting*> &aList, const Meeting *aMeeting )
205 {
206         qDebug() << "Engine::isMeetingInList( const QList<Meeting*> &, const Meeting * )";
207         for ( int i = 0; i < aList.count(); i++ )
208         {
209                 if ( aMeeting->equals( *(aList.at( i )) ) )
210                 {
211                         return true;
212                 }
213         }
214         return false;
215 }
216
217 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
218 {
219         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
220         // check if there is any new meeting in the list came from the server -> added
221         for ( int i = 0; i < aMeetings.count(); i++ )
222         {
223                 // if the (i)th meeting is not in the local meeting list
224                 if ( !isMeetingInList( iMeetings, aMeetings.at( i ) ) )
225                 {
226                         // add to the local database =)
227                         Meeting* m = new Meeting( *(aMeetings.at( i )) );
228                         iMeetings.append( m );
229                         // and signal the changes
230                         iWeeklyView->insertMeeting( m );
231                 }
232         }
233
234         // check if there is any meeting NOT in the list came from the server -> deleted
235         for ( int i = 0; i < iMeetings.count(); i++ )
236         {
237                 // if the (i)th meeting is in the local but NOT in the server's meeting list
238                 if ( !isMeetingInList( aMeetings, iMeetings.at( i ) ) )
239                 {
240                         Meeting* m = iMeetings.takeAt( i );
241                         // signal the changes
242                         iWeeklyView->deleteMeeting( m );
243                         // delete the meeting from the local list
244                         delete m;
245                 }
246         }
247
248         // refresh room status info
249         roomStatusInfoNeeded( defaultRoom() );
250 }
251
252 void Engine::meetingDetailsFetched( Meeting &aDetailedMeeting )
253 {
254         qDebug() << "Engine::meetingDetailsFetched( Meeting & )";
255         
256         if ( iMeetingInfoDialog != 0 )
257         {
258                 iMeetingInfoDialog->setMeeting( &aDetailedMeeting );
259                 iWindowManager->showDialog( iMeetingInfoDialog );
260         }
261
262 }
263
264 void Engine::errorHandler( int aCode, const QString &aAddInfo )
265 {
266         qDebug() << "Engine::ErrorHandler, aCode: " << aCode;
267         // inform UI about the problem
268         if( aCode >= 100 && aCode <= 150 )
269                 qDebug() << "CommunicationManager signaled an error:" << aCode;
270         // iWindowManager->closeProgressBar();
271         // iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
272 }
273
274 void Engine::currentRoomChanged( Room *aCurrentRoom )
275 {
276         qDebug() << "Engine::currentRoomChanged to " << aCurrentRoom->name();
277 //      QDateTime from( iWindowManager->weeklyView()->beginnigOfShownWeek() );
278 //      QDateTime to( from.addDays( 8 ) );
279 //      fetchMeetings( from, to, aCurrentRoom );
280 }
281
282 void Engine::fetchMeetings( const QDateTime &aFrom, const QDateTime &aUntil, const Room *aIn )
283 {
284         qDebug() << "Engine::fetchMeetings( const QDateTime &, const QDateTime &, const Room * )";
285         iCommunication->fetchMeetings( aFrom, aUntil, *aIn );
286 }
287
288 void Engine::shownWeekChanged( QDate aFrom )
289 {
290         qDebug() << "Engine::shownWeekChanged( QDate )";
291         QDateTime from( aFrom );
292         QDateTime to( aFrom.addDays( 7 ), QTime( 23, 59 ) );
293         qDebug() << "Engine::shownWeekChanged " << aFrom.toString( "d.m. h:mm" ) << " to " << to.toString( "d.m. h:mm" );
294 //      fetchMeetings( from, to, iWindowManager->weeklyView()->currentRoom() );
295 }
296
297 void Engine::changeModeOrdered( DeviceManager::OperationMode aMode )
298 {       
299         qDebug() << "Engine::changeModeOrdered( DeviceManager::OperationMode )";
300         QString message = tr( "You are about to change operation mode to %1." )
301                                 .arg( iDevice->operationModeToString( aMode ) );
302
303         // iPasswordDialog->update( message );
304         iWindowManager->showDialog( static_cast<QDialog *>( iPasswordDialog ) );
305 }
306
307 void Engine::passwordEntered( PasswordDialog::PasswordStatus aPasswordStatus )
308 {
309         qDebug() << "Engine::passwordEntered( PasswordDialog::PasswordStatus )";
310 //      iWindowManager->closePasswordDialog();
311         
312         switch ( aPasswordStatus )
313         {
314                 case PasswordDialog::Correct :
315                 {
316 //                      iWindowManager->showProgressBar( "Changing current operation mode." );
317 //                      connect( iWindowManager, SIGNAL( progressBarCancelled() ), this, SLOT( progressBarCancelled() ) );
318 //                      connect( iDevice, SIGNAL( changingMode( const QString & ) ),
319 //                                      iWindowManager, SLOT( updateProgressBar( const QString & ) ) );
320                         // TODO : Connect the signal directory to progress bar dialog which should be instance in engine
321 //                      connect( iDevice, SIGNAL( changingMode( const QString & ) ),
322 //                                      iWindowManager, SLOT( updateProgressBar( const QString & ) ) );
323                         connect( iDevice, SIGNAL( changingModeFailed() ), this, SLOT( progressBarCancelled() ) );
324                         iDevice->changeMode( true );
325                         break;
326                 }
327                 case PasswordDialog::Incorrect :
328                 {
329 //                      iWindowManager->error( tr( "Incorrect password." ) );
330                         iDevice->changeMode( false );
331                         break;
332                 }
333                 default : //case PasswordDialog::Canceled
334                 {
335                         iDevice->changeMode( false );
336                 }
337         }
338 }
339
340 void Engine::progressBarCancelled()
341 {
342         qDebug() << "Engine::progressBarCancelled()";
343         //TODO: cancel the on-going event
344 //      iWindowManager->closeProgressBar();
345         iDevice->changeMode( false );
346 }
347
348 void Engine::initUserInterface()
349 {
350         qDebug() << "[Engine::initUserInterface] <Invoked>";
351         // Initialize the window manager and connect what ever signals can be connected
352         iWindowManager = new WindowManager;
353         connect( iWindowManager, SIGNAL( eventDetected() ), this, SLOT( handleViewEvent() ) );
354         connect( iWindowManager, SIGNAL( previousViewRestored() ), this, SLOT( previousViewRestored() ) );
355         connect( iWindowManager, SIGNAL( dialogActivated() ), this, SLOT( dialogActivated() ) );
356         connect( iWindowManager, SIGNAL( dialogDeactivated() ), this, SLOT( dialogDeactivated() ) );
357         
358         // Initialize the weekly view and connect what ever signals can be connected at this stage
359         iWeeklyView = new WeeklyViewWidget(QDateTime::currentDateTime(), iConfiguration);
360         connect( iWeeklyView, SIGNAL( settingsButtonClicked() ), this, SLOT( settingsViewRequested() ) );
361         connect( iWeeklyView, SIGNAL( currentRoomChange( Room * ) ) , this, SLOT( currentRoomChange( Room * ) ) );
362         connect( iWeeklyView, SIGNAL( meetingActivated( Meeting * ) ), this, SLOT( fetchMeetingDetails( Meeting * ) ) ) ;
363         connect( iWeeklyView, SIGNAL( shownWeekChanged( QDate ) ) , this, SLOT( shownWeekChanged( QDate ) ) );
364         
365         // Initialize the settings view
366         iSettingsView = new SettingsView;
367         connect( iSettingsView, SIGNAL( okClicked() ) , this, SLOT( settingsOkClicked() ) );
368         
369         // Initialize the room status indicator
370         iRoomStatusIndicator = new RoomStatusIndicatorWidget( defaultRoom(), Room::FreeStatus, QTime::currentTime(), iConfiguration->displaySettings()->dateFormat() );
371         
372         // Create password dialog
373         iPasswordDialog = new PasswordDialog( iConfiguration->adminPassword(), tr("No Text Set"), tr("Title") );
374         connect( iPasswordDialog, SIGNAL( passwordEntered( PasswordDialog::PasswordStatus ) ), this, SLOT( passwordEntered( PasswordDialog::PasswordStatus ) ) );
375         
376         // Show the UI
377         iWindowManager->setWindowState( Qt::WindowMaximized );
378         iWindowManager->show();
379         iWindowManager->showView( iWeeklyView );
380         
381         qDebug() << "[Engine::initUserInterface] <Finished>";
382 }
383
384 void Engine::settingsViewRequested()
385 {
386         if ( iSettingsView != 0 )
387         {
388                 iWindowManager->showView( static_cast<ViewBase *>( iSettingsView ) );
389                 // Room status indicator will not be shown when settings view is active
390                 iIdleTimeCounter->stop();
391         }
392 }
393
394 void Engine::handleViewEvent()
395 {
396         qDebug() << "[Engine::handleViewEvent] <Invoked>";
397         if ( iIdleTimeCounter != 0 )
398         {
399                 // Restart the idle time counter when view event is received
400                 iIdleTimeCounter->stop();
401                 iIdleTimeCounter->start();
402         }
403 }
404
405 void Engine::initConfiguration()
406 {
407         iConfiguration = Configuration::instance();
408         if ( iConfiguration == 0 )
409         {
410                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
411         }
412 }
413
414 void Engine::idleTimerTimeout()
415 {
416         if ( iRoomStatusIndicator != 0 )
417         {
418                 iWindowManager->showView( static_cast<ViewBase *>( iRoomStatusIndicator ) );
419         }
420 }
421
422 void Engine::settingsOkClicked()
423 {
424         if ( iWeeklyView != 0 )
425         {
426                 iWindowManager->showView( iWeeklyView );
427                 // Start the idle time counter when we return to the main view
428                 iIdleTimeCounter->start();
429         }
430 }
431
432 void Engine::connectSignals()
433 {
434         // Handle weekly view signal connections
435         connect( iClock, SIGNAL( tick( QDateTime ) ), iWeeklyView, SLOT( setCurrentDateTime( QDateTime ) ) );
436 }
437
438 void Engine::initCommunication()
439 {
440         // initialize communication
441         iCommunication = new CommunicationManager( *(iConfiguration->connectionSettings()) );
442         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
443                         this, SLOT( errorHandler( int ) ) );
444         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
445                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
446         connect( iCommunication, SIGNAL( meetingDetailsFetched( Meeting& ) ),
447                         this, SLOT( meetingDetailsFetched( Meeting& ) ) );
448 }
449
450 void Engine::initDevice()
451 {
452         // create device manager
453         iDevice = new DeviceManager( iConfiguration->startupSettings() );
454         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
455         connect( iDevice, SIGNAL( changeModeOrdered( DeviceManager::OperationMode ) ), 
456                         this, SLOT( changeModeOrdered( DeviceManager::OperationMode ) ) );
457         iDevice->initDeviceManager();
458 }
459
460 void Engine::dialogActivated()
461 {
462         if ( iIdleTimeCounter != 0 )
463         {
464                 iIdleTimeCounter->stop();
465         }
466 }
467
468 void Engine::dialogDeactivated()
469 {
470         if ( iIdleTimeCounter != 0 )
471         {
472                 iIdleTimeCounter->start();
473         }
474 }
475
476 void Engine::previousViewRestored()
477 {
478         if ( iIdleTimeCounter != 0 )
479         {
480                 iIdleTimeCounter->start();
481         }
482 }
483
484 void Engine::fetchMeetingDetailsCancelled()
485 {
486         iCommunication->cancelFetchMeetingDetails();
487         iWindowManager->closeProgressBar();
488 }