Buttons resized and Registration button's place changed.
[speedfreak] / Client / carmainwindow.cpp
1 /*
2  * CarMainWindow main class
3  *
4  * @author     Toni Jussila <toni.jussila@fudeco.com>
5  * @author     Janne Änäkkälä <janne.anakkala@fudeco.com>
6  * @author     Tiina Kivilinna-Korhola <tiina.kivilinna-korhola@fudeco.com>
7  * @author     Olavi Pulkkinen <olavi.pulkkinen@fudeco.com>
8  * @copyright  (c) 2010 Speed Freak team
9  * @license    http://opensource.org/licenses/gpl-license.php GNU Public License
10  */
11
12 #include "carmainwindow.h"
13 #include "math.h"
14
15 /**
16   *Constructor of this class.
17   *@param QWidget pointer to parent object. By default the value is NULL.
18   */
19 CarMainWindow::CarMainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::CarMainWindow)
20 {
21     ui->setupUi(this);
22     ui->tabWidget->setCurrentWidget(this->ui->StartTab);
23     //result = new ResultDialog();
24     //measure = new MeasureDialog();
25     xmlreader = new XmlReader();
26
27     initComboBoxStartTabUnits();
28     initListViewStartTabAccelerationCategories();
29
30     myLogin = new LoginWindow(this);
31     myRegistration = new Registration(this);
32     xmlwriter = new XmlWriter();
33     manager = new QNetworkAccessManager(this);
34     connect(myRegistration,SIGNAL(sendregistration()),this,SLOT(registrate()));
35
36     time = 0;
37     speed = 0;
38     timer = new QTimer();
39
40     accelerometer = new Accelerometer();
41     accelerometer->setSampleRate(100);
42
43     measures = new Measures();
44     this->initializeMeasures();
45
46     timer->setInterval(300);
47
48     connect(this->timer, SIGNAL(timeout()), this, SLOT(after_timeout()));
49     connect(myLogin, SIGNAL( userNameChanged()), this, SLOT(updateUserName()));
50
51     ui->labelMeasureTabResult->hide();
52
53     this->setWindowTitle("Speed freak");
54
55 }
56
57 /**
58   *Destructor of this class. Should be used to release all allocated resources.
59   */
60 CarMainWindow::~CarMainWindow()
61 {
62     delete ui;
63     //delete result;
64     //delete measure;
65     delete xmlreader;
66     delete xmlwriter;
67     delete manager;
68 }
69
70 /**
71   *This function is used to .
72   *@param
73   */
74 void CarMainWindow::changeEvent(QEvent *e)
75 {
76     QMainWindow::changeEvent(e);
77     switch (e->type()) {
78     case QEvent::LanguageChange:
79         ui->retranslateUi(this);
80         break;
81     default:
82         break;
83     }
84 }
85
86 /**
87   *This slot function is called when ever list view is update. Start-tab view.
88   */
89 void CarMainWindow::on_listViewStartTabAccelerationCategories_clicked(QModelIndex index)
90 {
91     QString str = index.data().toString();
92     QStringList list = str.split("-");
93     QStringList list2 = list[1].split(" ");
94
95     ui->lineEditStartTabMin->setText(list[0]);
96     ui->lineEditStartTabMax->setText(list2[0]);
97     updateComboBoxStartTabUnits(list2[1]);
98 }
99
100 /**
101   *This slot function is called when ever auto start button clicked. Start-tab view.
102   */
103 void CarMainWindow::on_autoStartButton_clicked()
104 {
105
106     //delete measure;
107     //measure = NULL;
108     //measure = new MeasureDialog();
109    // connect(measure, SIGNAL(speedAchieved()), this, SLOT(openResultView()));
110     accelerometer->start();
111     timer->start();
112     // Show measure dialog.
113     //measure->show();
114     ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
115 }
116
117 /**
118   *This slot function is called when ever list view is update. Start-tab view.
119   *@param QString unit.
120   */
121 void CarMainWindow::updateComboBoxStartTabUnits(QString unit)
122 {
123     ui->comboBoxStartTabUnits->setCurrentIndex(ui->comboBoxStartTabUnits->findText(unit, Qt::MatchExactly));
124 }
125
126 /**
127   *This function is used to init unit combobox. Start-tab view.
128   */
129 void CarMainWindow::initComboBoxStartTabUnits()
130 {
131     units << "km/h" << "km" << "h" << "m" << "min" << "Mile" << "Mph" << "in" << "ft" << "yrd";
132     ui->comboBoxStartTabUnits->addItems(units);
133 }
134
135 /**
136   *This function is used to set items to unit combobox. Start-tab view.
137   *@param QStringlist units
138   */
139 void CarMainWindow::setComboBoxStartTabUnits(QStringList units)
140 {
141     ui->comboBoxStartTabUnits->addItems(units);
142 }
143
144 /**
145   *This function is used to init listViewStartTabAccelerationCategories. Start-tab view.
146   */
147 void CarMainWindow::initListViewStartTabAccelerationCategories()
148 {
149     accelerationCategoriesStartTab << "0-40 km/h" << "0-100 km/h"; //<< "0-1/4 Mile" << "0-1/8 Mile" << "0-50 km" << "50-100 Mile" << "0-60 Mph" << "0-100 m" << "0-50 ft" << "0-50 yrd" << "0-500 in";
150     QAbstractItemModel *model = new StringListModel(accelerationCategoriesStartTab);
151     ui->listViewStartTabAccelerationCategories->setModel(model);
152 }
153
154 /**
155   *This function is used to set items to listViewStartTabAccelerationCategories. Start-tab view.
156   *@param QStringlist accelerationCategoriesStartTab
157   */
158 void CarMainWindow::setListViewStartTabAccelerationCategories(QStringList accelerationCategoriesStartTab)
159 {
160     QAbstractItemModel *model = new StringListModel(accelerationCategoriesStartTab);
161     ui->listViewStartTabAccelerationCategories->setModel(model);
162 }
163
164 /**
165   *This function is used to set items to category combobox. Top-tab view.
166   *@param
167   */
168 void CarMainWindow::setCategoryCompoBox()
169 {
170     ui->comboBoxTopCategory->addItems(xmlreader->getTop10List());
171 }
172
173 /**
174   *This function is used to set items to labelTopList. Top-tab view.
175   *@param QString category
176   */
177 void CarMainWindow::setListViewTopList(QString category)
178 {
179     QString topList;
180
181     if (category == "acceleration-0-100")
182     {
183         topList.append(xmlreader->getTop10AccelerationList());
184     }
185
186     else if (category == "Speed")
187     {
188         topList.append(xmlreader->getTop10SpeedList());
189     }
190
191     else if (category == "G-force")
192     {
193         topList.append(xmlreader->getTop10GforceList());
194     }
195     ui->labelTopList->setText(topList);
196 }
197
198 /**
199   *This slot function is called when speed is achieved in measure dialog. Opens result dialog.
200   */
201 void CarMainWindow::openResultView()
202 {
203     //result->saveMeasuresToArray(measure->measures);
204     // Show result dialog.
205     //result->show();
206     ui->pushButtonSendResult->setEnabled(true);
207     QString timeInteger;
208     timeInteger.setNum(this->measures->getTime40kmh());
209     //time = "0 - 40 km/h: ";
210     //time.append(timeInteger);
211     //ui->labelResult40kmh->setText(time);
212     ui->labelMeasureTabResult->show();
213     ui->labelMeasureTabResult->setText(timeInteger);
214     //ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
215 }
216
217
218 /**
219   *This slot function is called when login/logout button is clicked.
220   */
221 void CarMainWindow::on_loginLogoutButton_clicked()
222 {
223     myLogin->show();
224 }
225
226 /**
227   *This slot function is called when registrate button is clicked.
228   */
229 void CarMainWindow::on_registratePushButton_clicked()
230 {
231     myRegistration->show();
232 }
233
234 /**
235   *This slot function is called when ever refresh button clicked. Top-tab view.
236   */
237 void CarMainWindow::on_buttonTopRefresh_clicked()
238 {
239     //setCategoryCompoBox();
240     requestTopList();
241 }
242
243 /**
244   *This slot function is called when ever category combobox current index changed. Top-tab view.
245   *@param QString category
246   */
247 void CarMainWindow::on_comboBoxTopCategory_currentIndexChanged(QString category)
248 {
249     setListViewTopList(category);
250 }
251
252 /**
253   *This slot function is called when ever category combobox activated. Top-tab view.
254   *@param QString category
255   */
256 void CarMainWindow::on_comboBoxTopCategory_activated(QString category)
257 {
258     setListViewTopList(category);
259 }
260
261 /**
262   *This slot function is called when set/change user button is clicked.
263   */
264 void CarMainWindow::on_setUserPushButton_clicked()
265 {
266     myLogin->show();
267
268     ui->userNameLabel->setText( "User: " + myLogin->getUserName());
269     ui->setUserPushButton->setText( "Change User");
270 }
271
272 /**
273   *@brief Sends registration information to the server in xml format.
274   *Reads user name, password and emaol address from resuldialogs internal variables.
275   *@todo Replace msg box with better reaction to server`s responce.
276   *@todo Write error handling.
277   */
278 void CarMainWindow::registrate()
279 {
280     qDebug() << "_registrate" ;
281     qDebug() << this->myRegistration->getUserName() << "+" << this->myRegistration->getPassword() << "+" << this->myRegistration->getEmail();
282
283     QBuffer *regbuffer = new QBuffer();
284     QUrl qurl("http://api.speedfreak-app.com/api/register");
285     QNetworkRequest request(qurl);
286     qDebug() << qurl.toString();
287
288     regbuffer->open(QBuffer::ReadWrite);
289     xmlwriter->writeRegistering(regbuffer,
290                       this->myRegistration->getUserName(),
291                       this->myRegistration->getPassword(),
292                       this->myRegistration->getEmail());
293     //Tmp msgbox - later server responce
294     QMessageBox::about(this,"Registrate",this->myRegistration->getUserName() + this->myRegistration->getPassword() + this->myRegistration->getEmail());
295
296     manager->post(request, ("data=" + regbuffer->data()));
297     qDebug() << "carmainwindow: regbuffer->data(): " << regbuffer->data();
298
299     //ackOfRegistration function gets called when HTTP request is completed
300     connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ackOfRegistration(QNetworkReply*)));
301     //connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
302     regbuffer->close();
303 }
304
305 /**
306   *@brief Sends result(s) to the server in xml format with authentication information in the header.
307   *@todo Write error handling.
308   */
309 void CarMainWindow::sendXml()
310 {
311     qDebug() << "_sendXml";
312
313     QBuffer *xmlbuffer = new QBuffer();
314     QString category_name = "acceleration-0-100";    //replace with real value from category list
315
316     QString credentials = this->myRegistration->getUserName() + ":" + this->myRegistration->getPassword();
317     credentials = "Basic " + credentials.toAscii().toBase64();
318
319     QUrl qurl("http://api.speedfreak-app.com/api/update/" + category_name);
320     qDebug() << qurl.toString();
321     QNetworkRequest request(qurl);
322     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
323
324     xmlbuffer->open(QBuffer::ReadWrite);
325     xmlwriter->writeResult(xmlbuffer);
326     qDebug() << "carmainwindow: xmlbuffer->data(): " << xmlbuffer->data();
327
328     manager->post(request, ("data=" + xmlbuffer->data()));
329     //connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ackOfResult(QNetworkReply*)));
330     //connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
331
332     //QNetworkReply *currentDownload;
333     //QString data("abcdefg");
334     //currentDownload = manager->post(request,"data=" + QUrl::toPercentEncoding(data));   //testing
335     //currentDownload = manager->post(request, ("data=" + xmlbuffer->data()));
336     //ackOfResult function gets called when HTTP request is completed
337     //connect(currentDownload, SIGNAL(finished()), SLOT(ackOfResult()));
338
339     xmlbuffer->close();
340 }
341
342 /**
343   *@brief Sends request to the server for a top list with authentication information in the header.
344   *@todo Write error handling.
345   *@todo Replace with real value from category list and limitNr
346   */
347 void CarMainWindow::requestTopList()
348 {
349     qDebug() << "_requestTopList" ;
350
351     QString urlBase = "http://api.speedfreak-app.com/api/results/";
352     QString category_name = "acceleration-0-100";    //replace with real value from category list/top window
353     int limitNr = 5;
354     QString limit = QString::number(limitNr);
355
356     QString credentials = this->myRegistration->getUserName() + ":" + this->myRegistration->getPassword();
357     credentials = "Basic " + credentials.toAscii().toBase64();
358
359     QUrl qurl(urlBase + category_name + "/" + limit);
360     qDebug() << qurl.toString();
361     QNetworkRequest request(qurl);
362
363     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
364     manager->post(request, ("data=" ));
365     //connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(networkResponse(QNetworkReply*)));
366     //connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
367
368     //QNetworkReply *currentDownload;
369     //currentDownload = manager->post(request, ("data=" ));
370     //ackOfResult function gets called when HTTP request is completed
371     //connect(currentDownload, SIGNAL(error()),SLOT(errorFromServer()));
372 }
373
374 /**
375   *@brief React to servers responce after result has been sent.
376   *@todo Implement function and write error handling.
377   */
378 void CarMainWindow::ackOfResult(QNetworkReply* reply)
379 {
380     qDebug() << "_ackOfResult";
381     qDebug() << reply->readAll();
382     QNetworkReply::NetworkError errorcode;
383     errorcode = reply->error();
384     if(errorcode != 0) {
385         qDebug() << errorcode << reply->errorString();
386     }
387     else {
388         qDebug() << "errorcode=0";
389     }
390 }
391
392 /**
393   *@brief React to servers responce after registration has been sent.
394   *@todo Implement function and write error handling.
395   */
396 void CarMainWindow::ackOfRegistration(QNetworkReply* reply)
397 {
398     qDebug() << "_ackOfRegistration";
399     qDebug() << reply->readAll();
400     QNetworkReply::NetworkError errorcode;
401     errorcode = reply->error();
402     if(errorcode != 0) {
403         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
404     }
405     else {
406         qDebug() << "errorcode=0";
407     }
408 }
409
410 void CarMainWindow::errorFromServer(QNetworkReply* reply)
411 {
412     qDebug() << "_errorFromServer";
413     QNetworkReply::NetworkError errorcode;
414
415     errorcode = reply->error();
416     if(errorcode != 0) {
417         qDebug() << errorcode;
418     }
419     else {
420         qDebug() << errorcode;
421     }
422 }
423
424 /**
425   *This slot function is called when the server has finished guery.
426   */
427 void CarMainWindow::networkResponse(QNetworkReply *reply)
428 {
429     qDebug() << "_networkResponse";
430     xmlreader->xmlRead(reply);
431     qDebug() << reply->readAll();
432     QNetworkReply::NetworkError errorcode;
433     errorcode = reply->error();
434     if(errorcode != 0) {
435         qDebug() << errorcode << reply->errorString();
436     }
437     else {
438         qDebug() << "errorcode=0";
439     }
440 }
441
442 /**
443   *@brief Just for development, for the real button is not shown until
444   *measurin started and there are results.
445   *@todo Implement with real code and yet leave sendXml in the bottom in use.
446   */
447 void CarMainWindow::on_manualStartButton_clicked()
448 {
449     sendXml();
450 }
451
452 /**
453   * This slot function is called when timer gives timeout signal. Checks current speed
454   * and stores times in measure class.
455   */
456 void CarMainWindow::after_timeout()
457 {
458     QString timeString, speedString;
459     //time++;
460     time = accelerometer->getTotalTime();
461     speed = accelerometer->getCurrentSpeed();
462     //speed = speed +10;
463
464     if (floor(speed) == 10)
465     {
466         measures->setTime10kmh(time);
467     }
468
469     else if (floor(speed) == 20)
470     {
471         measures->setTime20kmh(time);
472     }
473
474     else if (floor(speed) == 30)
475     {
476         measures->setTime30kmh(time);
477     }
478
479     else if (floor(speed) == 40)
480     {
481         measures->setTime40kmh(time);
482     }
483
484     else if (floor(speed) == 50)
485     {
486         measures->setTime50kmh(time);
487     }
488
489     else if (floor(speed) == 60)
490     {
491         measures->setTime60kmh(time);
492     }
493
494     else if (floor(speed) == 70)
495     {
496         measures->setTime70kmh(time);
497     }
498
499     else if (floor(speed) == 80)
500     {
501         measures->setTime80kmh(time);
502     }
503
504     else if (floor(speed) == 90)
505     {
506         measures->setTime90kmh(time);
507     }
508
509     else if (floor(speed) == 100)
510     {
511         measures->setTime100kmh(time);
512     }
513
514     else
515     {
516
517     }
518
519     // If speed is over 40 km/h emits speedAchieved() signal and close this dialog.
520     if (speed >= 40.0)
521     {
522         timer->stop();
523         accelerometer->stop();
524         time = 0;
525         speed = 0;
526         //emit this->speedAchieved();
527         this->openResultView();
528         //this->close();
529
530     }
531
532     // Updates speed and time.
533     else
534     {
535         timeString.setNum(time);
536         speedString.setNum(speed);
537         ui->labelMeasureTabTime->setText(timeString);
538         ui->labelMeasureTabSpeed->setText(speedString);
539
540         timer->start();
541     }
542
543 }
544
545 /**
546   * Initializes measures class's member variables.
547   */
548 void CarMainWindow::initializeMeasures()
549 {
550     measures->setTime10kmh(0);
551     measures->setTime20kmh(0);
552     measures->setTime30kmh(0);
553     measures->setTime40kmh(0);
554     measures->setTime50kmh(0);
555     measures->setTime60kmh(0);
556     measures->setTime70kmh(0);
557     measures->setTime80kmh(0);
558     measures->setTime90kmh(0);
559     measures->setTime100kmh(0);
560 }
561
562 /**
563   * This slot function is called when Abort button is clicked.
564   */
565 void CarMainWindow::on_pushButtonMeasureTabAbort_clicked()
566 {
567     measures->setTime10kmh(0);
568     measures->setTime20kmh(0);
569     measures->setTime30kmh(0);
570     measures->setTime40kmh(0);
571     measures->setTime50kmh(0);
572     measures->setTime60kmh(0);
573     measures->setTime70kmh(0);
574     measures->setTime80kmh(0);
575     measures->setTime90kmh(0);
576     measures->setTime100kmh(0);
577     timer->stop();
578     accelerometer->stop();
579     time = 0;
580     speed = 0;
581     ui->tabWidget->setCurrentWidget(this->ui->StartTab);
582     //this->close();
583 }
584
585 void CarMainWindow::on_pushButtonSendResult_clicked()
586 {
587     sendXml();
588     ui->pushButtonSendResult->setEnabled(false);
589 }
590
591 void CarMainWindow::updateUserName()
592 {
593     QString newUserName;
594
595     newUserName = myLogin->getUserName();
596     ui->userNameLabel->setText( "User: " + newUserName);
597
598     if (newUserName.length())
599     {
600        ui->setUserPushButton->setText( "Change User");
601        this->setWindowTitle("Speed freak - " + newUserName);
602     }
603     else
604     {
605         ui->setUserPushButton->setText( "Set User");
606         this->setWindowTitle("Speed freak");
607     }
608 }