summaryrefslogtreecommitdiff
path: root/src/components/application_manager/include/application_manager/application_manager_impl.h
blob: 0770cba4b167e086808da902269d0e3e375e9523 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_IMPL_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_IMPL_H_

#include <stdint.h>
#include <algorithm>
#include <atomic>
#include <deque>
#include <map>
#include <memory>
#include <set>
#include <vector>

#include "application_manager/app_launch/app_launch_data.h"
#include "application_manager/app_service_manager.h"
#include "application_manager/application_manager.h"
#include "application_manager/application_manager_settings.h"
#include "application_manager/command_factory.h"
#include "application_manager/command_holder.h"
#include "application_manager/event_engine/event_dispatcher_impl.h"
#include "application_manager/hmi_capabilities.h"
#include "application_manager/hmi_interfaces_impl.h"
#include "application_manager/message.h"
#include "application_manager/message_helper.h"
#include "application_manager/resumption/resume_ctrl.h"
#include "application_manager/rpc_handler.h"
#include "application_manager/rpc_service.h"
#include "application_manager/state_controller_impl.h"

#include "application_manager/rpc_handler.h"

#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/policies/policy_handler_observer.h"
#include "connection_handler/connection_handler.h"
#include "connection_handler/connection_handler_observer.h"
#include "connection_handler/device.h"
#include "formatters/CSmartFactory.h"
#include "hmi_message_handler/hmi_message_observer.h"
#include "hmi_message_handler/hmi_message_sender.h"
#include "policies/policy_handler.h"
#include "protocol_handler/protocol_handler.h"
#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/service_status_update_handler_listener.h"

#include "interfaces/HMI_API.h"
#include "interfaces/HMI_API_schema.h"
#include "interfaces/MOBILE_API_schema.h"

#include "interfaces/v4_protocol_v1_2_no_extra.h"
#include "interfaces/v4_protocol_v1_2_no_extra_schema.h"

#ifdef ENABLE_SECURITY
#include "security_manager/security_manager_listener.h"
#include "security_manager/ssl_context.h"
#endif  // ENABLE_SECURITY

#ifdef TELEMETRY_MONITOR
#include "telemetry_observer.h"
#endif  // TELEMETRY_MONITOR

#include "utils/macro.h"

#include "smart_objects/smart_object.h"
#include "utils/data_accessor.h"
#include "utils/lock.h"
#include "utils/message_queue.h"
#include "utils/prioritized_queue.h"
#include "utils/threads/message_loop_thread.h"
#include "utils/threads/thread.h"
#include "utils/timer.h"

struct BsonObject;

namespace threads {
class Thread;
}
class CommandNotificationImpl;

