summaryrefslogtreecommitdiff
path: root/src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/mobile/register_app_interface_request.cc
blob: 20302be5859452266d73012a1249cdceacc88d2e (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
/*

 Copyright (c) 2018, 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.
 */

#include "sdl_rpc_plugin/commands/mobile/register_app_interface_request.h"

#include <unistd.h>
#include <algorithm>
#include <map>
#include <string.h>

#include <utils/make_shared.h>
#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/application_impl.h"
#include "application_manager/app_launch/app_launch_ctrl.h"
#include "application_manager/message_helper.h"
#include "application_manager/resumption/resume_ctrl.h"
#include "application_manager/policies/policy_handler.h"
#include "application_manager/helpers/application_helper.h"
#include "application_manager/rpc_service.h"
#include "config_profile/profile.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/generated_msg_version.h"
#include "utils/file_system.h"

namespace {
namespace custom_str = utils::custom_string;

mobile_apis::AppHMIType::eType StringToAppHMIType(const std::string& str) {
  if ("DEFAULT" == str) {
    return mobile_apis::AppHMIType::DEFAULT;
  } else if ("COMMUNICATION" == str) {
    return mobile_apis::AppHMIType::COMMUNICATION;
  } else if ("MEDIA" == str) {
    return mobile_apis::AppHMIType::MEDIA;
  } else if ("MESSAGING" == str) {
    return mobile_apis::AppHMIType::MESSAGING;
  } else if ("NAVIGATION" == str) {
    return mobile_apis::AppHMIType::NAVIGATION;
  } else if ("INFORMATION" == str) {
    return mobile_apis::AppHMIType::INFORMATION;
  } else if ("SOCIAL" == str) {
    return mobile_apis::AppHMIType::SOCIAL;
  } else if ("BACKGROUND_PROCESS" == str) {
    return mobile_apis::AppHMIType::BACKGROUND_PROCESS;
  } else if ("TESTING" == str) {
    return mobile_apis::AppHMIType::TESTING;
  } else if ("SYSTEM" == str) {
    return mobile_apis::AppHMIType::SYSTEM;
  } else if ("PROJECTION" == str) {
    return mobile_apis::AppHMIType::PROJECTION;
  } else if ("REMOTE_CONTROL" == str) {
    return mobile_apis::AppHMIType::REMOTE_CONTROL;
  } else {
    return mobile_apis::AppHMIType::INVALID_ENUM;
  }
}

std::string AppHMITypeToString(mobile_apis::AppHMIType::eType type) {
  const std::map<mobile_apis::AppHMIType::eType, std::string> app_hmi_type_map =
      {{mobile_apis::AppHMIType::DEFAULT, "DEFAULT"},
       {mobile_apis::AppHMIType::REMOTE_CONTROL, "REMOTE_CONTROL"},
       {mobile_apis::AppHMIType::COMMUNICATION, "COMMUNICATION"},
       {mobile_apis::AppHMIType::MEDIA, "MEDIA"},
       {mobile_apis::AppHMIType::MESSAGING, "MESSAGING"},
       {mobile_apis::AppHMIType::NAVIGATION, "NAVIGATION"},
       {mobile_apis::AppHMIType::INFORMATION, "INFORMATION"},
       {mobile_apis::AppHMIType::SOCIAL, "SOCIAL"},
       {mobile_apis::AppHMIType::BACKGROUND_PROCESS, "BACKGROUND_PROCESS"},
       {mobile_apis::AppHMIType::TESTING, "TESTING"},
       {mobile_apis::AppHMIType::SYSTEM, "SYSTEM"},
       {mobile_apis::AppHMIType::PROJECTION, "PROJECTION"}};

  std::map<mobile_apis::AppHMIType::eType, std::string>::const_iterator iter =
      app_hmi_type_map.find(type);

  return app_hmi_type_map.end() != iter ? iter->second : std::string("");
}

struct AppHMITypeInserter {
  AppHMITypeInserter(smart_objects::SmartObject& so_array)
      : index_(0), so_array_(so_array) {}

  bool operator()(const std::string& app_hmi_type) {
    so_array_[index_] = StringToAppHMIType(app_hmi_type);
    ++index_;
    return true;
  }

 private:
  uint32_t index_;
  smart_objects::SmartObject& so_array_;
};

struct CheckMissedTypes {
  CheckMissedTypes(const policy::StringArray& policy_app_types,
                   std::string& log)
      : policy_app_types_(policy_app_types), log_(log) {}

  bool operator()(const smart_objects::SmartArray::value_type& value) {
    std::string app_type_str = AppHMITypeToString(
        static_cast<mobile_apis::AppHMIType::eType>(value.asInt()));
    if (!app_type_str.empty()) {
      policy::StringArray::const_iterator it = policy_app_types_.begin();
      policy::StringArray::const_iterator it_end = policy_app_types_.end();
      for (; it != it_end; ++it) {
        if (app_type_str == *it) {
          return true;
        }
      }
    }

    log_ += app_type_str;
    log_ += ",";

    return true;
  }

 private:
  const policy::StringArray& policy_app_types_;
  std::string& log_;
};

class SmartArrayValueExtractor {
 public:
  AppHmiType operator()(const smart_objects::SmartObject& so) const {
    return static_cast<AppHmiType>(so.asInt());
  }
};

struct IsSameNickname {
  IsSameNickname(const custom_str::CustomString& app_id) : app_id_(app_id) {}
  bool operator()(const policy::StringArray::value_type& nickname) const {
    return app_id_.CompareIgnoreCase(nickname.c_str());
  }

 private:
  const custom_str::CustomString& app_id_;
};
}

namespace sdl_rpc_plugin {
using namespace application_manager;

namespace commands {

RegisterAppInterfaceRequest::RegisterAppInterfaceRequest(
    const application_manager::commands::MessageSharedPtr& message,
    ApplicationManager& application_manager,
    app_mngr::rpc_service::RPCService& rpc_service,
    app_mngr::HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handler)
    : CommandRequestImpl(message,
                         application_manager,
                         rpc_service,
                         hmi_capabilities,
                         policy_handler)
    , result_code_(mobile_apis::Result::INVALID_ENUM) {}

RegisterAppInterfaceRequest::~RegisterAppInterfaceRequest() {}

bool RegisterAppInterfaceRequest::Init() {
  LOG4CXX_AUTO_TRACE(logger_);
  return true;
}

void RegisterAppInterfaceRequest::Run() {
  using namespace helpers;
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "Connection key is " << connection_key());

  // Fix problem with SDL and HMI HTML. This problem is not actual for HMI PASA.
  // Flag conditional compilation specific to customer is used in order to
  // exclude hit code
  // to RTC
  // FIXME(EZamakhov): on shutdown - get freez

  // wait till HMI started
  while (!application_manager_.IsStopping() &&
         !application_manager_.IsHMICooperating()) {
    LOG4CXX_DEBUG(logger_,
                  "Waiting for the HMI... conn_key="
                      << connection_key()
                      << ", correlation_id=" << correlation_id()
                      << ", default_timeout=" << default_timeout()
                      << ", thread=" << pthread_self());
    application_manager_.updateRequestTimeout(
        connection_key(), correlation_id(), default_timeout());
    sleep(1);
    // TODO(DK): timer_->StartWait(1);
  }

  if (application_manager_.IsStopping()) {
    LOG4CXX_WARN(logger_, "The ApplicationManager is stopping!");
    return;
  }

  if (IsApplicationSwitched()) {
    return;
  }

  const std::string mobile_app_id =
      (*message_)[strings::msg_params][strings::app_id].asString();

  ApplicationSharedPtr application =
      application_manager_.application(connection_key());

  if (application) {
    SendResponse(false, mobile_apis::Result::APPLICATION_REGISTERED_ALREADY);
    return;
  }

  const smart_objects::SmartObject& msg_params =
      (*message_)[strings::msg_params];

  const std::string policy_app_id = msg_params[strings::app_id].asString();
  std::string new_policy_app_id = policy_app_id;
  std::transform(policy_app_id.begin(),
                 policy_app_id.end(),
                 new_policy_app_id.begin(),
                 ::tolower);
  (*message_)[strings::msg_params][strings::app_id] = new_policy_app_id;

  if (application_manager_.IsApplicationForbidden(connection_key(),
                                                  policy_app_id)) {
    SendResponse(false, mobile_apis::Result::TOO_MANY_PENDING_REQUESTS);
    return;
  }

  if (IsApplicationWithSameAppIdRegistered()) {
    SendResponse(false, mobile_apis::Result::DISALLOWED);
    return;
  }

  mobile_apis::Result::eType policy_result = CheckWithPolicyData();

  if (Compare<mobile_apis::Result::eType, NEQ, ALL>(
          policy_result,
          mobile_apis::Result::SUCCESS,
          mobile_apis::Result::WARNINGS)) {
    SendResponse(false, policy_result);
    return;
  }

  mobile_apis::Result::eType coincidence_result = CheckCoincidence();

  if (mobile_apis::Result::SUCCESS != coincidence_result) {
    LOG4CXX_ERROR(logger_, "Coincidence check failed.");
    if (mobile_apis::Result::DUPLICATE_NAME == coincidence_result) {
      usage_statistics::AppCounter count_of_rejections_duplicate_name(
          GetPolicyHandler().GetStatisticManager(),
          policy_app_id,
          usage_statistics::REJECTIONS_DUPLICATE_NAME);
      ++count_of_rejections_duplicate_name;
    }
    SendResponse(false, coincidence_result);
    return;
  }

  if (IsWhiteSpaceExist()) {
    LOG4CXX_INFO(logger_,
                 "Incoming register app interface has contains \t\n \\t \\n");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  application = application_manager_.RegisterApplication(message_);

  if (!application) {
    LOG4CXX_ERROR(logger_, "Application hasn't been registered!");
    return;
  }
  // For resuming application need to restore hmi_app_id from resumeCtrl
  resumption::ResumeCtrl& resumer = application_manager_.resume_controller();
  const std::string& device_mac = application->mac_address();

  // there is side affect with 2 mobile app with the same mobile app_id
  if (resumer.IsApplicationSaved(policy_app_id, device_mac)) {
    application->set_hmi_application_id(
        resumer.GetHMIApplicationID(policy_app_id, device_mac));
  } else {
    application->set_hmi_application_id(
        application_manager_.GenerateNewHMIAppID());
  }

  application->set_is_media_application(
      msg_params[strings::is_media_application].asBool());

  if (msg_params.keyExists(strings::vr_synonyms)) {
    application->set_vr_synonyms(msg_params[strings::vr_synonyms]);
  }

  if (msg_params.keyExists(strings::ngn_media_screen_app_name)) {
    application->set_ngn_media_screen_name(
        msg_params[strings::ngn_media_screen_app_name]);
  }

  if (msg_params.keyExists(strings::tts_name)) {
    smart_objects::SmartObject& tts_name =
        (*message_)[strings::msg_params][strings::tts_name];
    mobile_apis::Result::eType verification_result =
        MessageHelper::VerifyTtsFiles(
            tts_name, application, application_manager_);

    if (mobile_apis::Result::FILE_NOT_FOUND == verification_result) {
      LOG4CXX_WARN(logger_,
                   "MessageHelper::VerifyTtsFiles return "
                       << verification_result);
      response_info_ = "One or more files needed for tts_name are not present";
      result_code_ = mobile_apis::Result::WARNINGS;
    }
    application->set_tts_name(tts_name);
  }

  if (msg_params.keyExists(strings::app_hmi_type)) {
    application->set_app_types(msg_params[strings::app_hmi_type]);

    // check app type
    const smart_objects::SmartObject& app_type =
        msg_params.getElement(strings::app_hmi_type);

    for (size_t i = 0; i < app_type.length(); ++i) {
      mobile_apis::AppHMIType::eType current_app_type =
          static_cast<mobile_apis::AppHMIType::eType>(
              app_type.getElement(i).asUInt());

      switch (current_app_type) {
        case mobile_apis::AppHMIType::NAVIGATION: {
          application->set_is_navi(true);
          break;
        }
        case mobile_apis::AppHMIType::COMMUNICATION: {
          application->set_voice_communication_supported(true);
          break;
        }
        case mobile_apis::AppHMIType::PROJECTION: {
          application->set_mobile_projection_enabled(true);
          break;
        }
        case mobile_apis::AppHMIType::REMOTE_CONTROL: {
          application->set_remote_control_supported(true);
          break;
        }
        default: {}
      }
    }
  }

  if (msg_params.keyExists(strings::day_color_scheme)) {
    application->set_day_color_scheme(msg_params[strings::day_color_scheme]);
  }

  if (msg_params.keyExists(strings::night_color_scheme)) {
    application->set_night_color_scheme(
        msg_params[strings::night_color_scheme]);
  }

  // Add device to policy table and set device info, if any
  policy::DeviceParams dev_params;
  if (-1 ==
      application_manager_.connection_handler()
          .get_session_observer()
          .GetDataOnDeviceID(application->device(),
                             &dev_params.device_name,
                             NULL,
                             &dev_params.device_mac_address,
                             &dev_params.device_connection_type)) {
    LOG4CXX_ERROR(logger_,
                  "Failed to extract information for device "
                      << application->device());
  }
  policy::DeviceInfo device_info;
  device_info.AdoptDeviceType(dev_params.device_connection_type);
  if (msg_params.keyExists(strings::device_info)) {
    FillDeviceInfo(&device_info);
  }

  GetPolicyHandler().SetDeviceInfo(device_mac, device_info);

  SendRegisterAppInterfaceResponseToMobile(ApplicationType::kNewApplication);
  smart_objects::SmartObjectSPtr so =
      GetLockScreenIconUrlNotification(connection_key(), application);
  rpc_service_.ManageMobileCommand(so, SOURCE_SDL);
}

smart_objects::SmartObjectSPtr
RegisterAppInterfaceRequest::GetLockScreenIconUrlNotification(
    const uint32_t connection_key, ApplicationSharedPtr app) {
  DCHECK_OR_RETURN(app.get(), smart_objects::SmartObjectSPtr());
  smart_objects::SmartObjectSPtr message =
      utils::MakeShared<smart_objects::SmartObject>(
          smart_objects::SmartType_Map);
  (*message)[strings::params][strings::function_id] =
      mobile_apis::FunctionID::OnSystemRequestID;
  (*message)[strings::params][strings::connection_key] = connection_key;
  (*message)[strings::params][strings::message_type] =
      mobile_apis::messageType::notification;
  (*message)[strings::params][strings::protocol_type] = mobile_protocol_type_;
  (*message)[strings::params][strings::protocol_version] = protocol_version_;
  (*message)[strings::msg_params][strings::request_type] =
      mobile_apis::RequestType::LOCK_SCREEN_ICON_URL;
  (*message)[strings::msg_params][strings::url] =
      GetPolicyHandler().GetLockScreenIconUrl();
  return message;
}

void FillVRRelatedFields(smart_objects::SmartObject& response_params,
                         const HMICapabilities& hmi_capabilities) {
  response_params[strings::language] = hmi_capabilities.active_vr_language();
  if (hmi_capabilities.vr_capabilities()) {
    response_params[strings::vr_capabilities] =
        *hmi_capabilities.vr_capabilities();
  }
}

void FillVIRelatedFields(smart_objects::SmartObject& response_params,
                         const HMICapabilities& hmi_capabilities) {
  if (hmi_capabilities.vehicle_type()) {
    response_params[hmi_response::vehicle_type] =
        *hmi_capabilities.vehicle_type();
  }
}

void FillTTSRelatedFields(smart_objects::SmartObject& response_params,
                          const HMICapabilities& hmi_capabilities) {
  response_params[strings::language] = hmi_capabilities.active_tts_language();
  if (hmi_capabilities.speech_capabilities()) {
    response_params[strings::speech_capabilities] =
        *hmi_capabilities.speech_capabilities();
  }
  if (hmi_capabilities.prerecorded_speech()) {
    response_params[strings::prerecorded_speech] =
        *(hmi_capabilities.prerecorded_speech());
  }
}

void FillUIRelatedFields(smart_objects::SmartObject& response_params,
                         const HMICapabilities& hmi_capabilities) {
  response_params[strings::hmi_display_language] =
      hmi_capabilities.active_ui_language();
  if (hmi_capabilities.display_capabilities()) {
    response_params[hmi_response::display_capabilities] =
        smart_objects::SmartObject(smart_objects::SmartType_Map);

    smart_objects::SmartObject& display_caps =
        response_params[hmi_response::display_capabilities];

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::display_type)) {
      display_caps[hmi_response::display_type] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::display_type);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::display_name)) {
      display_caps[hmi_response::display_name] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::display_name);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::text_fields)) {
      display_caps[hmi_response::text_fields] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::text_fields);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::image_fields)) {
      display_caps[hmi_response::image_fields] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::image_fields);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::media_clock_formats)) {
      display_caps[hmi_response::media_clock_formats] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::media_clock_formats);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::templates_available)) {
      display_caps[hmi_response::templates_available] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::templates_available);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::screen_params)) {
      display_caps[hmi_response::screen_params] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::screen_params);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::num_custom_presets_available)) {
      display_caps[hmi_response::num_custom_presets_available] =
          hmi_capabilities.display_capabilities()->getElement(
              hmi_response::num_custom_presets_available);
    }

    if (hmi_capabilities.display_capabilities()->keyExists(
            hmi_response::image_capabilities)) {
      display_caps[hmi_response::graphic_supported] =
          (hmi_capabilities.display_capabilities()
               ->getElement(hmi_response::image_capabilities)
               .length() > 0);
    }
  }

  if (hmi_capabilities.audio_pass_thru_capabilities()) {
    if (smart_objects::SmartType_Array ==
        hmi_capabilities.audio_pass_thru_capabilities()->getType()) {
      // hmi_capabilities json contains array and HMI response object
      response_params[strings::audio_pass_thru_capabilities] =
          *hmi_capabilities.audio_pass_thru_capabilities();
    } else {
      response_params[strings::audio_pass_thru_capabilities][0] =
          *hmi_capabilities.audio_pass_thru_capabilities();
    }
  }
  response_params[strings::hmi_capabilities] =
      smart_objects::SmartObject(smart_objects::SmartType_Map);
  response_params[strings::hmi_capabilities][strings::navigation] =
      hmi_capabilities.navigation_supported();
  response_params[strings::hmi_capabilities][strings::phone_call] =
      hmi_capabilities.phone_call_supported();
  response_params[strings::hmi_capabilities][strings::video_streaming] =
      hmi_capabilities.video_streaming_supported();
  response_params[strings::hmi_capabilities][strings::remote_control] =
      hmi_capabilities.rc_supported();
}

