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