First commit to dev_local, trying to merge with master..
[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
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 Engine::Engine() :
22                 iClock( 0 ), iConfiguration( Configuration::instance() ), iCommunication( 0 )
23 {
24         qDebug() << "Engine::Engine()";
25         iCommunicationFailed = false;
26         // if reading of configuration fails, signal that initialization failed
27         if ( iConfiguration == 0 )
28         {
29                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
30                 return;
31         }
32                 
33         //initialize window manager
34         iWindowManager = new WindowManager( iConfiguration );
35         connect( iWindowManager, SIGNAL( roomStatusInfoNeeded( Room * ) ), this, SLOT( roomStatusInfoNeeded( Room * ) ) );
36         connect( iWindowManager, SIGNAL( observedEventDetected() ), this, SLOT( observedEventDetected() ) );
37         connect( iWindowManager, SIGNAL( meetingActivated( Meeting * ) ), this, SLOT( fetchMeetingDetails( Meeting * ) ) );
38         connect( iWindowManager, SIGNAL( currentRoomChanged( Room * ) ), this, SLOT( currentRoomChanged( Room * ) ) );
39         connect( iWindowManager, SIGNAL( shownWeekChanged( QDate ) ), this, SLOT( shownWeekChanged( QDate ) ) );
40         connect( iWindowManager, SIGNAL( passwordEntered( PasswordDialog::PasswordStatus ) ),
41                         this, SLOT( passwordEntered( PasswordDialog::PasswordStatus ) ) );
42
43         
44         // initialize communication
45         iCommunication = new CommunicationManager( *(iConfiguration->connectionSettings()) );
46         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
47                         this, SLOT( errorHandler( int ) ) );
48         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
49                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
50         connect( iCommunication, SIGNAL( meetingDetailsFetched( Meeting& ) ),
51                         this, SLOT( meetingDetailsFetched( Meeting& ) ) );
52
53         //initialize idle time counter
54         iIdleTimeCounter = new QTimer();
55         iIdleTimeCounter->setSingleShot( true );
56         iIdleTimeCounter->setInterval( IDLE_TIME_MULTIPLIER * iConfiguration->displaySettings()->screensaver() );
57         iIdleTimeCounter->start();
58         connect( iIdleTimeCounter, SIGNAL( timeout() ), iWindowManager, SLOT( showRoomStatus() ) );
59
60         // create application clock
61         iClock = new Clock;
62         connect( iClock, SIGNAL( tick( QDateTime ) ), this, SLOT( checkStatusOfAllRooms() ) );
63         connect( iClock, SIGNAL( tick( QDateTime ) ), iWindowManager, SLOT( distributeDateTimeInfo( QDateTime ) ) );
64
65         iAutoRefresh = new QTimer;
66         iAutoRefresh->setInterval( iConfiguration->connectionSettings()->refreshInterval() * 1000 );
67         iAutoRefresh->start();
68         connect( iAutoRefresh, SIGNAL( timeout() ), iAutoRefresh, SLOT( start() ) );
69         connect( iAutoRefresh, SIGNAL( timeout() ), this, SLOT( fetchMeetings() ) );
70
71         // create device manager
72         iDevice = new DeviceManager( iConfiguration->startupSettings() );
73         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
74         connect( iDevice, SIGNAL( changeModeOrdered( DeviceManager::OperationMode ) ), 
75                         this, SLOT( changeModeOrdered( DeviceManager::OperationMode ) ) );
76         iDevice->initDeviceManager();
77         
78         if( iDevice->currentOperationMode() == DeviceManager::KioskMode )
79                 iWindowManager->fullScreen();
80
81         QTimer::singleShot( 0, this, SLOT( fetchMeetings() ) );
82
83         // TODO: continue implementation
84 }
85
86 Engine::~Engine()
87 {
88         qDebug() << "Engine::~Engine()";
89         while ( !iMeetings.isEmpty() )
90                 delete iMeetings.takeFirst();
91         iIdleTimeCounter->stop();
92         delete iIdleTimeCounter;
93         iIdleTimeCounter = 0;
94         delete iWindowManager;
95         iWindowManager = 0;
96         delete iClock;
97         iClock = 0;
98         delete iDevice;
99         iDevice = 0;
100 }
101
102 void Engine::closeApplication()
103 {
104         qDebug() << "Engine::closeApplication()";
105         // closes application after 1 second
106         QTimer::singleShot( 1000, QApplication::instance(), SLOT( quit() ) );
107 }
108
109 void Engine::observedEventDetected()
110 {
111         qDebug() << "Engine::observedEventDetected()";
112         iWindowManager->showWeeklyView();
113         // prepare to restart idle counter
114         if ( iIdleTimeCounter->isActive() )
115         {
116                 iIdleTimeCounter->stop();
117         }
118         // (re)start idle counter
119         iIdleTimeCounter->start();
120 }
121
122 Room* Engine::defaultRoom()
123 {
124         qDebug() << "Engine::defaultRoom()";
125         return iConfiguration->defaultRoom();
126 }
127
128 void Engine::checkStatusOfAllRooms()
129 {
130         qDebug() << "Engine::checkStatusOfAllRooms()";
131         // iterate trough on the rooms
132         for ( int i = 0; i < iConfiguration->rooms().count(); i++ )
133         {
134                 // and check the status
135                 roomStatusInfoNeeded( iConfiguration->rooms().at( i ) );
136         }
137 }
138
139 int Engine::indexOfMeetingAt( Room *aRoom, QDateTime aAt )
140 {
141         qDebug() << "Engine::indexOfMeetingAt( Room *, QDateTime )";
142         for ( int i = 0; i < iMeetings.count(); i++ )
143         {
144                 // exchange server ensures that there is only one meeting in a room at a specified time
145                 if ( aRoom->equals( iMeetings.at( i )->room() )
146                           && iMeetings.at( i )->startsAt() <= aAt
147                           && iMeetings.at( i )->endsAt() >= aAt )
148                 {
149                         return i;
150                 }
151         }
152         return -1;
153 }
154
155 int Engine::indexOfMeetingAfter( Room *aRoom, QDateTime aAfter )
156 {
157         qDebug() << "Engine::indexOfMeetingAfter( Room *, QDateTime )";
158         // seeks for the next meeting on the SAME DAY
159         int min = -1;
160         for ( int i = 0; i < iMeetings.count(); i++ )
161         {
162                 // if the meeting is in the same room, on the same day but after the specified time
163                 if ( aRoom->equals( iMeetings.at( i )->room() )
164                           && iMeetings.at( i )->startsAt().date() == aAfter.date()
165                           && iMeetings.at( i )->startsAt() > aAfter )
166                 {
167                         // if there was not any meeting find yet or the previously found is a later one then the (i)th
168                         if ( min == -1
169                                   || iMeetings.at( min )->startsAt() > iMeetings.at( i )->startsAt() )
170                         {
171                                 min = i;
172                         }
173                 }
174         }
175         return min;
176 }
177
178 void Engine::roomStatusInfoNeeded( Room *aRoom )
179 {
180         qDebug() << "Engine::roomStatusInfoNeeded( Room * )";
181         if ( aRoom == 0 )
182         {
183                 return;
184         }
185
186         int indexOfCurrentMeeting = indexOfMeetingAt( aRoom, iClock->datetime() );
187         int indexOfNextMeeting = indexOfMeetingAfter( aRoom, iClock->datetime() );
188
189         // if there is no meeting, then status is Free; otherwise Busy
190         Room::Status status = ( indexOfCurrentMeeting == -1 ) ? Room::FreeStatus : Room::BusyStatus;
191         // if room is Busy, then check end time, otherwise...
192         QTime until = ( status == Room::BusyStatus ) ? iMeetings.at( indexOfCurrentMeeting )->endsAt().time() :
193                           // ...if there is meeting following on the same day then check end time, otherwise end is the of the working day
194                           (( indexOfNextMeeting != -1 ) ? iMeetings.at( indexOfNextMeeting )->startsAt().time() : Engine::endOfTheDay );
195
196         //currently works only for deafult room
197         if( aRoom->equals( *(defaultRoom() ) ) )
198                 iWindowManager->roomStatusChanged( aRoom, status, until );
199 }
200
201 void Engine::fetchMeetings()
202 {
203         Room *room = defaultRoom();
204         qDebug() << "Engine::fetchMeetings for " << room->name();
205         fetchMeetings( iClock->datetime(), iClock->datetime().addDays( 7 ), room );
206 }
207
208 void Engine::fetchMeetingDetails( Meeting *aMeeting )
209 {
210         qDebug() << "Engine::fetchMeetingDetails( Meeting* )";
211         iWindowManager->showProgressBar( tr("Please Wait"), true );
212         iWindowManager->updateProgressBar( tr("Fetching Meeting Details...") );
213         connect( iWindowManager,
214                          SIGNAL( progressBarCancelled() ),
215                          this,
216                          SLOT( fetchMeetingDetailsCancelled() )
217                         );
218         iCommunication->fetchMeetingDetails( *aMeeting );
219 }
220
221 bool Engine::isMeetingInList( const QList<Meeting*> &aList, const Meeting *aMeeting )
222 {
223         qDebug() << "Engine::isMeetingInList( const QList<Meeting*> &, const Meeting * )";
224         for ( int i = 0; i < aList.count(); i++ )
225         {
226                 if ( aMeeting->equals( *(aList.at( i )) ) )
227                 {
228                         return true;
229                 }
230         }
231         return false;
232 }
233
234 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
235 {
236         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
237         if( iCommunicationFailed )
238         {
239                 iCommunicationFailed = false;
240                 //iWindowManager->connectionEstablished();
241         }
242
243         // check if there is any new meeting in the list came from the server -> added
244         for ( int i = 0; i < aMeetings.count(); i++ )
245         {
246                 // if the (i)th meeting is not in the local meeting list
247                 if ( !isMeetingInList( iMeetings, aMeetings.at( i ) ) )
248                 {
249                         // add to the local database =)
250                         Meeting* m = new Meeting( *(aMeetings.at( i )) );
251                         iMeetings.append( m );
252                         // and signal the changes
253                         iWindowManager->insertMeeting( m );
254                 }
255         }
256
257         // check if there is any meeting NOT in the list came from the server -> deleted
258         for ( int i = 0; i < iMeetings.count(); i++ )
259         {
260                 // if the (i)th meeting is in the local but NOT in the server's meeting list
261                 if ( !isMeetingInList( aMeetings, iMeetings.at( i ) ) )
262                 {
263                         Meeting* m = iMeetings.takeAt( i );
264                         // signal the changes
265                         iWindowManager->deleteMeeting( m );
266                         // delete the meeting from the local list
267                         delete m;
268                 }
269         }
270
271         // refresh room status info
272         roomStatusInfoNeeded( defaultRoom() );
273 }
274
275 void Engine::meetingDetailsFetched( Meeting &aDetailedMeeting )
276 {
277         qDebug() << "Engine::meetingDetailsFetched( Meeting & )";
278         iWindowManager->closeProgressBar();
279         if( iCommunicationFailed )
280         {
281                 iCommunicationFailed = false;
282                 iWindowManager->connectionEstablished();
283         }
284         iWindowManager->showMeetingInfo( &aDetailedMeeting );
285 }
286
287 void Engine::errorHandler( int aCode, const QString &aAddInfo )
288 {
289         qDebug() << "Engine::ErrorHandler, aCode: " << aCode;
290         // inform UI about the problem
291         if( aCode >= 100 && aCode <= 150 )
292         {
293                 qDebug() << "CommunicationManager signaled an error:" << aCode;
294                 if( !iCommunicationFailed )
295                 {
296                         // Only inform window manager when first error appears
297                         iCommunicationFailed = true;
298                         //iWindowManager->connectionLost();
299                 }
300         }
301         iWindowManager->closeProgressBar();
302         iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
303 }
304
305 void Engine::currentRoomChanged( Room *aCurrentRoom )
306 {
307         qDebug() << "Engine::currentRoomChanged to " << aCurrentRoom->name();
308         QDateTime from( iWindowManager->weeklyView()->beginnigOfShownWeek() );
309         QDateTime to( from.addDays( 8 ) );
310         fetchMeetings( from, to, aCurrentRoom );
311 }
312
313 void Engine::fetchMeetings( const QDateTime &aFrom, const QDateTime &aUntil, const Room *aIn )
314 {
315         qDebug() << "Engine::fetchMeetings( const QDateTime &, const QDateTime &, const Room * )";
316         iCommunication->fetchMeetings( aFrom, aUntil, *aIn );
317 }
318
319 void Engine::shownWeekChanged( QDate aFrom )
320 {
321         qDebug() << "Engine::shownWeekChanged( QDate )";
322         QDateTime from( aFrom );
323         QDateTime to( aFrom.addDays( 7 ), QTime( 23, 59 ) );
324         qDebug() << "Engine::shownWeekChanged " << aFrom.toString( "d.m. h:mm" ) << " to " << to.toString( "d.m. h:mm" );
325         fetchMeetings( from, to, iWindowManager->weeklyView()->currentRoom() );
326 }
327
328 void Engine::changeModeOrdered( DeviceManager::OperationMode aMode )
329 {       
330         qDebug() << "Engine::changeModeOrdered( DeviceManager::OperationMode )";
331         QString message = tr( "You are about to change operation mode to %1." )
332                                 .arg( iDevice->operationModeToString( aMode ) );
333         
334         iWindowManager->showPasswordDialog( iConfiguration->adminPassword(), message );
335 }
336
337 void Engine::passwordEntered( PasswordDialog::PasswordStatus aPasswordStatus )
338 {
339         qDebug() << "Engine::passwordEntered( PasswordDialog::PasswordStatus )";
340         iWindowManager->closePasswordDialog();
341         
342         switch ( aPasswordStatus )
343         {
344                 case PasswordDialog::Correct :
345                 {
346                         iWindowManager->showProgressBar( "Changing current operation mode." );
347                         connect( iWindowManager, SIGNAL( progressBarCancelled() ), this, SLOT( progressBarCancelled() ) );
348                         connect( iDevice, SIGNAL( changingMode( const QString & ) ),
349                                         iWindowManager, SLOT( updateProgressBar( const QString & ) ) );
350                         iDevice->changeMode( true );
351                         break;
352                 }
353                 case PasswordDialog::Incorrect :
354                 {
355                         iWindowManager->error( tr( "Incorrect password." ) );
356                         iDevice->changeMode( false );
357                         break;
358                 }
359                 default : //case PasswordDialog::Canceled
360                 {
361                         iDevice->changeMode( false );
362                 }
363         }
364 }
365
366 void Engine::progressBarCancelled()
367 {
368         qDebug() << "Engine::progressBarCancelled()";
369         //TODO: cancel the on-going event
370         iWindowManager->closeProgressBar();
371         iDevice->changeMode( false );
372 }
373
374 void Engine::fetchMeetingDetailsCancelled()
375 {
376         iCommunication->cancelFetchMeetingDetails();
377         iWindowManager->closeProgressBar();
378 }