void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile(
    ApplicationType app_type) {
  LOG4CXX_AUTO_TRACE(logger_);
  smart_objects::SmartObject response_params(smart_objects::SmartType_Map);

  mobile_apis::Result::eType result_code = mobile_apis::Result::SUCCESS;

  const HMICapabilities& hmi_capabilities = hmi_capabilities_;

  const uint32_t key = connection_key();
  ApplicationSharedPtr application = application_manager_.application(key);

  resumption::ResumeCtrl& resumer = application_manager_.resume_controller();

  if (!application) {
    LOG4CXX_ERROR(logger_,
                  "There is no application for such connection key" << key);
    LOG4CXX_DEBUG(logger_, "Need to start resume data persistent timer");
    resumer.OnAppRegistrationEnd();
    return;
  }

  response_params[strings::sync_msg_version][strings::major_version] =
      major_version;  // From generated file interfaces/generated_msg_version.h
  response_params[strings::sync_msg_version][strings::minor_version] =
      minor_version;  // From generated file interfaces/generated_msg_version.h
  response_params[strings::sync_msg_version][strings::patch_version] =
      patch_version;  // From generated file interfaces/generated_msg_version.h

  const smart_objects::SmartObject& msg_params =
      (*message_)[strings::msg_params];

  if (msg_params[strings::language_desired].asInt() !=
          hmi_capabilities.active_vr_language() ||
      msg_params[strings::hmi_display_language_desired].asInt() !=
          hmi_capabilities.active_ui_language()) {
    LOG4CXX_WARN(logger_,
                 "Wrong language on registering application "
                     << application->name().c_str());

    LOG4CXX_ERROR(
        logger_,
        "VR language desired code is "
            << msg_params[strings::language_desired].asInt()
            << " , active VR language code is "
            << hmi_capabilities.active_vr_language() << ", UI language code is "
            << msg_params[strings::hmi_display_language_desired].asInt()
            << " , active UI language code is "
            << hmi_capabilities.active_ui_language());

    result_code = mobile_apis::Result::WRONG_LANGUAGE;
  }

  if (HmiInterfaces::STATE_NOT_AVAILABLE !=
      application_manager_.hmi_interfaces().GetInterfaceState(
          HmiInterfaces::HMI_INTERFACE_TTS)) {
    FillTTSRelatedFields(response_params, hmi_capabilities);
  }

  if (HmiInterfaces::STATE_NOT_AVAILABLE !=
      application_manager_.hmi_interfaces().GetInterfaceState(
          HmiInterfaces::HMI_INTERFACE_VR)) {
    FillVRRelatedFields(response_params, hmi_capabilities);
  }

  if (HmiInterfaces::STATE_NOT_AVAILABLE !=
      application_manager_.hmi_interfaces().GetInterfaceState(
          HmiInterfaces::HMI_INTERFACE_UI)) {
    FillUIRelatedFields(response_params, hmi_capabilities);
  }

  if (HmiInterfaces::STATE_NOT_AVAILABLE !=
      application_manager_.hmi_interfaces().GetInterfaceState(
          HmiInterfaces::HMI_INTERFACE_VehicleInfo)) {
    FillVIRelatedFields(response_params, hmi_capabilities);
  }

  if (hmi_capabilities.button_capabilities()) {
    response_params[hmi_response::button_capabilities] =
        *hmi_capabilities.button_capabilities();
  }

  if (hmi_capabilities.soft_button_capabilities()) {
    response_params[hmi_response::soft_button_capabilities] =
        *hmi_capabilities.soft_button_capabilities();
  }

  if (hmi_capabilities.preset_bank_capabilities()) {
    response_params[hmi_response::preset_bank_capabilities] =
        *hmi_capabilities.preset_bank_capabilities();
  }

  if (hmi_capabilities.hmi_zone_capabilities()) {
    if (smart_objects::SmartType_Array ==
        hmi_capabilities.hmi_zone_capabilities()->getType()) {
      // hmi_capabilities json contains array and HMI response object
      response_params[hmi_response::hmi_zone_capabilities] =
          *hmi_capabilities.hmi_zone_capabilities();
    } else {
      response_params[hmi_response::hmi_zone_capabilities][0] =
          *hmi_capabilities.hmi_zone_capabilities();
    }
  }

  if (hmi_capabilities.pcm_stream_capabilities()) {
    response_params[strings::pcm_stream_capabilities] =
        *hmi_capabilities.pcm_stream_capabilities();
  }

  const std::vector<uint32_t>& diag_modes =
      application_manager_.get_settings().supported_diag_modes();
  if (!diag_modes.empty()) {
    std::vector<uint32_t>::const_iterator it = diag_modes.begin();
    uint32_t index = 0;
    for (; it != diag_modes.end(); ++it) {
      response_params[strings::supported_diag_modes][index] = *it;
      ++index;
    }
  }

  response_params[strings::sdl_version] =
      application_manager_.get_settings().sdl_version();
  const std::string ccpu_version = hmi_capabilities_.ccpu_version();
  if (!ccpu_version.empty()) {
    response_params[strings::system_software_version] = ccpu_version;
  }

  if (ApplicationType::kSwitchedApplicationWrongHashId == app_type) {
    LOG4CXX_DEBUG(logger_,
                  "Application has been switched from another transport, "
                  "but doesn't have correct hashID.");

    application_manager::DeleteApplicationData(application,
                                               application_manager_);

    SendResponse(
        true, mobile_apis::Result::RESUME_FAILED, NULL, &response_params);
    return;
  }

  if (ApplicationType::kSwitchedApplicationHashOk == app_type) {
    LOG4CXX_DEBUG(logger_,
                  "Application has been switched from another transport "
                  "and has correct hashID.");
    SendResponse(true, mobile_apis::Result::SUCCESS, NULL, &response_params);
    return;
  }

  bool resumption =
      (*message_)[strings::msg_params].keyExists(strings::hash_id);

  bool need_restore_vr = resumption;

  std::string hash_id;
  std::string add_info;
  if (resumption) {
    hash_id = (*message_)[strings::msg_params][strings::hash_id].asString();
    if (!resumer.CheckApplicationHash(application, hash_id)) {
      LOG4CXX_WARN(logger_,
                   "Hash from RAI does not match to saved resume data.");
      result_code = mobile_apis::Result::RESUME_FAILED;
      add_info = "Hash from RAI does not match to saved resume data.";
      need_restore_vr = false;
    } else if (!resumer.CheckPersistenceFilesForResumption(application)) {
      LOG4CXX_WARN(logger_, "Persistent data is missing.");
      result_code = mobile_apis::Result::RESUME_FAILED;
      add_info = "Persistent data is missing.";
      need_restore_vr = false;
    } else {
      add_info = "Resume succeeded.";
    }
  }
  if ((mobile_apis::Result::SUCCESS == result_code) &&
      (mobile_apis::Result::INVALID_ENUM != result_code_)) {
    add_info += response_info_;
    result_code = result_code_;
  }

  // in case application exist in resumption we need to send resumeVrgrammars
  if (false == resumption) {
    resumption = resumer.IsApplicationSaved(application->policy_app_id(),
                                            application->mac_address());
  }

  AppHmiTypes hmi_types;
  if ((*message_)[strings::msg_params].keyExists(strings::app_hmi_type)) {
    smart_objects::SmartArray* hmi_types_ptr =
        (*message_)[strings::msg_params][strings::app_hmi_type].asArray();
    DCHECK_OR_RETURN_VOID(hmi_types_ptr);
    SmartArrayValueExtractor extractor;
    if (hmi_types_ptr && 0 < hmi_types_ptr->size()) {
      std::transform(hmi_types_ptr->begin(),
                     hmi_types_ptr->end(),
                     std::back_inserter(hmi_types),
                     extractor);
    }
  }
  policy::StatusNotifier notify_upd_manager = GetPolicyHandler().AddApplication(
      application->policy_app_id(), hmi_types);

  response_params[strings::icon_resumed] =
      file_system::FileExists(application->app_icon_path());

  SendResponse(true, result_code, add_info.c_str(), &response_params);
  SendOnAppRegisteredNotificationToHMI(
      *(application.get()), resumption, need_restore_vr);
  if (msg_params.keyExists(strings::app_hmi_type)) {
    GetPolicyHandler().SetDefaultHmiTypes(application->policy_app_id(),
                                          &(msg_params[strings::app_hmi_type]));
  }

  // Default HMI level should be set before any permissions validation, since it
  // relies on HMI level.
  application_manager_.OnApplicationRegistered(application);
  (*notify_upd_manager)();

  // Start PTU after successfull registration
  // Sends OnPermissionChange notification to mobile right after RAI response
  // and HMI level set-up
  GetPolicyHandler().OnAppRegisteredOnMobile(application->policy_app_id());

  if (result_code != mobile_apis::Result::RESUME_FAILED) {
    resumer.StartResumption(application, hash_id);
  } else {
    resumer.StartResumptionOnlyHMILevel(application);
  }

  // By default app subscribed to CUSTOM_BUTTON
  SendSubscribeCustomButtonNotification();
  SendChangeRegistrationOnHMI(application);
}