namespace application_manager {
namespace mobile_api = mobile_apis;
using namespace utils;
using namespace timer;
namespace custom_str = custom_string;

class ApplicationManagerImpl;

enum VRTTSSessionChanging { kVRSessionChanging = 0, kTTSSessionChanging };

typedef std::map<protocol_handler::ServiceType, std::set<uint32_t> >
    ServiceStreamingStatusMap;

typedef std::map<const int32_t, ExpiredButtonRequestData>
    ExpiredButtonRequestsMap;

struct CommandParametersPermissions;
typedef std::map<std::string, hmi_apis::Common_TransportType::eType>
    DeviceTypes;

struct AppIconInfo {
  std::string endpoint;
  bool pending_request;
  AppIconInfo();
  AppIconInfo(std::string ws_endpoint, bool pending)
      : endpoint(ws_endpoint), pending_request(pending) {}
};

SDL_CREATE_LOG_VARIABLE("ApplicationManager")
typedef std::shared_ptr<timer::Timer> TimerSPtr;

class ApplicationManagerImpl
    : public ApplicationManager,
      public connection_handler::ConnectionHandlerObserver,
      public policy::PolicyHandlerObserver,
      public protocol_handler::ServiceStatusUpdateHandlerListener
#ifdef ENABLE_SECURITY
    ,
      public security_manager::SecurityManagerListener
#endif  // ENABLE_SECURITY
#ifdef TELEMETRY_MONITOR
    ,
      public telemetry_monitor::TelemetryObservable<AMTelemetryObserver>
#endif  // TELEMETRY_MONITOR
{

  friend class ResumeCtrl;
  friend class CommandImpl;

 public:
  ApplicationManagerImpl(const ApplicationManagerSettings& am_settings,
                         const policy::PolicySettings& policy_settings);
  ~ApplicationManagerImpl();

  /**
   * Inits application manager
   */
  bool Init(resumption::LastStateWrapperPtr last_state_wrapper,
            media_manager::MediaManager* media_manager) OVERRIDE;

  /**
   * @brief Stop work.
   *
   * @return TRUE on success otherwise FALSE.
   **/
  bool Stop() OVERRIDE;

  DataAccessor<ApplicationSet> applications() const OVERRIDE;
  DataAccessor<AppsWaitRegistrationSet> pending_applications() const OVERRIDE;
  DataAccessor<ReregisterWaitList> reregister_applications() const OVERRIDE;
  ApplicationSharedPtr application(uint32_t app_id) const OVERRIDE;

  ApplicationSharedPtr active_application() const OVERRIDE;

  ApplicationSharedPtr get_full_or_limited_application() const OVERRIDE;

  ApplicationSharedPtr application_by_hmi_app(
      uint32_t hmi_app_id) const OVERRIDE;
  ApplicationSharedPtr application_by_policy_id(
      const std::string& policy_app_id) const OVERRIDE;
  ApplicationSharedPtr pending_application_by_hmi_app(
      uint32_t hmi_app_id) const OVERRIDE;
  ApplicationSharedPtr pending_application_by_policy_id(
      const std::string& policy_app_id) const OVERRIDE;
  ApplicationSharedPtr reregister_application_by_policy_id(
      const std::string& policy_app_id) const OVERRIDE;

  std::vector<ApplicationSharedPtr> applications_by_name(
      const std::string& app_name) const OVERRIDE;
  std::vector<ApplicationSharedPtr> applications_by_button(
      uint32_t button) OVERRIDE;
  std::vector<ApplicationSharedPtr> applications_with_navi() OVERRIDE;
  std::vector<ApplicationSharedPtr> applications_with_mobile_projection()
      OVERRIDE;

  ApplicationSharedPtr get_limited_media_application() const OVERRIDE;
  ApplicationSharedPtr get_limited_navi_application() const OVERRIDE;
  ApplicationSharedPtr get_limited_voice_application() const OVERRIDE;
  ApplicationSharedPtr get_limited_mobile_projection_application()
      const OVERRIDE;

  uint32_t application_id(const int32_t correlation_id) OVERRIDE;
  void set_application_id(const int32_t correlation_id,
                          const uint32_t app_id) OVERRIDE;

  uint32_t get_current_audio_source() const OVERRIDE;

  void set_current_audio_source(const uint32_t source) OVERRIDE;

  void OnHMIStateChanged(const uint32_t app_id,
                         const HmiStatePtr from,
                         const HmiStatePtr to) OVERRIDE;

  void ProcessOnDataStreamingNotification(
      const protocol_handler::ServiceType service_type,
      const uint32_t app_id,
      const bool streaming_data_available) FINAL;

  void SendDriverDistractionState(ApplicationSharedPtr application);

  void SendGetIconUrlNotifications(const uint32_t connection_key,
                                   ApplicationSharedPtr application);

  ApplicationSharedPtr application(
      const std::string& device_id,
      const std::string& policy_app_id) const OVERRIDE;

  /**
   * @brief ChangeAppsHMILevel the function that will change application's
   * hmi level.
   *
   * @param app_id id of the application whose hmi level should be changed.
   *
   * @param level new hmi level for certain application.
   */
  void ChangeAppsHMILevel(uint32_t app_id, mobile_apis::HMILevel::eType level);

  virtual plugin_manager::RPCPluginManager& GetPluginManager() OVERRIDE {
    DCHECK(plugin_manager_);
    return *plugin_manager_;
  }

  virtual AppServiceManager& GetAppServiceManager() OVERRIDE {
    DCHECK(app_service_manager_);
    return *app_service_manager_;
  }

  std::vector<std::string> devices(
      const std::string& policy_app_id) const OVERRIDE;

  /**
   * @brief Checks if application with the same HMI type
   *        (media, voice communication or navi) exists
   *        in HMI_FULL or HMI_LIMITED level.
   *
   * @param app Pointer to application to compare with
   *
   * @return true if exist otherwise false
   */
  bool IsAppTypeExistsInFullOrLimited(ApplicationConstSharedPtr app) const;

  /**
   * @brief Checks if Application is subscribed for way points
   * @param Application id
   * @return true if Application is subscribed for way points
   * otherwise false
   */
  bool IsAppSubscribedForWayPoints(uint32_t app_id) const OVERRIDE;

  /**
   * @brief Checks if Application is subscribed for way points
   * @param Application reference
   * @return true if Application is subscribed for way points
   * otherwise false
   */
  bool IsAppSubscribedForWayPoints(Application& app) const OVERRIDE;

  void SaveWayPointsMessage(smart_objects::SmartObjectSPtr way_points_message,
                            uint32_t app_id = 0) OVERRIDE;

  void SubscribeAppForWayPoints(uint32_t app_id,
                                bool response_from_hmi = true) OVERRIDE;

  void SubscribeAppForWayPoints(ApplicationSharedPtr app,
                                bool response_from_hmi = true) OVERRIDE;

  void UnsubscribeAppFromWayPoints(uint32_t app_id,
                                   bool response_from_hmi = true) OVERRIDE;

  void UnsubscribeAppFromWayPoints(ApplicationSharedPtr app,
                                   bool response_from_hmi = true) OVERRIDE;

  bool IsSubscribedToHMIWayPoints() const OVERRIDE;

  /**
   * @brief Is Any Application is subscribed for way points
   * @return true if some app is subscribed otherwise false
   */
  bool IsAnyAppSubscribedForWayPoints() const OVERRIDE;

  /**
   * @brief Get subscribed for way points
   * @return reference to set of subscribed apps for way points
   */
  const std::set<uint32_t> GetAppsSubscribedForWayPoints() const OVERRIDE;

  /**
   * @brief Notifies all components interested in Vehicle Data update
   * i.e. new value of odometer etc and returns list of applications
   * subscribed for event.
   * @param vehicle_info Enum value of type of vehicle data
   * @param new value (for integer values currently) of vehicle data
   */
  void IviInfoUpdated(const std::string& vehicle_info, int value) OVERRIDE;

  void OnApplicationRegistered(ApplicationSharedPtr app) OVERRIDE;

  /**
   * @brief OnApplicationSwitched starts processing of commands collected
   * during device switching process
   * @param app Application
   */
  void OnApplicationSwitched(ApplicationSharedPtr app) OVERRIDE;

  HMICapabilities& hmi_capabilities() OVERRIDE;
  const HMICapabilities& hmi_capabilities() const OVERRIDE;

  /**
   * @brief ProcessQueryApp executes logic related to QUERY_APP system request.
   *
   * @param sm_object smart object wich is actually parsed json obtained within
   * system request.
   * @param connection_key connection key for app, which sent system request
   */
  void ProcessQueryApp(const smart_objects::SmartObject& sm_object,
                       const uint32_t connection_key) OVERRIDE;

  bool is_attenuated_supported() const OVERRIDE;

#ifdef TELEMETRY_MONITOR
  /**
   * @brief Setup observer for time metric.
   *
   * @param observer - pointer to observer
   */
  void SetTelemetryObserver(AMTelemetryObserver* observer) OVERRIDE;
#endif  // TELEMETRY_MONITOR

  ApplicationSharedPtr RegisterApplication(
      const std::shared_ptr<smart_objects::SmartObject>&
          request_for_registration) OVERRIDE;

  void FinalizeAppRegistration(ApplicationSharedPtr application,
                               const uint32_t connection_key) OVERRIDE;
  /*
   * @brief Closes application by id
   *
   * @param app_id Application id
   * @param reason reason of unregistering application
   * @param is_resuming describes - is this unregister
   *        is normal or need to be resumed\
   * @param is_unexpected_disconnect
   * Indicates if connection was unexpectedly lost(TM layer, HB)
   */
  void UnregisterApplication(const uint32_t& app_id,
                             mobile_apis::Result::eType reason,
                             bool is_resuming = false,
                             bool is_unexpected_disconnect = false) OVERRIDE;

  /**
   * @brief Handle sequence for unauthorized application
   * @param app_id Application id
   */
  void OnAppUnauthorized(const uint32_t& app_id) OVERRIDE;

  /*
   * @brief Sets unregister reason for closing all registered applications
   * duringHU switching off
   *
   * @param reason Describes the reason for HU switching off
   */
  void SetUnregisterAllApplicationsReason(
      mobile_api::AppInterfaceUnregisteredReason::eType reason) OVERRIDE;

  /*
   * @brief Called on Master_reset or Factory_defaults
   * when User chooses to reset HU.
   * Resets Policy Table if applicable.
   */
  void HeadUnitReset(
      mobile_api::AppInterfaceUnregisteredReason::eType reason) OVERRIDE;

  /*
   * @brief Closes all registered applications
   */
  void UnregisterAllApplications();

  bool ActivateApplication(ApplicationSharedPtr app) OVERRIDE;

  /**
   * @brief Put application in FULL HMI Level if possible,
   *        otherwise put applicatuion other HMI level.
   *        do not send any notifications to mobile
   * @param app, application, that need to be puted in FULL
   * @return seted HMI Level
   */
  mobile_api::HMILevel::eType IsHmiLevelFullAllowed(ApplicationSharedPtr app);

  void ConnectToDevice(const std::string& device_mac) OVERRIDE;

  void OnHMIReady() OVERRIDE;

  void RequestForInterfacesAvailability() OVERRIDE;

  void DisconnectCloudApp(ApplicationSharedPtr app) OVERRIDE;

  void RefreshCloudAppInformation() OVERRIDE;

  void CreatePendingApplication(
      const transport_manager::ConnectionUID connection_id,
      const transport_manager::DeviceInfo& device_info,
      connection_handler::DeviceHandle device_id) OVERRIDE;

  void OnWebEngineDeviceCreated() OVERRIDE;

  void CreatePendingLocalApplication(const std::string& policy_app_id) OVERRIDE;

  void RemovePendingApplication(const std::string& policy_app_id) OVERRIDE;

  void SetPendingApplicationState(
      const transport_manager::ConnectionUID connection_id,
      const transport_manager::DeviceInfo& device_info);

  std::string PolicyIDByIconUrl(const std::string url) OVERRIDE;

  void SetIconFileFromSystemRequest(const std::string policy_id) OVERRIDE;

  /**
   * @brief Notifies the applicaiton manager that a cloud connection status has
   * updated and should trigger an UpdateAppList RPC to the HMI
   */
  void OnConnectionStatusUpdated();

  /**
   * @brief Retrieve the current connection status of a cloud app
   * @param app A cloud application
   * @return The current CloudConnectionStatus of app
   */
  hmi_apis::Common_CloudConnectionStatus::eType GetCloudAppConnectionStatus(
      ApplicationConstSharedPtr app) const;

  /*
   * @brief Returns unique correlation ID for to mobile request
   *
   * @return Unique correlation ID
   */
  uint32_t GetNextMobileCorrelationID() OVERRIDE;

  /*
   * @brief Returns unique correlation ID for HMI request
   *
   * @return Unique correlation ID
   */
  uint32_t GetNextHMICorrelationID() OVERRIDE;

  /**
   * @brief Starts AudioPassThru process by given application
   * @param app_id ID of the application which starts the process
   * @return true if AudioPassThru can be started, false otherwise
   */
  bool BeginAudioPassThru(uint32_t app_id) OVERRIDE;

  /**
   * @brief Finishes already started AudioPassThru process by given application
   * @param app_id ID of the application which started the process
   * @return true if AudioPassThru process has been started with given
   * application and thus it can be stopped, false otherwise
   */
  bool EndAudioPassThru(uint32_t app_id) OVERRIDE;

  /*
   * @brief Retrieves driver distraction state
   *
   * @return Current state of the distraction state
   */
  hmi_apis::Common_DriverDistractionState::eType driver_distraction_state()
      const;

  /*
   * @brief Sets state for driver distraction
   *
   * @param state New state to be set
   */
  void set_driver_distraction_state(
      const hmi_apis::Common_DriverDistractionState::eType state) OVERRIDE;

  /*
   * @brief Retrieves SDL access to all mobile apps
   *
   * @return Currently active state of the access
   */
  inline bool all_apps_allowed() const;

  /*
   * @brief Sets SDL access to all mobile apps
   *
   * @param allowed SDL access to all mobile apps
   */
  void SetAllAppsAllowed(const bool allowed) OVERRIDE;

  /**
   * @brief CreateRegularState create regular HMI state for application
   * @param app Application
   * @param window_type type of window
   * @param hmi_level of returned state
   * @param audio_state of returned state
   * @param system_context of returned state
   * @return new regular HMI state
   */
  HmiStatePtr CreateRegularState(
      std::shared_ptr<Application> app,
      const mobile_apis::WindowType::eType window_type,
      const mobile_apis::HMILevel::eType hmi_level,
      const mobile_apis::AudioStreamingState::eType audio_state,
      const mobile_apis::VideoStreamingState::eType video_state,
      const mobile_apis::SystemContext::eType system_context) const OVERRIDE;

  /**
   * @brief Checks, if given RPC is allowed at current HMI level for specific
   * application in policy table
   * @param app Application
   * @param window_id id of application's window
   * @param function_id FunctionID of RPC
   * @param params_permissions Permissions for RPC parameters (e.g.
   * SubscribeVehicleData) defined in policy table
   * @return SUCCESS, if allowed, otherwise result code of check
   */
  mobile_apis::Result::eType CheckPolicyPermissions(
      const ApplicationSharedPtr app,
      const WindowID window_id,
      const std::string& function_id,
      const RPCParams& rpc_params,
      CommandParametersPermissions* params_permissions = NULL) OVERRIDE;

  /**
   * @brief IsApplicationForbidden allows to distinguish if application is
   * not allowed to register, becuase of spaming.
   *
   * @param connection_key the conection key ofthe required application
   *
   * @param mobile_app_id application's mobile(policy) identifier.
   *
   * @return true in case application is allowed to register, false otherwise.
   */
  bool IsApplicationForbidden(uint32_t connection_key,
                              const std::string& mobile_app_id);

  /**
   * @brief Notification from PolicyHandler about PTU.
   * Compares AppHMIType between saved in app and received from PTU. If they are
   * different method sends:
   * UI_ChangeRegistration with list new AppHMIType;
   * ActivateApp with HMI level BACKGROUND;
   * OnHMIStatus notification;
   * for app with HMI level FULL or LIMITED.
   * method sends:
   * UI_ChangeRegistration with list new AppHMIType
   * for app with HMI level BACKGROUND.
   */
  void OnUpdateHMIAppType(
      std::map<std::string, std::vector<std::string> > app_hmi_types) OVERRIDE;

  /**
   * @brief OnPTUFinished is called on policy table update coming
   * @param ptu_result True if PTU is succeeded, otherwise - false
   */
  void OnPTUFinished(const bool ptu_result) FINAL;

#if defined(EXTERNAL_PROPRIETARY_MODE) && defined(ENABLE_SECURITY)
  /**
   * @brief OnCertDecryptFailed is called when certificate decryption fails in
   * external flow
   * @return since this callback is a part of SecurityManagerListener, bool
   * return value is used to indicate whether listener instance can be deleted
   * by calling entity. if true - listener can be deleted and removed from
   * listeners by SecurityManager, false - listener retains its place within
   * SecurityManager.
   */
  bool OnCertDecryptFailed() FINAL;

  /**
   * @brief OnCertDecryptFinished is called when certificate decryption is
   * finished in the external flow
   * @param decrypt_result bool value indicating whether decryption was
   * successful
   */
  void OnCertDecryptFinished(const bool decrypt_result) FINAL;
#endif

  /**
   * @brief OnPTUTimeoutExceeded is called on policy table update timed out
   */
  void OnPTUTimeoutExceeded() FINAL;

  /**
   *@brief ProcessServiceStatusUpdate callback that is invoked in case of
   *service status update
   *@param connection_key - connection key
   *@param service_type enum value containing type of service.
   *@param service_event enum value containing event that occured during service
   *start.
   *@param service_update_reason enum value containing reason why service_event
   *occured.
   **/
  void ProcessServiceStatusUpdate(
      const uint32_t connection_key,
      hmi_apis::Common_ServiceType::eType service_type,
      hmi_apis::Common_ServiceEvent::eType service_event,
      utils::Optional<hmi_apis::Common_ServiceStatusUpdateReason::eType>
          service_update_reason) FINAL;

#ifdef ENABLE_SECURITY
  bool OnPTUFailed() FINAL;
#endif  // ENABLE_SECURITY
  /*
   * @brief Starts audio pass thru thread
   *
   * @param session_key     Session key of connection for Mobile side
   * @param correlation_id  Correlation id for response for Mobile side
   * @param max_duration    Max duration of audio recording in milliseconds
   * @param sampling_rate   Value for rate(8, 16, 22, 44 kHz)
   * @param bits_per_sample The quality the audio is recorded.
   * @param audio_type      Type of audio data
   */
  void StartAudioPassThruThread(int32_t session_key,
                                int32_t correlation_id,
                                int32_t max_duration,
                                int32_t sampling_rate,
                                int32_t bits_per_sample,
                                int32_t audio_type) OVERRIDE;

  /*
   * @brief Terminates audio pass thru thread
   * @param application_key Id of application for which
   * audio pass thru should be stopped
   */
  void StopAudioPassThru(int32_t application_key) OVERRIDE;

  std::string GetDeviceName(connection_handler::DeviceHandle handle);

  /*
   * @brief Converts connection string transport type representation
   * to HMI Common_TransportType
   *
   * @param transport_type String representing connection type
   *
   * @return Corresponding HMI TransporType value
   */
  hmi_apis::Common_TransportType::eType GetDeviceTransportType(
      const std::string& transport_type);

  void set_hmi_message_handler(hmi_message_handler::HMIMessageHandler* handler);
  void set_connection_handler(connection_handler::ConnectionHandler* handler);
  void set_protocol_handler(protocol_handler::ProtocolHandler* handler);

  void StartDevicesDiscovery();

  void RemoveHMIFakeParameters(
      application_manager::commands::MessageSharedPtr& message,
      const hmi_apis::FunctionID::eType& function_id) OVERRIDE;

  /**
   * @brief TerminateRequest forces termination of request
   * @param connection_key - application id of request
   * @param corr_id correlation id of request
   * @param function_id function id of request
   */
  void TerminateRequest(const uint32_t connection_key,
                        const uint32_t corr_id,
                        const int32_t function_id) OVERRIDE;

  bool RetainRequestInstance(const uint32_t connection_key,
                             const uint32_t correlation_id) OVERRIDE;

  bool RemoveRetainedRequest(const uint32_t connection_key,
                             const uint32_t correlation_id) OVERRIDE;

  bool IsStillWaitingForResponse(const uint32_t connection_key,
                                 const uint32_t correlation_id) const OVERRIDE;

  void OnQueryAppsRequest(
      const connection_handler::DeviceHandle device) OVERRIDE;

  // Overriden ConnectionHandlerObserver method
  void OnDeviceListUpdated(
      const connection_handler::DeviceMap& device_list) OVERRIDE;
  void OnFindNewApplicationsRequest() OVERRIDE;
  void RemoveDevice(
      const connection_handler::DeviceHandle& device_handle) OVERRIDE;

  bool GetProtocolVehicleData(
      connection_handler::ProtocolVehicleData& data) OVERRIDE;

  /**
   * @brief OnDeviceSwitchingStart is invoked on device transport switching
   * start (e.g. from Bluetooth to USB) and creates waiting list of applications
   * expected to be re-registered after switching is complete
   * @param device_from device params being switched to the new transport
   * @param device_to device params on the new transport
   */
  void OnDeviceSwitchingStart(
      const connection_handler::Device& device_from,
      const connection_handler::Device& device_to) FINAL;

  /**
   * @brief OnDeviceSwitchingFinish is invoked on device trasport switching end
   * i.e. timeout for switching is expired, unregisters applications from
   * waiting list which haven't been re-registered and clears the waiting list
   * @param device_uid UID of device being switched
   */
  void OnDeviceSwitchingFinish(const std::string& device_uid) FINAL;

  void OnServiceStartedCallback(
      const connection_handler::DeviceHandle& device_handle,
      const int32_t& session_key,
      const protocol_handler::ServiceType& type,
      const BsonObject* params) OVERRIDE;
  void OnServiceEndedCallback(
      const int32_t& session_key,
      const protocol_handler::ServiceType& type,
      const connection_handler::CloseSessionReason& close_reason) OVERRIDE;
  void OnSecondaryTransportStartedCallback(
      const connection_handler::DeviceHandle device_handle,
      const int32_t session_key) OVERRIDE;
  void OnSecondaryTransportEndedCallback(const int32_t session_key) OVERRIDE;

  /**
   * @brief Check if application with specified app_id has NAVIGATION HMI type
   * @param app_id id of application to check
   * @return true if application is navi otherwise returns false
   */
  bool CheckAppIsNavi(const uint32_t app_id) const OVERRIDE;

#ifdef ENABLE_SECURITY
  /**
   * @brief Notification about protection result
   * @param connection_key Unique key of session which triggers handshake
   * @param result result of connection protection
   * @return true on success notification handling or false otherwise
   */
  bool OnHandshakeDone(
      uint32_t connection_key,
      security_manager::SSLContext::HandshakeResult result) OVERRIDE;

  /**
   * @brief Notification about handshake failure
   * @return true on success notification handling or false otherwise
   */
  bool OnGetSystemTimeFailed() OVERRIDE;

  /**
   * @brief Notification that certificate update is required.
   */
  void OnCertificateUpdateRequired() OVERRIDE;

  /**
   * @brief Get certificate data from policy
   * @param reference to string where to save certificate data
   * @return true if listener saved some data to string otherwise false
   */
  bool GetPolicyCertificateData(std::string& data) const OVERRIDE;

  /**
   * @brief Get unique handshake context by application id
   * @param key id of application
   * @return generated handshake context or empty context if application with
   * provided id does not exist
   */
  security_manager::SSLContext::HandshakeContext GetHandshakeContext(
      uint32_t key) const OVERRIDE;
#endif  // ENABLE_SECURITY

  /**
   * @ Add notification to collection
   *
   * @param ptr Reference to shared pointer that point on hmi notification
   */
  void AddNotification(const CommandSharedPtr ptr);

  /**
   * @ Add notification to collection
   *
   * @param notification Pointer that points to hmi notification
   */
  void RemoveNotification(const commands::Command* notification);

  /**
   * @ Updates request timeout
   *
   * @param connection_key Connection key of application
   * @param mobile_correlation_id Correlation ID of the mobile request
   * @param new_timeout_value New timeout in milliseconds to be set
   */
  void UpdateRequestTimeout(uint32_t connection_key,
                            uint32_t mobile_correlation_id,
                            uint32_t new_timeout_value) OVERRIDE;

  /**
   * @brief TODO
   *
   * @param connection_key Connection key of application
   * @param mobile_correlation_id Correlation ID of the mobile request
   */
  void IncreaseForwardedRequestTimeout(uint32_t connection_key,
                                       uint32_t mobile_correlation_id) OVERRIDE;

  /**
   * @brief AddPolicyObserver allows to subscribe needed component to events
   * from policy.
   *
   * @param listener the component to subscribe.
   */
  void AddPolicyObserver(PolicyHandlerObserver* listener);

  /**
   * @brief RemovePolicyObserver allows to remove observer from collection.
   *
   * @param listener observer to remove.
   */
  void RemovePolicyObserver(PolicyHandlerObserver* listener);

  /**
   * @brief Checks application HMI state and returns true if streaming is
   * allowed
   * @param app_id Application id
   * @param service_type Service type to check
   * @return True if streaming is allowed, false in other case
   */
  bool HMIStateAllowsStreaming(
      uint32_t app_id,
      protocol_handler::ServiceType service_type) const OVERRIDE;

  /**
   * @brief Checks if application can stream (streaming service is started and
   * streaming is enabled in application)
   * @param app_id Application id
   * @param service_type Service type to check
   * @return True if streaming is allowed, false in other case
   */
  bool CanAppStream(uint32_t app_id,
                    protocol_handler::ServiceType service_type) const OVERRIDE;

  /**
   * @brief Ends opened navi services audio and video for application
   * @param app_id Application id
   */
  void EndNaviServices(uint32_t app_id) OVERRIDE;

  /**
   * @brief Ends opened navi service audio or video for application
   * @param app_id Application id
   * @param service_type Service type to check
   */
  void EndService(const uint32_t app_id,
                  const protocol_handler::ServiceType service_type) OVERRIDE;

  void ForbidStreaming(uint32_t app_id,
                       protocol_handler::ServiceType service_type) OVERRIDE;

  void OnStreamingConfigurationSuccessful(
      uint32_t app_id, protocol_handler::ServiceType service_type) OVERRIDE;

  void OnStreamingConfigurationFailed(uint32_t app_id,
                                      std::vector<std::string>& rejected_params,
                                      const std::string& reason) OVERRIDE;

  void OnAppStreaming(uint32_t app_id,
                      protocol_handler::ServiceType service_type,
                      bool state) OVERRIDE;

  mobile_api::HMILevel::eType GetDefaultHmiLevel(
      ApplicationConstSharedPtr application) const;

  /**
   * @brief Checks if required transport for resumption is available
   *
   * The required transport can be configured through smartDeviceLink.ini file.
   *
   * @param application an instance of the app to check
   * @return true if the app is connected through one of the required
   *         transports, false otherwise
   */
  bool CheckResumptionRequiredTransportAvailable(
      ApplicationConstSharedPtr application) const;

  /**
   * Getter for resume_controller
   * @return Resume Controller
   */
  resumption::ResumeCtrl& resume_controller() OVERRIDE {
    return *resume_ctrl_.get();
  }

  HmiInterfaces& hmi_interfaces() OVERRIDE {
    return hmi_interfaces_;
  }

  /**
   * Generate grammar ID
   *
   * @return New grammar ID
   */
  uint32_t GenerateGrammarID() OVERRIDE;

  /**
   * Generate new HMI application ID
   *
   * @return New HMI application ID
   */
  uint32_t GenerateNewHMIAppID() OVERRIDE;

  /*
   * @brief Save binary data to specified directory
   *
   * @param binary data
   * @param path for saving data
   * @param file_name File name
   * @param offset for saving data to existing file with offset.
   *        If offset is 0 - create new file ( overrite existing )
   *
   *
   * @return SUCCESS if file was saved, other code otherwise
   */
  mobile_apis::Result::eType SaveBinary(const std::vector<uint8_t>& binary_data,
                                        const std::string& file_path,
                                        const std::string& file_name,
                                        const uint64_t offset) OVERRIDE;

  /**
   * @brief Get available app space
   * @param name of the app folder(make + mobile app id)
   * @return free app space.
   */
  uint32_t GetAvailableSpaceForApp(const std::string& folder_name);

  /*
   * @brief returns true if HMI is cooperating
   */
  bool IsHMICooperating() const OVERRIDE;

  void SetHMICooperating(const bool hmi_cooperating) OVERRIDE;
  /**
   * @brief Method used to send default app tts globalProperties
   * in case they were not provided from mobile side after defined time
   */
  void OnTimerSendTTSGlobalProperties();

  /**
   * @brief method adds application
   * to tts_global_properties_app_list_
   * @param app_id contains application which will
   * send TTS global properties after timeout
   */
  void AddAppToTTSGlobalPropertiesList(const uint32_t app_id) OVERRIDE;

  /**
   * @brief method removes application
   * from tts_global_properties_app_list_
   * @param app_id contains application which will
   * send TTS global properties after timeout
   */
  void RemoveAppFromTTSGlobalPropertiesList(const uint32_t app_id) OVERRIDE;

  ResetGlobalPropertiesResult ResetGlobalProperties(
      const smart_objects::SmartObject& global_properties_ids,
      const uint32_t app_id) OVERRIDE;

  ResetGlobalPropertiesResult ResetAllApplicationGlobalProperties(
      const uint32_t app_id) OVERRIDE;

  // TODO(AOleynik): Temporary added, to fix build. Should be reworked.
  connection_handler::ConnectionHandler& connection_handler() const OVERRIDE;
  protocol_handler::ProtocolHandler& protocol_handler() const OVERRIDE;

  policy::PolicyHandlerInterface& GetPolicyHandler() OVERRIDE {
    return *policy_handler_;
  }

  const policy::PolicyHandlerInterface& GetPolicyHandler() const OVERRIDE {
    return *policy_handler_;
  }

  rpc_service::RPCService& GetRPCService() const OVERRIDE {
    return *rpc_service_;
  }

  rpc_handler::RPCHandler& GetRPCHandler() const OVERRIDE {
    return *rpc_handler_;
  }

  request_controller::RequestTimeoutHandler& get_request_timeout_handler()
      const OVERRIDE {
    DCHECK(request_timeout_handler_);
    return *request_timeout_handler_;
  }

  request_controller::RequestController& get_request_controller()
      const OVERRIDE {
    DCHECK(request_ctrl_);
    return *request_ctrl_;
  }

  void SetRPCService(std::unique_ptr<rpc_service::RPCService>& rpc_service) {
    rpc_service_ = std::move(rpc_service);
  }

  bool is_audio_pass_thru_active() const OVERRIDE;
  /*
   * @brief Function Should be called when Low Voltage is occured
   */
  void OnLowVoltage();

  /*
   * @brief Function Should be called when WakeUp occures after Low Voltage
   */
  void OnWakeUp();

  /**
   * @brief IsApplicationForbidden allows to distinguish if application is
   * not allowed to register, because of spamming.
   *
   * @param connection_key the connection key ofthe required application
   *
   * @param policy_app_id application's mobile(policy) identifier.
   *
   * @return true in case application is allowed to register, false otherwise.
   */
  bool IsApplicationForbidden(uint32_t connection_key,
                              const std::string& policy_app_id) const OVERRIDE;

  policy::DeviceConsent GetUserConsentForDevice(
      const std::string& device_id) const OVERRIDE;

  // typedef for Applications list
  typedef std::set<std::string> ForbiddenApps;

  struct AppIdPredicate {
    uint32_t app_id_;
    AppIdPredicate(uint32_t app_id) : app_id_(app_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? app_id_ == app->app_id() : false;
    }
  };

  struct HmiAppIdPredicate {
    uint32_t hmi_app_id_;
    HmiAppIdPredicate(uint32_t hmi_app_id) : hmi_app_id_(hmi_app_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? hmi_app_id_ == app->hmi_app_id() : false;
    }
  };

  struct PolicyAppIdPredicate {
    std::string policy_app_id_;
    PolicyAppIdPredicate(const std::string& policy_app_id)
        : policy_app_id_(policy_app_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? policy_app_id_ == app->policy_app_id() : false;
    }
  };

  struct SubscribedToButtonPredicate {
    mobile_apis::ButtonName::eType button_;
    SubscribedToButtonPredicate(mobile_apis::ButtonName::eType button)
        : button_(button) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? app->IsSubscribedToButton(button_) : false;
    }
  };

