ViewBase added and major changes to use the new architecture
[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         iCommunication->fetchMeetingDetails( *aMeeting );
195 }
196
197 bool Engine::isMeetingInList( const QList<Meeting*> &aList, const Meeting *aMeeting )
198 {
199         qDebug() << "Engine::isMeetingInList( const QList<Meeting*> &, const Meeting * )";
200         for ( int i = 0; i < aList.count(); i++ )
201         {
202                 if ( aMeeting->equals( *(aList.at( i )) ) )
203                 {
204                         return true;
205                 }
206         }
207         return false;
208 }
209
210 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
211 {
212         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
213         // check if there is any new meeting in the list came from the server -> added
214         for ( int i = 0; i < aMeetings.count(); i++ )
215         {
216                 // if the (i)th meeting is not in the local meeting list
217                 if ( !isMeetingInList( iMeetings, aMeetings.at( i ) ) )
218                 {
219                         // add to the local database =)
220                         Meeting* m = new Meeting( *(aMeetings.at( i )) );
221                         iMeetings.append( m );
222                         // and signal the changes
223                         iWeeklyView->insertMeeting( m );
224                 }
225         }
226
227         // check if there is any meeting NOT in the list came from the server -> deleted
228         for ( int i = 0; i < iMeetings.count(); i++ )
229         {
230                 // if the (i)th meeting is in the local but NOT in the server's meeting list
231                 if ( !isMeetingInList( aMeetings, iMeetings.at( i ) ) )
232                 {
233                         Meeting* m = iMeetings.takeAt( i );
234                         // signal the changes
235                         iWeeklyView->deleteMeeting( m );
236                         // delete the meeting from the local list
237                         delete m;
238                 }
239         }
240
241         // refresh room status info
242         roomStatusInfoNeeded( defaultRoom() );
243 }
244
245 void Engine::meetingDetailsFetched( Meeting &aDetailedMeeting )
246 {
247         qDebug() << "Engine::meetingDetailsFetched( Meeting & )";
248         
249         if ( iMeetingInfoDialog != 0 )
250         {
251                 iMeetingInfoDialog->setMeeting( &aDetailedMeeting );
252                 iWindowManager->showDialog( iMeetingInfoDialog );
253         }
254
255 }
256
257 void Engine::errorHandler( int aCode, const QString &aAddInfo )
258 {
259         qDebug() << "Engine::ErrorHandler, aCode: " << aCode;
260         // inform UI about the problem
261         if( aCode >= 100 && aCode <= 110 )
262                 qDebug() << "CommunicationManager signaled an error:" << aCode;
263 //      iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
264 }
265
266 void Engine::currentRoomChanged( Room *aCurrentRoom )
267 {
268         qDebug() << "Engine::currentRoomChanged to " << aCurrentRoom->name();
269 //      QDateTime from( iWindowManager->weeklyView()->beginnigOfShownWeek() );
270 //      QDateTime to( from.addDays( 8 ) );
271 //      fetchMeetings( from, to, aCurrentRoom );
272 }
273
274 void Engine::fetchMeetings( const QDateTime &aFrom, const QDateTime &aUntil, const Room *aIn )
275 {
276         qDebug() << "Engine::fetchMeetings( const QDateTime &, const QDateTime &, const Room * )";
277         iCommunication->fetchMeetings( aFrom, aUntil, *aIn );
278 }
279
280 void Engine::shownWeekChanged( QDate aFrom )
281 {
282         qDebug() << "Engine::shownWeekChanged( QDate )";
283         QDateTime from( aFrom );
284         QDateTime to( aFrom.addDays( 7 ), QTime( 23, 59 ) );
285         qDebug() << "Engine::shownWeekChanged " << aFrom.toString( "d.m. h:mm" ) << " to " << to.toString( "d.m. h:mm" );
286 //      fetchMeetings( from, to, iWindowManager->weeklyView()->currentRoom() );
287 }
288
289 void Engine::changeModeOrdered( DeviceManager::OperationMode aMode )
290 {       
291         qDebug() << "Engine::changeModeOrdered( DeviceManager::OperationMode )";
292         QString message = tr( "You are about to change operation mode to %1." )
293                                 .arg( iDevice->operationModeToString( aMode ) );
294
295         // iPasswordDialog->update( message );
296         iWindowManager->showDialog( static_cast<QDialog *>( iPasswordDialog ) );
297 }
298
299 void Engine::passwordEntered( PasswordDialog::PasswordStatus aPasswordStatus )
300 {
301         qDebug() << "Engine::passwordEntered( PasswordDialog::PasswordStatus )";
302 //      iWindowManager->closePasswordDialog();
303         
304         switch ( aPasswordStatus )
305         {
306                 case PasswordDialog::Correct :
307                 {
308 //                      iWindowManager->showProgressBar( "Changing current operation mode." );
309 //                      connect( iWindowManager, SIGNAL( progressBarCancelled() ), this, SLOT( progressBarCancelled() ) );
310 //                      connect( iDevice, SIGNAL( changingMode( const QString & ) ),
311 //                                      iWindowManager, SLOT( updateProgressBar( const QString & ) ) );
312                         iDevice->changeMode( true );
313                         break;
314                 }
315                 case PasswordDialog::Incorrect :
316                 {
317 //                      iWindowManager->error( tr( "Incorrect password." ) );
318                         iDevice->changeMode( false );
319                         break;
320                 }
321                 default : //case PasswordDialog::Canceled
322                 {
323                         iDevice->changeMode( false );
324                 }
325         }
326 }
327
328 void Engine::progressBarCancelled()
329 {
330         qDebug() << "Engine::progressBarCancelled()";
331         //TODO: cancel the on-going event
332 //      iWindowManager->closeProgressBar();
333         iDevice->changeMode( false );
334 }
335
336 void Engine::initUserInterface()
337 {
338         qDebug() << "[Engine::initUserInterface] <Invoked>";
339         // Initialize the window manager and connect what ever signals can be connected
340         iWindowManager = new WindowManager;
341         connect( iWindowManager, SIGNAL( eventDetected() ), this, SLOT( handleViewEvent() ) );
342         connect( iWindowManager, SIGNAL( previousViewRestored() ), this, SLOT( previousViewRestored() ) );
343         connect( iWindowManager, SIGNAL( dialogActivated() ), this, SLOT( dialogActivated() ) );
344         connect( iWindowManager, SIGNAL( dialogDeactivated() ), this, SLOT( dialogDeactivated() ) );
345         
346         // Initialize the weekly view and connect what ever signals can be connected at this stage
347         iWeeklyView = new WeeklyViewWidget(QDateTime::currentDateTime(), iConfiguration);
348         connect( iWeeklyView, SIGNAL( settingsButtonClicked() ), this, SLOT( settingsViewRequested() ) );
349         connect( iWeeklyView, SIGNAL( currentRoomChange( Room * ) ) , this, SLOT( currentRoomChange( Room * ) ) );
350         connect( iWeeklyView, SIGNAL( meetingActivated( Meeting * ) ), this, SLOT( fetchMeetingDetails( Meeting * ) ) ) ;
351         connect( iWeeklyView, SIGNAL( shownWeekChanged( QDate ) ) , this, SLOT( shownWeekChanged( QDate ) ) );
352         
353         // Initialize the settings view
354         iSettingsView = new SettingsView;
355         connect( iSettingsView, SIGNAL( okClicked() ) , this, SLOT( settingsOkClicked() ) );
356         
357         // Initialize the room status indicator
358         iRoomStatusIndicator = new RoomStatusIndicatorWidget( defaultRoom(), Room::FreeStatus, QTime::currentTime(), iConfiguration->displaySettings()->dateFormat() );
359         
360         // Create password dialog
361         iPasswordDialog = new PasswordDialog( iConfiguration->adminPassword(), tr("No Text Set"), tr("Title") );
362         connect( iPasswordDialog, SIGNAL( passwordEntered( PasswordDialog::PasswordStatus ) ), this, SLOT( passwordEntered( PasswordDialog::PasswordStatus ) ) );
363         
364         // Show the UI
365         iWindowManager->setWindowState( Qt::WindowMaximized );
366         iWindowManager->show();
367         iWindowManager->showView( iWeeklyView );
368         
369         qDebug() << "[Engine::initUserInterface] <Finished>";
370 }
371
372 void Engine::settingsViewRequested()
373 {
374         if ( iSettingsView != 0 )
375         {
376                 iWindowManager->showView( static_cast<ViewBase *>( iSettingsView ) );
377                 // Room status indicator will not be shown when settings view is active
378                 iIdleTimeCounter->stop();
379         }
380 }
381
382 void Engine::handleViewEvent()
383 {
384         qDebug() << "[Engine::handleViewEvent] <Invoked>";
385         if ( iIdleTimeCounter != 0 )
386         {
387                 // Restart the idle time counter when view event is received
388                 iIdleTimeCounter->stop();
389                 iIdleTimeCounter->start();
390         }
391 }
392
393 void Engine::initConfiguration()
394 {
395         iConfiguration = Configuration::instance();
396         if ( iConfiguration == 0 )
397         {
398                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
399         }
400 }
401
402 void Engine::idleTimerTimeout()
403 {
404         if ( iRoomStatusIndicator != 0 )
405         {
406                 iWindowManager->showView( static_cast<ViewBase *>( iRoomStatusIndicator ) );
407         }
408 }
409
410 void Engine::settingsOkClicked()
411 {
412         if ( iWeeklyView != 0 )
413         {
414                 iWindowManager->showView( iWeeklyView );
415                 // Start the idle time counter when we return to the main view
416                 iIdleTimeCounter->start();
417         }
418 }
419
420 void Engine::connectSignals()
421 {
422         // Handle weekly view signal connections
423         connect( iClock, SIGNAL( tick( QDateTime ) ), iWeeklyView, SLOT( setCurrentDateTime( QDateTime ) ) );
424 }
425
426 void Engine::initCommunication()
427 {
428         // initialize communication
429         iCommunication = new CommunicationManager( *(iConfiguration->connectionSettings()) );
430         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
431                         this, SLOT( errorHandler( int ) ) );
432         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
433                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
434         connect( iCommunication, SIGNAL( meetingDetailsFetched( Meeting& ) ),
435                         this, SLOT( meetingDetailsFetched( Meeting& ) ) );
436 }
437
438 void Engine::initDevice()
439 {
440         // create device manager
441         iDevice = new DeviceManager( iConfiguration->startupSettings() );
442         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
443         connect( iDevice, SIGNAL( changeModeOrdered( DeviceManager::OperationMode ) ), 
444                         this, SLOT( changeModeOrdered( DeviceManager::OperationMode ) ) );
445         iDevice->initDeviceManager();
446 }
447
448 void Engine::dialogActivated()
449 {
450         if ( iIdleTimeCounter != 0 )
451         {
452                 iIdleTimeCounter->stop();
453         }
454 }
455
456 void Engine::dialogDeactivated()
457 {
458         if ( iIdleTimeCounter != 0 )
459         {
460                 iIdleTimeCounter->start();
461         }
462 }
463
464 void Engine::previousViewRestored()
465 {
466         if ( iIdleTimeCounter != 0 )
467         {
468                 iIdleTimeCounter->start();
469         }
470 }