DEPRECATED void
RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile() {
  SendRegisterAppInterfaceResponseToMobile(ApplicationType::kNewApplication);
}

void RegisterAppInterfaceRequest::SendChangeRegistration(
    const hmi_apis::FunctionID::eType function_id,
    const int32_t language,
    const uint32_t app_id) {
  using helpers::Compare;
  using helpers::EQ;
  using helpers::ONE;
  const HmiInterfaces& hmi_interfaces = application_manager_.hmi_interfaces();
  const HmiInterfaces::InterfaceID interface =
      hmi_interfaces.GetInterfaceFromFunction(function_id);
  if (hmi_interfaces.GetInterfaceState(interface) !=
      HmiInterfaces::STATE_NOT_AVAILABLE) {
    smart_objects::SmartObject msg_params(smart_objects::SmartType_Map);
    msg_params[strings::language] = language;
    msg_params[strings::app_id] = app_id;
    SendHMIRequest(function_id, &msg_params);
  } else {
    LOG4CXX_DEBUG(logger_, "Interface " << interface << "is not avaliable");
  }
}

void RegisterAppInterfaceRequest::SendChangeRegistrationOnHMI(
    ApplicationConstSharedPtr app) {
  using namespace hmi_apis::FunctionID;
  DCHECK_OR_RETURN_VOID(app);
  DCHECK_OR_RETURN_VOID(mobile_apis::Language::INVALID_ENUM != app->language());
  SendChangeRegistration(VR_ChangeRegistration, app->language(), app->app_id());
  SendChangeRegistration(
      TTS_ChangeRegistration, app->language(), app->app_id());
  SendChangeRegistration(UI_ChangeRegistration, app->language(), app->app_id());
}