  struct AppV4DevicePredicate {
    connection_handler::DeviceHandle handle_;
    AppV4DevicePredicate(const connection_handler::DeviceHandle handle)
        : handle_(handle) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? handle_ == app->device() &&
                       Message::is_sufficient_version(
                           protocol_handler::MajorProtocolVersion::
                               PROTOCOL_VERSION_4,
                           app->protocol_version())
                 : false;
    }
  };

  struct DevicePredicate {
    connection_handler::DeviceHandle handle_;
    DevicePredicate(const connection_handler::DeviceHandle handle)
        : handle_(handle) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return handle_ == app->device() ? true : false;
    }
  };

  struct GrammarIdPredicate {
    uint32_t grammar_id_;
    GrammarIdPredicate(uint32_t grammar_id) : grammar_id_(grammar_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? grammar_id_ == app->get_grammar_id() : false;
    }
  };

  struct AppNamePredicate {
    std::string app_name_;
    AppNamePredicate(const std::string& app_name) : app_name_(app_name) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? app->name() == app_name_ : false;
    }
  };

  /**
   * @brief Sends UpdateAppList notification to HMI
   */
  void SendUpdateAppList() OVERRIDE;

  /**
   * @brief Marks applications received through QueryApps as should be
   * greyed out on HMI
   * @param is_greyed_out, true, if should be greyed out, otherwise - false
   * @param handle, device handle
   */
  void MarkAppsGreyOut(const connection_handler::DeviceHandle handle,
                       bool is_greyed_out) OVERRIDE;

  ApplicationConstSharedPtr WaitingApplicationByID(
      const uint32_t hmi_id) const OVERRIDE;

  DataAccessor<AppsWaitRegistrationSet> AppsWaitingForRegistration()
      const OVERRIDE;

  /**
   * @brief Checks, if apps list had been queried already from certain device
   * @param handle, Device handle
   * @return true, if list had been queried already, otherwise - false
   */
  bool IsAppsQueriedFrom(
      const connection_handler::DeviceHandle handle) const OVERRIDE;

  /**
   * @brief IsAppInReconnectMode check if application belongs to session
   * affected by transport switching at the moment by checking internal
   * waiting list prepared on switching start
   * @param device_id device identifier
   * @param policy_app_id Application id
   * @return True if application is in the waiting list, otherwise - false
   */
  bool IsAppInReconnectMode(const connection_handler::DeviceHandle& device_id,
                            const std::string& policy_app_id) const FINAL;

  bool IsStopping() const OVERRIDE {
    return is_stopping_;
  }

  bool WaitForHmiIsReady() OVERRIDE;

  /**
   * @brief ProcessReconnection handles reconnection flow for application on
   * transport switch
   * @param application Pointer to switched application, must be validated
   * before passing
   * @param connection_key Connection key from registration request of
   * switched
   * application
   */
  void ProcessReconnection(ApplicationSharedPtr application,
                           const uint32_t connection_key) FINAL;

  /**
   * @brief Clears all applications' persistent data
   */
  void ClearAppsPersistentData();

  StateController& state_controller() OVERRIDE;
  const ApplicationManagerSettings& get_settings() const OVERRIDE;
  std::string GetCorrectMobileIDFromMessage(
      const commands::MessageSharedPtr& message) const OVERRIDE;
  virtual event_engine::EventDispatcher& event_dispatcher() OVERRIDE;

  app_launch::AppLaunchCtrl& app_launch_ctrl() OVERRIDE;

  bool IsSOStructValid(const hmi_apis::StructIdentifiers::eType struct_id,
                       const smart_objects::SmartObject& display_capabilities);

  virtual bool UnsubscribeAppFromSoftButtons(
      const commands::MessageSharedPtr response) OVERRIDE;

  /**
   * @brief Function returns supported SDL Protocol Version
   * @return protocol version depends on parameters from smartDeviceLink.ini.
   */
  protocol_handler::MajorProtocolVersion SupportedSDLVersion() const OVERRIDE;

  void ApplyFunctorForEachPlugin(
      std::function<void(plugin_manager::RPCPlugin&)> functor) OVERRIDE;

  ns_smart_device_link_rpc::V1::v4_protocol_v1_2_no_extra&
  mobile_v4_protocol_so_factory() OVERRIDE;

 private:
  /**
   * @brief Sets is_stopping flag to true
   */
  void InitiateStopping();

  /**
   * @brief Adds application to registered applications list and marks it as
   * registered
   * @param application Application that should be added to registered
   * applications list.
   */
  void AddAppToRegisteredAppList(const ApplicationSharedPtr application);

  /**
   * @brief Removes service status record for service that failed to start
   * @param app Application whose service status record should be removed
   * @param Service type which status record should be removed
   */
  bool HandleRejectedServiceStatus(
      ApplicationSharedPtr app,
      const hmi_apis::Common_ServiceType::eType service_type);
  /**
   * @brief PullLanguagesInfo allows to pull information about languages.
   *
   * @param app_data entry to parse
   *
   * @param ttsName tts name that should be filled.
   * @param vrSynonym vr synonymus that should be filled.
   */
  void PullLanguagesInfo(const smart_objects::SmartObject& app_data,
                         smart_objects::SmartObject& ttsName,
                         smart_objects::SmartObject& vrSynonym);

  /**
   * @brief Method compares arrays of app HMI type
   * @param from_policy contains app HMI type from policy
   * @param from_application contains app HMI type from application
   * @return return TRUE if arrays of appHMIType equal, otherwise return FALSE
   */
  bool CompareAppHMIType(const smart_objects::SmartObject& from_policy,
                         const smart_objects::SmartObject& from_application);

  hmi_apis::HMI_API& hmi_so_factory();
  mobile_apis::MOBILE_API& mobile_so_factory();

  bool ConvertSOtoMessage(const smart_objects::SmartObject& message,
                          Message& output,
                          const bool allow_unknown_parameters = false);

  template <typename ApplicationList>
  void PrepareApplicationListSO(ApplicationList& app_list,
                                smart_objects::SmartObject& applications,
                                ApplicationManager& app_mngr) {
    smart_objects::SmartArray* app_array = applications.asArray();
    uint32_t app_count = NULL == app_array ? 0 : app_array->size();
    typename ApplicationList::const_iterator it;
    for (it = app_list.begin(); it != app_list.end(); ++it) {
      if (it->use_count() == 0) {
        SDL_LOG_ERROR("Application not found");
        continue;
      }

      smart_objects::SmartObject hmi_application(smart_objects::SmartType_Map);
      const protocol_handler::SessionObserver& session_observer =
          connection_handler().get_session_observer();
      if (MessageHelper::CreateHMIApplicationStruct(*it,
                                                    session_observer,
                                                    GetPolicyHandler(),
                                                    &hmi_application,
                                                    app_mngr)) {
        applications[app_count++] = hmi_application;
      } else {
        SDL_LOG_DEBUG("Can't CreateHMIApplicationStruct");
      }
    }

    if (0 == app_count) {
      SDL_LOG_WARN("Empty applications list");
    }
  }

  void OnApplicationListUpdateTimer();

  /**
   * @brief CreateApplications creates aplpication adds it to application list
   * and prepare data for sending AppIcon request.
   *
   * @param obj_array applications array.
   *
   * @param connection_key connection key of app, which provided app list to
   * be created
   */
  void CreateApplications(smart_objects::SmartArray& obj_array,
                          const uint32_t connection_key);

  /*
   * @brief Function is called on IGN_OFF, Master_reset or Factory_defaults
   * to notify HMI that SDL is shutting down.
   */
  void SendOnSDLClose();

  /**
   * @brief returns true if low voltage state is active
   */
  bool IsLowVoltage() const OVERRIDE;

  /**
   * @brief Allows to process postponed commands for application
   * when its HMI level has been changed.
   * @param app_id the application id for processing.
   * @param from the old HMILevel.
   * @param to the new HMILevel for the certain app.
   */
  void ProcessPostponedMessages(const uint32_t app_id);

  /**
   * @brief Allows to process applications after HMILevel has been changed.
   * @param app_id the application id for processing.
   * @param from the old HMILevel.
   * @param to the new HMILevel for the certain app.
   */
  void ProcessApp(const uint32_t app_id,
                  const HmiStatePtr from,
                  const HmiStatePtr to);

  /**
   * @brief Starts EndStream timer for a specified application service type
   * @param app_id Application to process
   * @param service_type Type of service to track
   */
  void StartEndStreamTimer(const uint32_t app_id,
                           const protocol_handler::ServiceType service_type);

  /**
   * @brief Allows to send appropriate message to mobile device.
   * @param message The smart object which contains all neccesary info to send
   * notification.
   */
  void SendMobileMessage(smart_objects::SmartObjectSPtr message);

  /**
   * @brief Sets default value of the HELPPROMT global property
   * to the first vrCommand of the Command Menu registered in application
   *
   * @param app Registered application
   * @param is_timeout_promp Flag indicating that timeout prompt
   * should be reset
   *
   * @return TRUE on success, otherwise FALSE
   */
  bool ResetHelpPromt(ApplicationSharedPtr app) const;

  /**
   * @brief  Sets default value of the TIMEOUTPROMT global property
   * to the first vrCommand of the Command Menu registered in application
   *
   * @param app Registered application
   *
   * @return TRUE on success, otherwise FALSE
   */
  bool ResetTimeoutPromt(ApplicationSharedPtr app) const;

  /**
   * @brief Sets default value of the VRHELPTITLE global property
   * to the application name and value of the VRHELPITEMS global property
   * to value equal to registered command -1(default command “Help / Cancel”.)
   *
   * @param app Registered application
   *
   * @return TRUE on success, otherwise FALSE
   */
  bool ResetVrHelpTitleItems(ApplicationSharedPtr app) const;

 private:
  struct NaviServiceStatusDescriptor {
    bool is_video_service_active_;
    bool is_audio_service_active_;
  };

  struct NaviServiceDescriptor {
    uint32_t app_id_;
    protocol_handler::ServiceType service_type_;
    TimerSPtr timer_to_stop_service_;
  };

  typedef std::map<uint32_t, NaviServiceStatusDescriptor> NaviServiceStatusMap;
  typedef std::deque<NaviServiceDescriptor> NaviServicesDequeue;

  /**
   * @brief GetHashedAppID allows to obtain unique application id as a string.
   * It concatenates device mac and application id to obtain unique id.
   *
   * @param connection_key connection key for which need to obtain device mac;
   *
   * @param policy_app_id mobile(policy) application id on particular device.
   * This parameter will be concatenated with device id.
   *
   * @return unique aplication identifier.
   */
  std::string GetHashedAppID(uint32_t connection_key,
                             const std::string& policy_app_id) const;

  /**
   * @brief CreateAllAppGlobalPropsIDList creates an array of all application
   * global properties IDs. Used as utility to call
   * ApplicationManger::ResetGlobalProperties
   * with all global properties.
   * @return array smart object with global properties identifiers.
   */
  const smart_objects::SmartObjectSPtr CreateAllAppGlobalPropsIDList(
      const uint32_t app_id) const;

  /**
   * @brief Removes suspended and stopped timers from timer pool
   */
  void ClearTimerPool();

  /**
   * @brief CloseNaviApp allows to unregister application in case the
   * EndServiceEndedAck
   * didn't come for at least one of services(audio or video)
   */
  void CloseNaviApp();

  /**
   * @brief Suspends streaming ability of application in case application's HMI
   * level has been changed to not allowed for streaming
   */
  void EndStreaming();

  /**
   * @brief Starts specified navi service for application
   * @param app_id Application to proceed
   * @param service_type Type of service to start
   * @param params configuration parameters specified by mobile
   * @return True if service is immediately started or configuration
   * parameters are sent to HMI, false on other cases
   */
  bool StartNaviService(uint32_t app_id,
                        protocol_handler::ServiceType service_type,
                        const BsonObject* params);

  /**
   * @brief Stops specified navi service for application
   * @param app_id Application to proceed
   * @param service_type Type of service to stop
   */
  void StopNaviService(uint32_t app_id,
                       protocol_handler::ServiceType service_type);

  /**
   * @brief Allows streaming for application if it was disallowed by
   * DisallowStreaming()
   * @param app_id Application to proceed
   */
  void AllowStreaming(uint32_t app_id);

  /**
   * @brief Disallows streaming for application, but doesn't close
   * opened services. Streaming ability could be restored by AllowStreaming();
   * @param app_id Application to proceed
   * @param service_type Type of service to disallow
   */
  void DisallowStreaming(const uint32_t app_id,
                         const protocol_handler::ServiceType service_type);

  /**
   * @brief Types of directories used by Application Manager
   */
  enum DirectoryType { TYPE_STORAGE, TYPE_SYSTEM, TYPE_ICONS };

  typedef std::map<DirectoryType, std::string> DirectoryTypeMap;
  DirectoryTypeMap dir_type_to_string_map_;

  /**
   * @brief Converts directory type to string
   * @param type Directory type
   * @return Stringified type
   */
  const std::string DirectoryTypeToString(DirectoryType type) const;

  /**
   * @brief Creates directory path, if necessary
   * @param path Directory path
   * @param type Directory type
   * @return true, if succedeed, otherwise - false
   */
  bool InitDirectory(const std::string& path, DirectoryType type) const;

  /**
   * @brief Checks, whether r/w permissions are present for particular path
   * @param path Directory path
   * @param type Directory type
   * @return true, if allowed, otherwise - false
   */
  bool IsReadWriteAllowed(const std::string& path, DirectoryType type) const;

  /**
   * @brief Removes apps, waiting for registration related to
   * certain device handle
   * @param handle, Device handle
   */
  void RemoveAppsWaitingForRegistration(
      const connection_handler::DeviceHandle handle);

  void ClearTTSGlobalPropertiesList();

  /**
   * @brief EraseAppFromReconnectionList drops application from reconnection
   * list on transport switch success
   * @param app Pointer to application
   */
  void EraseAppFromReconnectionList(const ApplicationSharedPtr& app);

  /**
   * @brief SwitchApplication updates parameters of switched application and
   * internal applications list
   * @param app Pointer to switched application, must be validated before
   * passing in
   * @param connection_key Connection key of switched application from its
   * registration request
   * @param device_id Device id of switched application
   * @param mac_address New device mac address
   */
  void SwitchApplication(ApplicationSharedPtr app,
                         const uint32_t connection_key,
                         const size_t device_id,
                         const std::string& mac_address);

  /**
   * @brief Converts device handle to transport type string used in
   * smartDeviceLink.ini file, e.g. "TCP_WIFI"
   * @param device_handle A device handle
   * @return string representation of the transport of the device
   */
  const std::string GetTransportTypeProfileString(
      connection_handler::DeviceHandle device_handle) const;

  /**
   * @brief Converts BSON object containing video parameters to
   * smart object's map object
   * @param output the smart object to add video parameters
   * @param input BSON object to read parameters from
   */
  static void ConvertVideoParamsToSO(smart_objects::SmartObject& output,
                                     const BsonObject* input);

  /**
   * @brief Converts rejected parameters' names acquired from HMI to
   * SDL protocol's parameter names
   * @param list of rejected parameters' names
   * @return converted parameters' names
   */
  static std::vector<std::string> ConvertRejectedParamList(
      const std::vector<std::string>& input);

  void AddExpiredButtonRequest(
      const uint32_t app_id,
      const int32_t corr_id,
      const hmi_apis::Common_ButtonName::eType button_name) OVERRIDE;

  utils::Optional<ExpiredButtonRequestData> GetExpiredButtonRequestData(
      const int32_t corr_id) const OVERRIDE;

  void DeleteExpiredButtonRequest(const int32_t corr_id) OVERRIDE;

 private:
  const ApplicationManagerSettings& settings_;
  /**
   * @brief List of applications
   */
  ApplicationSet applications_;
  AppsWaitRegistrationSet apps_to_register_;
  ForbiddenApps forbidden_applications;
  ReregisterWaitList reregister_wait_list_;

  // Lock for applications list
  mutable std::shared_ptr<sync_primitives::RecursiveLock>
      applications_list_lock_ptr_;
  mutable std::shared_ptr<sync_primitives::Lock>
      apps_to_register_list_lock_ptr_;
  mutable std::shared_ptr<sync_primitives::Lock> reregister_wait_list_lock_ptr_;
  mutable sync_primitives::Lock subscribed_way_points_apps_lock_;

  /**
   * @brief Map of correlation id  and associated application id.
   */
  std::map<const int32_t, const uint32_t> appID_list_;

  /**
   * @brief Set AppIDs of subscribed apps for way points
   */
  std::set<uint32_t> subscribed_way_points_apps_list_;

  bool subscribed_to_hmi_way_points_;

  smart_objects::SmartObjectSPtr hmi_way_points_data_;

  std::map<uint32_t, smart_objects::SmartObject> mobile_way_points_data_;

  /**
   * @brief Map contains applications which
   * will send TTS global properties to HMI after timeout
   */
  std::map<uint32_t, date_time::TimeDuration> tts_global_properties_app_list_;
  std::set<connection_handler::DeviceHandle> query_apps_devices_;
  bool audio_pass_thru_active_;
  uint32_t audio_pass_thru_app_id_;
  sync_primitives::Lock audio_pass_thru_lock_;
  sync_primitives::Lock tts_global_properties_app_list_lock_;
  mutable sync_primitives::Lock query_apps_devices_lock_;
  hmi_apis::Common_DriverDistractionState::eType driver_distraction_state_;
  bool is_vr_session_strated_;
  bool hmi_cooperating_;
  bool is_all_apps_allowed_;
  uint32_t current_audio_source_;

  event_engine::EventDispatcherImpl event_dispatcher_;
  media_manager::MediaManager* media_manager_;

  hmi_message_handler::HMIMessageHandler* hmi_handler_;
  connection_handler::ConnectionHandler* connection_handler_;
  std::unique_ptr<policy::PolicyHandlerInterface> policy_handler_;
  protocol_handler::ProtocolHandler* protocol_handler_;
  std::unique_ptr<request_controller::RequestTimeoutHandler>
      request_timeout_handler_;
  std::unique_ptr<request_controller::RequestController> request_ctrl_;
  std::unique_ptr<plugin_manager::RPCPluginManager> plugin_manager_;
  std::unique_ptr<application_manager::AppServiceManager> app_service_manager_;

  /**
   * @brief Map contains apps with HMI state before incoming call
   * After incoming call ends previous HMI state must restore
   *
   */
  struct AppState {
    AppState(const mobile_apis::HMILevel::eType& level,
             const mobile_apis::AudioStreamingState::eType& streaming_state,
             const mobile_apis::SystemContext::eType& context)
        : hmi_level(level)
        , audio_streaming_state(streaming_state)
        , system_context(context) {}

    mobile_apis::HMILevel::eType hmi_level;
    mobile_apis::AudioStreamingState::eType audio_streaming_state;
    mobile_apis::SystemContext::eType system_context;
  };

  hmi_apis::HMI_API hmi_so_factory_;
  mobile_apis::MOBILE_API mobile_so_factory_;
  ns_smart_device_link_rpc::V1::v4_protocol_v1_2_no_extra
      mobile_v4_protocol_so_factory_;

  std::atomic<uint32_t> mobile_correlation_id_;
  std::atomic<uint32_t> correlation_id_;
  const uint32_t max_correlation_id_;

  std::unique_ptr<HMICapabilities> hmi_capabilities_;
  // The reason of HU shutdown
  mobile_api::AppInterfaceUnregisteredReason::eType unregister_reason_;

  /**
   * @brief Resume controler is responcible for save and load information
   * about persistent application data on disk, and save session ID for resuming
   * application in case INGITION_OFF or MASTER_RESSET
   */
  std::unique_ptr<resumption::ResumeCtrl> resume_ctrl_;

  HmiInterfacesImpl hmi_interfaces_;

  sync_primitives::Lock navi_service_status_lock_;
  NaviServiceStatusMap navi_service_status_;

  sync_primitives::Lock navi_app_to_stop_lock_;
  NaviServicesDequeue navi_app_to_stop_;

  sync_primitives::Lock navi_app_to_end_stream_lock_;
  NaviServicesDequeue navi_app_to_end_stream_;

  sync_primitives::Lock streaming_timer_pool_lock_;
  std::vector<TimerSPtr> streaming_timer_pool_;

  uint32_t navi_close_app_timeout_;
  uint32_t navi_end_stream_timeout_;

  mutable sync_primitives::Lock wait_for_hmi_lock_;
  sync_primitives::ConditionalVariable wait_for_hmi_condvar_;

  StateControllerImpl state_ctrl_;
  std::unique_ptr<app_launch::AppLaunchData> app_launch_dto_;
  std::unique_ptr<app_launch::AppLaunchCtrl> app_launch_ctrl_;

  // This is a cache to remember DeviceHandle of secondary transports. Only used
  // during RegisterApplication().
  typedef std::map<int32_t, connection_handler::DeviceHandle> DeviceMap;

  DeviceMap secondary_transport_devices_cache_;

  mutable std::shared_ptr<sync_primitives::RecursiveLock>
      pending_device_map_lock_ptr_;
  std::map<std::string, std::string> pending_device_map_;

  sync_primitives::Lock app_icon_map_lock_ptr_;
  std::map<std::string, AppIconInfo> app_icon_map_;