void RegisterAppInterfaceRequest::SendOnAppRegisteredNotificationToHMI(
    const app_mngr::Application& application_impl,
    bool resumption,
    bool need_restore_vr) {
  using namespace smart_objects;
  SmartObjectSPtr notification = utils::MakeShared<SmartObject>(SmartType_Map);
  if (!notification) {
    LOG4CXX_ERROR(logger_, "Failed to create smart object");
    return;
  }

  (*notification)[strings::params] = SmartObject(SmartType_Map);
  smart_objects::SmartObject& params = (*notification)[strings::params];
  params[strings::function_id] = static_cast<int32_t>(
      hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
  params[strings::message_type] = static_cast<int32_t>(kNotification);
  params[strings::protocol_version] = protocol_version_;
  params[strings::protocol_type] = hmi_protocol_type_;

  (*notification)[strings::msg_params] = SmartObject(SmartType_Map);
  smart_objects::SmartObject& msg_params = (*notification)[strings::msg_params];
  // Due to current requirements in case when we're in resumption mode
  // we have to always send resumeVRGrammar field.
  if (resumption) {
    msg_params[strings::resume_vr_grammars] = need_restore_vr;
  }

  if (application_impl.vr_synonyms()) {
    msg_params[strings::vr_synonyms] = *(application_impl.vr_synonyms());
  }

  if (application_impl.tts_name()) {
    msg_params[strings::tts_name] = *(application_impl.tts_name());
  }

  const std::string policy_app_id = application_impl.policy_app_id();
  std::string priority;
  GetPolicyHandler().GetPriority(policy_app_id, &priority);

  if (!priority.empty()) {
    msg_params[strings::priority] = MessageHelper::GetPriorityCode(priority);
  }

  msg_params[strings::msg_params] = SmartObject(SmartType_Map);
  smart_objects::SmartObject& application = msg_params[strings::application];
  application[strings::app_name] = application_impl.name();
  application[strings::app_id] = application_impl.app_id();
  application[hmi_response::policy_app_id] = policy_app_id;
  if (file_system::FileExists(application_impl.app_icon_path())) {
    application[strings::icon] = application_impl.app_icon_path();
  }

  const smart_objects::SmartObject* ngn_media_screen_name =
      application_impl.ngn_media_screen_name();
  if (ngn_media_screen_name) {
    application[strings::ngn_media_screen_app_name] = *ngn_media_screen_name;
  }

  application[strings::hmi_display_language_desired] =
      static_cast<int32_t>(application_impl.ui_language());

  application[strings::is_media_application] =
      application_impl.is_media_application();

  const smart_objects::SmartObject* app_type = application_impl.app_types();
  if (app_type) {
    application[strings::app_type] = *app_type;
  }

  const policy::RequestType::State app_request_types_state =
      GetPolicyHandler().GetAppRequestTypeState(policy_app_id);
  if (policy::RequestType::State::AVAILABLE == app_request_types_state) {
    const auto request_types =
        GetPolicyHandler().GetAppRequestTypes(policy_app_id);
    application[strings::request_type] = SmartObject(SmartType_Array);
    smart_objects::SmartObject& request_types_array =
        application[strings::request_type];

    size_t index = 0;
    for (auto it : request_types) {
      request_types_array[index] = it;
      ++index;
    }
  } else if (policy::RequestType::State::EMPTY == app_request_types_state) {
    application[strings::request_type] = SmartObject(SmartType_Array);
  }

  const policy::RequestSubType::State app_request_subtypes_state =
      GetPolicyHandler().GetAppRequestSubTypeState(policy_app_id);
  if (policy::RequestSubType::State::AVAILABLE == app_request_subtypes_state) {
    const auto request_subtypes =
        GetPolicyHandler().GetAppRequestSubTypes(policy_app_id);
    application[strings::request_subtype] = SmartObject(SmartType_Array);
    smart_objects::SmartObject& request_subtypes_array =
        application[strings::request_subtype];

    size_t index = 0;
    for (auto it : request_subtypes) {
      request_subtypes_array[index] = it;
      ++index;
    }
  } else if (policy::RequestSubType::State::EMPTY ==
             app_request_subtypes_state) {
    application[strings::request_subtype] = SmartObject(SmartType_Array);
  }

  const protocol_handler::SessionObserver& session_observer =
      application_manager_.connection_handler().get_session_observer();

  application[strings::device_info] = SmartObject(SmartType_Map);
  smart_objects::SmartObject& device_info = application[strings::device_info];
  MessageHelper::CreateDeviceInfo(application_impl.device(),
                                  session_observer,
                                  GetPolicyHandler(),
                                  application_manager_,
                                  &device_info);

  if (application_impl.secondary_device() != 0) {
    application[strings::secondary_device_info] = SmartObject(SmartType_Map);
    smart_objects::SmartObject& secondary_device_info =
        application[strings::secondary_device_info];
    MessageHelper::CreateDeviceInfo(application_impl.secondary_device(),
                                    session_observer,
                                    GetPolicyHandler(),
                                    application_manager_,
                                    &secondary_device_info);
  }

  const smart_objects::SmartObject* day_color_scheme =
      application_impl.day_color_scheme();
  if (day_color_scheme) {
    application[strings::day_color_scheme] = *day_color_scheme;
  }

  const smart_objects::SmartObject* night_color_scheme =
      application_impl.night_color_scheme();
  if (night_color_scheme) {
    application[strings::night_color_scheme] = *night_color_scheme;
  }

  DCHECK(rpc_service_.ManageHMICommand(notification));
}

mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckCoincidence() {
  LOG4CXX_AUTO_TRACE(logger_);
  const smart_objects::SmartObject& msg_params =
      (*message_)[strings::msg_params];

  ApplicationSet accessor = application_manager_.applications().GetData();

  ApplicationSetConstIt it = accessor.begin();
  const custom_str::CustomString& app_name =
      msg_params[strings::app_name].asCustomString();

  for (; accessor.end() != it; ++it) {
    // name check
    const custom_str::CustomString& cur_name = (*it)->name();
    if (app_name.CompareIgnoreCase(cur_name)) {
      LOG4CXX_ERROR(logger_, "Application name is known already.");
      return mobile_apis::Result::DUPLICATE_NAME;
    }

    const smart_objects::SmartObject* vr = (*it)->vr_synonyms();
    const std::vector<smart_objects::SmartObject>* curr_vr = NULL;
    if (NULL != vr) {
      curr_vr = vr->asArray();
      CoincidencePredicateVR v(app_name);

      if (0 != std::count_if(curr_vr->begin(), curr_vr->end(), v)) {
        LOG4CXX_ERROR(logger_, "Application name is known already.");
        return mobile_apis::Result::DUPLICATE_NAME;
      }
    }

    // vr check
    if (msg_params.keyExists(strings::vr_synonyms)) {
      const std::vector<smart_objects::SmartObject>* new_vr =
          msg_params[strings::vr_synonyms].asArray();

      CoincidencePredicateVR v(cur_name);
      if (0 != std::count_if(new_vr->begin(), new_vr->end(), v)) {
        LOG4CXX_ERROR(logger_, "vr_synonyms duplicated with app_name .");
        return mobile_apis::Result::DUPLICATE_NAME;
      }
    }  // end vr check

  }  // application for end

  return mobile_apis::Result::SUCCESS;
}  // method end

mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
  LOG4CXX_AUTO_TRACE(logger_);
  // TODO(AOleynik): Check is necessary to allow register application in case
  // of disabled policy
  // Remove this check, when HMI will support policy
  if (!GetPolicyHandler().PolicyEnabled()) {
    return mobile_apis::Result::WARNINGS;
  }

  smart_objects::SmartObject& message = *message_;
  policy::StringArray app_nicknames;
  policy::StringArray app_hmi_types;

  const std::string mobile_app_id =
      message[strings::msg_params][strings::app_id].asString();
  const bool init_result = GetPolicyHandler().GetInitialAppData(
      mobile_app_id, &app_nicknames, &app_hmi_types);

  if (!init_result) {
    LOG4CXX_ERROR(logger_, "Error during initial application data check.");
    return mobile_apis::Result::INVALID_DATA;
  }

  if (!app_nicknames.empty()) {
    IsSameNickname compare(
        message[strings::msg_params][strings::app_name].asCustomString());
    policy::StringArray::const_iterator it =
        std::find_if(app_nicknames.begin(), app_nicknames.end(), compare);
    if (app_nicknames.end() == it) {
      LOG4CXX_WARN(logger_,
                   "Application name was not found in nicknames list.");
      // App should be unregistered, if its name is not present in nicknames
      // list
      usage_statistics::AppCounter count_of_rejections_nickname_mismatch(
          GetPolicyHandler().GetStatisticManager(),
          mobile_app_id,
          usage_statistics::REJECTIONS_NICKNAME_MISMATCH);
      ++count_of_rejections_nickname_mismatch;
      return mobile_apis::Result::DISALLOWED;
    }
  }

  mobile_apis::Result::eType result = mobile_apis::Result::SUCCESS;

  // If AppHMIType is not included in policy - allow any type
  if (!app_hmi_types.empty()) {
    if (message[strings::msg_params].keyExists(strings::app_hmi_type)) {
      // If AppHmiTypes are partially same, the system should allow those listed
      // in the policy table and send warning info on missed values
      smart_objects::SmartArray app_types =
          *(message[strings::msg_params][strings::app_hmi_type].asArray());

      std::string log;
      CheckMissedTypes checker(app_hmi_types, log);
      std::for_each(app_types.begin(), app_types.end(), checker);
      if (!log.empty()) {
        response_info_ =
            "Following AppHmiTypes are not present in policy "
            "table:" +
            log;
        result_code_ = mobile_apis::Result::WARNINGS;
      }
    }
    // Replace AppHmiTypes in request with values allowed by policy table
    message[strings::msg_params][strings::app_hmi_type] =
        smart_objects::SmartObject(smart_objects::SmartType_Array);

    smart_objects::SmartObject& app_hmi_type =
        message[strings::msg_params][strings::app_hmi_type];

    AppHMITypeInserter inserter(app_hmi_type);
    std::for_each(app_hmi_types.begin(), app_hmi_types.end(), inserter);
  }

  return result;
}