#ifdef TELEMETRY_MONITOR
  AMTelemetryObserver* metric_observer_;
#endif  // TELEMETRY_MONITOR

  Timer application_list_update_timer_;

  Timer tts_global_properties_timer_;

  Timer clear_pool_timer_;

  bool is_low_voltage_;

  uint32_t apps_size_;

  std::atomic<bool> registered_during_timer_execution_;

  std::atomic<bool> is_stopping_;

  std::unique_ptr<CommandHolder> commands_holder_;

  std::unique_ptr<rpc_service::RPCService> rpc_service_;
  std::unique_ptr<rpc_handler::RPCHandler> rpc_handler_;

  ServiceStreamingStatusMap streaming_application_services_;
  sync_primitives::Lock streaming_services_lock_;

  mutable sync_primitives::Lock expired_button_requests_lock_;
  mutable ExpiredButtonRequestsMap expired_button_requests_;

#ifdef BUILD_TESTS
 public:
  /**
   * @brief register a mock application without going through the formal
   * registration process. Only for unit testing.
   * @param mock_app the mock app to be registered
   */
  void AddMockApplication(ApplicationSharedPtr mock_app);

  /**
   * @brief Add a mock application to the pending application list without going
   * through the formal registration process. Only for unit testing.
   * @param mock_app the mock app to be added to the pending application list
   */
  void AddMockPendingApplication(ApplicationSharedPtr mock_app);

  /**
   * @brief set a mock media manager without running Init(). Only for unit
   * testing.
   * @param mock_media_manager the mock media manager to be assigned
   */
  void SetMockMediaManager(media_manager::MediaManager* mock_media_manager);

  /**
   * @brief set a mock rpc service directly. Only for unit
   * testing.
   * @param mock_app the mock rpc service to be assigned
   */
  void SetMockRPCService(rpc_service::RPCService* rpc_service) {
    rpc_service_.reset(rpc_service);
  }

  /**
   * @brief set a mock rpc service directly. Only for unit
   * testing.
   * @param mock_app the mock rpc service to be assigned
   */
  void SetMockPolicyHandler(policy::PolicyHandlerInterface* policy_handler) {
    policy_handler_.reset(policy_handler);
  }

  virtual void SetPluginManager(
      std::unique_ptr<plugin_manager::RPCPluginManager>& plugin_manager)
      OVERRIDE {
    plugin_manager_.reset(plugin_manager.release());
  }

  virtual void SetAppServiceManager(AppServiceManager* app_service_manager) {
    app_service_manager_.reset(app_service_manager);
  }

 private:
#endif

  DISALLOW_COPY_AND_ASSIGN(ApplicationManagerImpl);
};

inline bool ApplicationManagerImpl::all_apps_allowed() const {
  return is_all_apps_allowed_;
}

}  // namespace application_manager

#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_IMPL_H_