void RegisterAppInterfaceRequest::FillDeviceInfo(
    policy::DeviceInfo* device_info) {
  const std::string hardware = "hardware";
  const std::string firmware_rev = "firmwareRev";
  const std::string os = "os";
  const std::string os_ver = "osVersion";
  const std::string carrier = "carrier";
  const std::string max_number_rfcom_ports = "maxNumberRFCOMMPorts";

  const smart_objects::SmartObject& msg_params =
      (*message_)[strings::msg_params];

  const smart_objects::SmartObject& device_info_so =
      msg_params[strings::device_info];

  if (device_info_so.keyExists(hardware)) {
    device_info->hardware =
        msg_params[strings::device_info][hardware].asString();
  }
  if (device_info_so.keyExists(firmware_rev)) {
    device_info->firmware_rev =
        msg_params[strings::device_info][firmware_rev].asString();
  }
  if (device_info_so.keyExists(os)) {
    device_info->os = device_info_so[os].asString();
  }
  if (device_info_so.keyExists(os_ver)) {
    device_info->os_ver = device_info_so[os_ver].asString();
  }
  if (device_info_so.keyExists(carrier)) {
    device_info->carrier = device_info_so[carrier].asString();
  }
  if (device_info_so.keyExists(max_number_rfcom_ports)) {
    device_info->max_number_rfcom_ports =
        device_info_so[max_number_rfcom_ports].asInt();
  }
}

bool RegisterAppInterfaceRequest::IsApplicationWithSameAppIdRegistered() {
  LOG4CXX_AUTO_TRACE(logger_);

  const custom_string::CustomString mobile_app_id =
      (*message_)[strings::msg_params][strings::app_id].asCustomString();

  const ApplicationSet& applications =
      application_manager_.applications().GetData();

  ApplicationSetConstIt it = applications.begin();
  ApplicationSetConstIt it_end = applications.end();

  for (; it != it_end; ++it) {
    if (mobile_app_id.CompareIgnoreCase((*it)->policy_app_id().c_str())) {
      return true;
    }
  }

  return false;
}

bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
  LOG4CXX_AUTO_TRACE(logger_);
  const char* str = NULL;

  str = (*message_)[strings::msg_params][strings::app_name].asCharArray();
  if (!CheckSyntax(str)) {
    LOG4CXX_ERROR(logger_, "Invalid app_name syntax check failed");
    return true;
  }

  if ((*message_)[strings::msg_params].keyExists(strings::tts_name)) {
    const smart_objects::SmartArray* tn_array =
        (*message_)[strings::msg_params][strings::tts_name].asArray();

    smart_objects::SmartArray::const_iterator it_tn = tn_array->begin();
    smart_objects::SmartArray::const_iterator it_tn_end = tn_array->end();

    for (; it_tn != it_tn_end; ++it_tn) {
      str = (*it_tn)[strings::text].asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_, "Invalid tts_name syntax check failed");
        return true;
      }
    }
  }

  if ((*message_)[strings::msg_params].keyExists(
          strings::ngn_media_screen_app_name)) {
    str = (*message_)[strings::msg_params][strings::ngn_media_screen_app_name]
              .asCharArray();
    if (strlen(str) && !CheckSyntax(str)) {
      LOG4CXX_ERROR(logger_,
                    "Invalid ngn_media_screen_app_name syntax check failed");
      return true;
    }
  }

  if ((*message_)[strings::msg_params].keyExists(strings::vr_synonyms)) {
    const smart_objects::SmartArray* vs_array =
        (*message_)[strings::msg_params][strings::vr_synonyms].asArray();

    smart_objects::SmartArray::const_iterator it_vs = vs_array->begin();
    smart_objects::SmartArray::const_iterator it_vs_end = vs_array->end();

    for (; it_vs != it_vs_end; ++it_vs) {
      str = (*it_vs).asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_, "Invalid vr_synonyms syntax check failed");
        return true;
      }
    }
  }

  if ((*message_)[strings::msg_params].keyExists(strings::hash_id)) {
    str = (*message_)[strings::msg_params][strings::hash_id].asCharArray();
    if (!CheckSyntax(str)) {
      LOG4CXX_ERROR(logger_, "Invalid hash_id syntax check failed");
      return true;
    }
  }

  if ((*message_)[strings::msg_params].keyExists(strings::device_info)) {
    if ((*message_)[strings::msg_params][strings::device_info].keyExists(
            strings::hardware)) {
      str = (*message_)[strings::msg_params][strings::device_info]
                       [strings::hardware].asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_,
                      "Invalid device_info hardware syntax check failed");
        return true;
      }
    }

    if ((*message_)[strings::msg_params][strings::device_info].keyExists(
            strings::firmware_rev)) {
      str = (*message_)[strings::msg_params][strings::device_info]
                       [strings::firmware_rev].asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_,
                      "Invalid device_info firmware_rev syntax check failed");
        return true;
      }
    }

    if ((*message_)[strings::msg_params][strings::device_info].keyExists(
            strings::os)) {
      str = (*message_)[strings::msg_params][strings::device_info][strings::os]
                .asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_, "Invalid device_info os syntax check failed");
        return true;
      }
    }

    if ((*message_)[strings::msg_params][strings::device_info].keyExists(
            strings::os_version)) {
      str = (*message_)[strings::msg_params][strings::device_info]
                       [strings::os_version].asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_,
                      "Invalid device_info os_version syntax check failed");
        return true;
      }
    }

    if ((*message_)[strings::msg_params][strings::device_info].keyExists(
            strings::carrier)) {
      str = (*message_)[strings::msg_params][strings::device_info]
                       [strings::carrier].asCharArray();
      if (strlen(str) && !CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_,
                      "Invalid device_info carrier syntax check failed");
        return true;
      }
    }
  }

  if ((*message_)[strings::msg_params].keyExists(strings::app_id)) {
    str = (*message_)[strings::msg_params][strings::app_id].asCharArray();
    if (!CheckSyntax(str)) {
      LOG4CXX_ERROR(logger_, "Invalid app_id syntax check failed");
      return true;
    }
  }

  return false;
}

void RegisterAppInterfaceRequest::CheckResponseVehicleTypeParam(
    smart_objects::SmartObject& vehicle_type,
    const std::string& param,
    const std::string& backup_value) {
  using namespace hmi_response;
  if (!vehicle_type.keyExists(param) || vehicle_type[param].empty()) {
    if (!backup_value.empty()) {
      LOG4CXX_DEBUG(logger_,
                    param << " is missing."
                             "Will be replaced with policy table value.");
      vehicle_type[param] = backup_value;
    } else {
      vehicle_type.erase(param);
    }
  }
}

void RegisterAppInterfaceRequest::SendSubscribeCustomButtonNotification() {
  using namespace smart_objects;
  using namespace hmi_apis;

  SmartObject msg_params = SmartObject(SmartType_Map);
  msg_params[strings::app_id] = connection_key();
  msg_params[strings::name] = Common_ButtonName::CUSTOM_BUTTON;
  msg_params[strings::is_suscribed] = true;
  CreateHMINotification(FunctionID::Buttons_OnButtonSubscription, msg_params);
}

bool RegisterAppInterfaceRequest::IsApplicationSwitched() {
  const smart_objects::SmartObject& msg_params =
      (*message_)[strings::msg_params];

  const std::string& policy_app_id = msg_params[strings::app_id].asString();

  LOG4CXX_DEBUG(logger_, "Looking for application id " << policy_app_id);

  auto app = application_manager_.application_by_policy_id(policy_app_id);

  if (!app) {
    LOG4CXX_DEBUG(logger_,
                  "Application with policy id " << policy_app_id
                                                << " is not found.");
    return false;
  }

  LOG4CXX_DEBUG(logger_,
                "Application with policy id " << policy_app_id << " is found.");
  if (!application_manager_.IsAppInReconnectMode(policy_app_id)) {
    LOG4CXX_DEBUG(logger_,
                  "Policy id " << policy_app_id
                               << " is not found in reconnection list.");
    SendResponse(false, mobile_apis::Result::APPLICATION_REGISTERED_ALREADY);
    return false;
  }

  LOG4CXX_DEBUG(logger_, "Application is found in reconnection list.");

  auto app_type = ApplicationType::kSwitchedApplicationWrongHashId;
  if ((*message_)[strings::msg_params].keyExists(strings::hash_id)) {
    const auto hash_id =
        (*message_)[strings::msg_params][strings::hash_id].asString();

    auto& resume_ctrl = application_manager_.resume_controller();
    if (resume_ctrl.CheckApplicationHash(app, hash_id)) {
      app_type = ApplicationType::kSwitchedApplicationHashOk;
    }
  }

  application_manager_.ProcessReconnection(app, connection_key());
  SendRegisterAppInterfaceResponseToMobile(app_type);

  application_manager_.SendHMIStatusNotification(app);

  application_manager_.OnApplicationSwitched(app);

  return true;
}

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

}  // namespace commands

}  // namespace application_manager