summaryrefslogtreecommitdiffstats
path: root/demo3/common/agl-service-windowmanager/policy_manager/policy_manager.cpp
blob: 05f2ccbd5deb6c2a1a2702e67c5f12911299d1ae (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
/*
 * Copyright (c) 2018 TOYOTA MOTOR CORPORATION
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <fstream>
#include <sstream>
#include <istream>
#include <thread>
#include <map>
#include <algorithm>
#include <json-c/json.h>
#include "policy_manager.hpp"
#include "util.hpp"

extern "C"
{
#define AFB_BINDING_VERSION 2
#include <afb/afb-binding.h>
#include <systemd/sd-event.h>
#include "stm.h"
}

namespace pm
{
static const char kPathRolesConfigFile[] = "/etc/roles.json";
static const char kPathLayoutsConfigFile[] = "/etc/layouts.json";

static const int kInvisibleRoleHistoryNum = 5;

static PolicyManager *g_context;

static int transitionStateWrapper(sd_event_source *source, void *data)
{
    int ret = g_context->transitionState(source, data);
    return ret;
}

static int timerEventWrapper(sd_event_source *source, uint64_t usec, void *data)
{
    int ret = g_context->timerEvent(source, usec, data);
    return ret;
}

} // namespace pm

PolicyManager::PolicyManager()
    : eventname2no(),
      categoryname2no(),
      areaname2no(),
      role2category(),
      category2role(),
      category2areas()
{
    this->p_crr_state = new (StmState);
    this->p_prv_state = new (StmState);
}

PolicyManager::~PolicyManager()
{
    delete this->p_crr_state;
    delete this->p_prv_state;
}

int PolicyManager::initialize(std::string ecu_name)
{
    int ret = 0;

    // Set ECU name
    this->ecu_name = ecu_name;

    // Create convert map
    for (int i = StmEvtNoMin; i <= StmEvtNoMax; i++)
    {
        HMI_DEBUG("event name:%s no:%d", kStmEventName[i], i);
        this->eventname2no[kStmEventName[i]] = i;
    }

    for (int i = StmCtgNoMin; i <= StmCtgNoMax; i++)
    {
        HMI_DEBUG("category name:%s no:%d", kStmCategoryName[i], i);
        this->categoryname2no[kStmCategoryName[i]] = i;
    }

    for (int i = StmAreaNoMin; i <= StmAreaNoMax; i++)
    {
        HMI_DEBUG("area name:%s no:%d", kStmAreaName[i], i);
        this->areaname2no[kStmAreaName[i]] = i;
    }

    // Load roles config
    ret = this->loadRolesConfigFile();
    if (0 > ret)
    {
        HMI_ERROR("Load roles config file Error!!");
        return ret;
    }

    // Load layouts config
    ret = this->loadLayoutsConfigFile();
    if (0 > ret)
    {
        HMI_ERROR("Load layouts config file Error!!");
        return ret;
    }

    // Initialize state which is managed by PolicyManager
    this->initializeState();

    // Initialize StateTransitioner
    stmInitialize(ecu_name.c_str());

    // Store instance
    pm::g_context = this;

    return ret;
}

void PolicyManager::registerCallback(CallbackTable callback)
{
    this->callback.onStateTransitioned = callback.onStateTransitioned;
    this->callback.onError = callback.onError;
}

int PolicyManager::setInputEventData(json_object *json_in)
{
    // Check arguments
    if (nullptr == json_in)
    {
        HMI_ERROR("Argument is NULL!!");
        return -1;
    }

    // Get event from json_object
    const char *event = this->getStringFromJson(json_in, "event");
    int event_no = StmEvtNoNone;
    if (nullptr != event)
    {
        // Convert name to number
        auto itr = this->eventname2no.find(event);
        if (this->eventname2no.end() != itr)
        {
            event_no = this->eventname2no[event];
            HMI_DEBUG("event(%s:%d)", event, event_no);
        }
        else
        {
            HMI_ERROR("Invalid event name!!");
            return -1;
        }
    }
    else
    {
        HMI_ERROR("Event is not set!!");
        return -1;
    }

    // Get role from json_object
    const char *role = this->getStringFromJson(json_in, "role");
    std::string category = "";
    int category_no = StmCtgNoNone;
    if (nullptr != role)
    {
        HMI_DEBUG("role(%s)", role);

        // Convert role to category
        auto itr = this->role2category.find(role);
        if (this->role2category.end() != itr)
        {
            category = this->role2category[role];
        }
        else
        {
            itr = this->role2category.find("fallback");
            if (this->role2category.end() != itr)
            {
                HMI_DEBUG("Role:%s is not registered in roles config file, fallback as normal app", role);
                category = this->role2category["fallback"];
            }
        }

        if ("" != category)
        {
            // Convert name to number
            category_no = categoryname2no[category];
            HMI_DEBUG("category(%s:%d)", category.c_str(), category_no);
        }
    }
    if (StmCtgNoNone == category_no)
    {
        role = "";
    }

    // Get area from json_object
    const char *area = this->getStringFromJson(json_in, "area");
    int area_no = StmAreaNoNone;
    if ((nullptr != area) && (StmCtgNoNone != category_no))
    {
        for (const auto &x : this->category2areas[category])
        {
            if (x == std::string(area))
            {
                area_no = this->areaname2no[area];
                break;
            }
        }
        if (StmAreaNoNone == area_no)
        {
            area = this->category2areas[category].front().c_str();
            area_no = this->areaname2no[area];
        }
        HMI_DEBUG("area(%s:%d)", area, area_no);
    }

    // Set event info to the queue
    EventInfo event_info;
    int event_id = STM_CREATE_EVENT_ID(event_no, category_no, area_no);
    event_info.event = event_id;
    event_info.role = std::string(role);
    event_info.delay = 0;
    this->event_info_queue.push(event_info);

    return 0;
}

int PolicyManager::executeStateTransition()
{
    int ret;
    EventInfo event_info;

    // Get event info from queue and delete
    event_info = this->event_info_queue.front();
    this->event_info_queue.pop();

    // Set event info to check policy
    ret = this->setStateTransitionProcessToSystemd(event_info.event,
                                                   event_info.delay,
                                                   event_info.role);
    return ret;
}

void PolicyManager::undoState()
{
    HMI_DEBUG("Undo State !!!");

    // Undo state of STM
    stmUndoState();

    HMI_DEBUG(">>>>>>>>>> BEFORE UNDO");
    this->dumpLayerState(this->crr_layers);

    this->crr_layers = this->prv_layers;
    this->crr_invisible_role_history = this->prv_invisible_role_history;

    HMI_DEBUG(">>>>>>>>>> AFTER UNDO");
    this->dumpLayerState(this->crr_layers);
}

void PolicyManager::initializeState()
{
    this->initializeModeState();
    this->initializeLayerState();
}

void PolicyManager::initializeModeState()
{
    Mode init_car_ele;
    init_car_ele.state = "none";
    init_car_ele.changed = false;

    for (int i = StmCarElementNoMin; i <= StmCarElementNoMax; i++)
    {
        const char *car_ele_name = kStmCarElementName[i];
        this->crr_car_elements[car_ele_name] = init_car_ele;
    }

    this->prv_car_elements = this->crr_car_elements;
}

void PolicyManager::initializeLayerState()
{
    AreaState init_area;
    LayoutState init_layout;
    init_area.name = kStmAreaName[StmAreaNoNone];
    init_area.category = kStmCategoryName[StmCtgNoNone];
    init_area.role = "";
    init_layout.name = kStmLayoutName[StmLayoutNoNone];
    init_layout.area_list.push_back(init_area);

    for (int i = StmLayerNoMin; i <= StmLayerNoMax; i++)
    {
        const char *layer_name = kStmLayerName[i];
        this->crr_layers[layer_name].name = layer_name;
        this->crr_layers[layer_name].layout_state = init_layout;
        this->crr_layers[layer_name].changed = false;
    }

    this->prv_layers = this->crr_layers;
}

void PolicyManager::addStateToJson(const char *name, bool changed,
                                   std::string state, json_object **json_out)
{
    if ((nullptr == name) || (nullptr == json_out))
    {
        HMI_ERROR("Invalid argument!!!");
        return;
    }

    json_object_object_add(*json_out, "name", json_object_new_string(name));
    json_object_object_add(*json_out, "state", json_object_new_string(state.c_str()));
    json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
}

void PolicyManager::addStateToJson(const char *layer_name, bool changed,
                                   AreaList area_list, json_object **json_out)
{
    if ((nullptr == layer_name) || (nullptr == json_out))
    {
        HMI_ERROR("Invalid argument!!!");
        return;
    }

    json_object *json_areas = json_object_new_array();
    json_object *json_tmp;
    for (const auto &as : area_list)
    {
        json_tmp = json_object_new_object();
        json_object_object_add(json_tmp, "name", json_object_new_string(as.name.c_str()));
        json_object_object_add(json_tmp, "role", json_object_new_string(as.role.c_str()));
        json_object_array_add(json_areas, json_tmp);
    }

    json_object_object_add(*json_out, "name", json_object_new_string(layer_name));
    json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
    json_object_object_add(*json_out, "areas", json_areas);
}

void PolicyManager::updateState(int event_id)
{
    this->updateModeState();
    this->updateLayer(event_id);
}

void PolicyManager::updateModeState()
{
    int car_state_no;
    std::string car_state;
    bool changed;

    // Store previous layers
    this->prv_car_elements = this->crr_car_elements;

    // Update car elements
    HMI_DEBUG(">>> CAR ELEMENTS");
    for (int car_ele_no = StmCarElementNoMin;
         car_ele_no <= StmCarElementNoMax; car_ele_no++)
    {
        const char *car_ele_name = kStmCarElementName[car_ele_no];

        car_state_no = this->p_crr_state->car_element[car_ele_no].state;
        car_state = kStmCarElementStateNameList[car_ele_no][car_state_no];
        changed = (this->p_crr_state->car_element[car_ele_no].changed) ? true : false;

        this->crr_car_elements[car_ele_name].state = car_state;
        this->crr_car_elements[car_ele_name].changed = changed;

        HMI_DEBUG(">>> >>> NAME: %s", car_ele_name);
        HMI_DEBUG(">>> >>> >>> STATE:%s", car_state.c_str());
        HMI_DEBUG(">>> >>> >>> CHANGED:%s", (changed) ? "true" : "false");
    }
}

void PolicyManager::updateLayer(int event_id)
{
    for (int layer_no = StmLayerNoMin;
         layer_no <= StmLayerNoMax; layer_no++)
    {
        HMI_DEBUG(">>> LAYER:%s CHANGED:%d LAYOUT:%s",
                  kStmLayerName[layer_no], this->p_crr_state->layer[layer_no].changed,
                  kStmLayoutName[this->p_crr_state->layer[layer_no].state]);
    }

    // Store previous layers
    this->prv_layers = this->crr_layers;

    // Store previous role history
    this->prv_invisible_role_history = this->crr_invisible_role_history;

    // Update layers
    for (int layer_no = StmLayerNoMin;
         layer_no <= StmLayerNoMax; layer_no++)
    {
        const char *layer_name = kStmLayerName[layer_no];

        // If restriction mode is changed to mode2 on,
        // store current state for state of restriction mode off
        if (this->changedRestrictionModeTo2On() ||
            this->changedLightstatusBrakeOnToOff())
        {
            HMI_DEBUG("Store current state for state of restriction mode off");
            this->prv_layers_car_stop[layer_name] = this->crr_layers[layer_name];
        }

        // This layer is changed?
        int changed = this->p_crr_state->layer[layer_no].changed;
        if (changed)
        {
            HMI_DEBUG(">>>>>>>>>> Update layout of layer:%s", layer_name);

            // Get current layout name of this layer
            int crr_layout_state_no = this->p_crr_state->layer[layer_no].state;
            std::string crr_layout_name = std::string(kStmLayoutName[crr_layout_state_no]);

            LayoutState crr_layout_state;
            changed = this->updateLayout(event_id, layer_no,
                                         crr_layout_name, crr_layout_state);

            // Update current layout of this layer
            this->crr_layers[layer_name].layout_state = crr_layout_state;
        }
        else
        {
            int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
            std::string req_ctg = kStmCategoryName[category_no];
            std::string req_role = this->req_role_list[event_id];
            for (const auto &ctg : this->layer2categories[layer_name])
            {
                if (ctg == req_ctg)
                {
                    // If layer is not changed and requested role is in this layer,
                    // push requested role to history stack
                    // because the application which has this role have been started
                    HMI_DEBUG("Add requested role to history "
                              "because the application which has this role have been started");
                    this->pushInvisibleRoleHistory(req_ctg, req_role);
                }
            }
        }

        // Update changed flag
        this->crr_layers[layer_name].changed = (changed) ? true : false;
    }

    // Erase role for the event_id from list
    this->req_role_list.erase(event_id);

    HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (BEFORE)");
    this->dumpLayerState(this->prv_layers);

    HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (AFTER)");
    this->dumpLayerState(this->crr_layers);

    this->dumpInvisibleRoleHistory();
}

int PolicyManager::updateLayout(int event_id, int layer_no,
                                std::string crr_layout_name, LayoutState &crr_layout_state)
{
    int changed = 1;

    int event_no = STM_GET_EVENT_FROM_ID(event_id);
    int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
    int area_no = STM_GET_AREA_FROM_ID(event_id);

    std::string req_evt = kStmEventName[event_no];
    std::string req_ctg = kStmCategoryName[category_no];
    std::string req_area = kStmAreaName[area_no];
    std::string req_role = this->req_role_list[event_id];

    const char *layer_name = kStmLayerName[layer_no];

    // Get previous layout name of this layer
    LayoutState prv_layout_state = this->prv_layers[layer_name].layout_state;
    std::string prv_layout_name = prv_layout_state.name;

    if (this->changedRestrictionMode2OnToOther() ||
        this->changedLightstatusBrakeOffToOn())
    {
        // If restriction mode is changed from mode2 -> mode1,
        // restore state of restriction mode off
        HMI_DEBUG("Restriction mode is changed from mode2 -> mode1, so restore state of restriction mode off");
        crr_layout_state = this->prv_layers_car_stop[layer_name].layout_state;
        crr_layout_name = crr_layout_state.name;
        if ((prv_layout_name == crr_layout_name) &&
            (kStmAreaName[StmAreaNoNone] == crr_layout_name))
        {
            changed = 0;
        }
        else
        {
            // If the roles which is exist in previous layout is not in current,
            // push to role history
            for (const auto &prv_as : prv_layout_state.area_list)
            {
                for (const auto &crr_as : crr_layout_state.area_list)
                {
                    if (prv_as.role == crr_as.role)
                        break;
                }

                this->pushInvisibleRoleHistory(prv_as.category, prv_as.role);
            }
        }
    }
    else if ((prv_layout_name == crr_layout_name) &&
        (kStmLayoutName[StmLayoutNoNone] == crr_layout_name))
    {
        // If previous and current layout are none
        // Copy previous layout state for current
        crr_layout_state = prv_layout_state;
        changed = 0;
    }
    else
    {
        crr_layout_state = prv_layout_state;
        changed = 1;

        HMI_DEBUG("-- layout name previous:%s current:%s",
                  prv_layout_name.c_str(), crr_layout_name.c_str());
        if (prv_layout_name == crr_layout_name)
        {
            HMI_DEBUG("---- Previous layout is same with current");
        }
        else
        {
            // If previous layout is NOT same with current,
            // current areas is set with default value
            HMI_DEBUG("---- Previous layout is NOT same with current");
            crr_layout_state.name = this->default_layouts[crr_layout_name].name;
            crr_layout_state.category_num = this->default_layouts[crr_layout_name].category_num;
            crr_layout_state.area_list = this->default_layouts[crr_layout_name].area_list;
        }

        // Create candidate list
        std::map<std::string, AreaList> cand_list;
        // for (int ctg_no = StmCtgNoMin;
        //      ctg_no <= StmCtgNoMax; ctg_no++)
        // {
        for (const auto &ctg : this->layer2categories[layer_name])
        {
            // if (ctg_no == StmCtgNoNone)
            // {
            //     continue;
            // }

            // const char *ctg = kStmCategoryName[ctg_no];
            HMI_DEBUG("-- Create candidate list for ctg:%s", ctg.c_str());

            AreaList tmp_cand_list;
            int candidate_num = 0;
            int blank_num = crr_layout_state.category_num[ctg];

            // If requested event is "activate"
            // and there are requested category and area,
            // update area with requested role in current layout.
            bool request_for_this_layer = false;
            std::string used_role = "";
            if ((ctg == req_ctg) && ("activate" == req_evt))
            {
                HMI_DEBUG("---- Requested event is activate");
                for (AreaState &as : crr_layout_state.area_list)
                {
                    if (as.category == req_ctg)
                    {
                        request_for_this_layer = true;

                        if (as.name == req_area)
                        {
                            as.role = req_role;
                            used_role = req_role;
                            blank_num--;
                            HMI_DEBUG("------ Update current layout: area:%s category:%s role:%s",
                                      as.name.c_str(), as.category.c_str(), as.role.c_str());
                            break;
                        }
                    }
                }
            }

            // Create candidate list for category from the previous displayed categories
            for (AreaState area_state : prv_layout_state.area_list)
            {
                if ((ctg == area_state.category) &&
                    (used_role != area_state.role))
                {
                    // If there is the category
                    // which is same with new category and not used for updating yet,
                    // push it to list
                    HMI_DEBUG("---- Push previous(category:%s role:%s) to candidate list",
                              area_state.category.c_str(), area_state.role.c_str());
                    tmp_cand_list.push_back(area_state);
                    candidate_num++;
                }
            }

            // If NOT updated by requested area:
            // there is not requested area in new layout,
            // so push requested role to candidate list
            if (request_for_this_layer && ("" == used_role))
            {
                HMI_DEBUG("---- Push request(area:%s category:%s role:%s) to candidate list",
                          req_area.c_str(), req_ctg.c_str(), req_role.c_str());
                AreaState area_state;
                area_state.name = req_area;
                area_state.category = req_ctg;
                area_state.role = req_role;
                tmp_cand_list.push_back(area_state);
                candidate_num++;
            }

            HMI_DEBUG("---- blank_num:%d candidate_num:%d", blank_num, candidate_num);

            // Compare number of candidate/blank,
            // And remove role in order of the oldest as necessary
            if (candidate_num < blank_num)
            {
                // Refer history stack
                // and add to the top of tmp_cand_list in order to the newest
                while (candidate_num != blank_num)
                {
                    AreaState area_state;
                    area_state.name = kStmAreaName[StmAreaNoNone];
                    area_state.category = ctg;
                    area_state.role = this->popInvisibleRoleHistory(ctg);
                    if ("" == area_state.role)
                    {
                        HMI_ERROR("There is no role in history stack!!");
                    }
                    tmp_cand_list.push_back(area_state);
                    HMI_DEBUG("------ Add role:%s to candidate list",
                              area_state.role.c_str());
                    candidate_num++;
                }
            }
            else if (candidate_num > blank_num)
            {
                // Remove the oldest role from candidate list
                while (candidate_num != blank_num)
                {
                    std::string removed_role = tmp_cand_list.begin()->role;
                    HMI_DEBUG("------ Remove the oldest role:%s from candidate list",
                              removed_role.c_str());
                    tmp_cand_list.erase(tmp_cand_list.begin());
                    candidate_num--;

                    // Push removed data to history stack
                    this->pushInvisibleRoleHistory(ctg, removed_role);

                    // Remove from current layout
                    for (AreaState &as : crr_layout_state.area_list)
                    {
                        if (as.role == removed_role)
                        {
                            as.role = "";
                        }
                    }
                }
            }
            else
            { // (candidate_num == blank_num)
                // nop
            }

            cand_list[ctg] = tmp_cand_list;
        }

        // Update areas
        HMI_DEBUG("-- Update areas by using candidate list");
        for (AreaState &as : crr_layout_state.area_list)
        {
            HMI_DEBUG("---- Check area:%s category:%s role:%s",
                      as.name.c_str(), as.category.c_str(), as.role.c_str());
            if ("" == as.role)
            {
                HMI_DEBUG("------ Update this area with role:%s",
                          cand_list[as.category].begin()->role.c_str());
                as.role = cand_list[as.category].begin()->role;
                cand_list[as.category].erase(cand_list[as.category].begin());
            }
        }
    }
    return changed;
}

void PolicyManager::createOutputInformation(json_object **json_out)
{
    json_object *json_tmp;

    // Create car element information
    // {
    //     "car_elements": [
    //     {
    //         "parking_brake": {
    //             "changed": <bool>,
    //             "state": <const char*>
    //         },
    //         ...
    //     },
    json_object *json_car_ele = json_object_new_array();
    const char *car_ele_name;
    for (int car_ele_no = StmCarElementNoMin;
         car_ele_no <= StmCarElementNoMax; car_ele_no++)
    {
        car_ele_name = kStmCarElementName[car_ele_no];
        json_tmp = json_object_new_object();
        this->addStateToJson(car_ele_name,
                             this->crr_car_elements[car_ele_name].changed,
                             this->crr_car_elements[car_ele_name].state,
                             &json_tmp);
        json_object_array_add(json_car_ele, json_tmp);
    }
    json_object_object_add(*json_out, "car_elements", json_car_ele);

    // Create layout information
    //
    //     "layers": [
    //     {
    //         "homescreen": {
    //             "changed": <bool>,
    //             "areas": [
    //             {
    //                 "name":<const char*>,
    //                 "role":<const char*>
    //             }.
    //             ...
    //             ]
    //         }
    //     },
    //     ...
    json_object *json_layer = json_object_new_array();
    const char *layer_name;
    for (int layer_no = StmLayerNoMin;
         layer_no <= StmLayerNoMax; layer_no++)
    {
        layer_name = kStmLayerName[layer_no];
        json_tmp = json_object_new_object();
        this->addStateToJson(layer_name,
                             this->crr_layers[layer_name].changed,
                             this->crr_layers[layer_name].layout_state.area_list,
                             &json_tmp);
        json_object_array_add(json_layer, json_tmp);
    }
    json_object_object_add(*json_out, "layers", json_layer);
}

void PolicyManager::controlTimerEvent()
{
    if (this->p_crr_state->car_element[StmCarElementNoRunning].changed)
    {
        if (StmRunningNoRun == this->p_crr_state->car_element[StmCarElementNoRunning].state)
        {
            // Set delay event(restriction mode on)
            this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOn,
                                                     3000, "");
        }
        else if (StmRunningNoStop ==
                 this->p_crr_state->car_element[StmCarElementNoRunning].state)
        {
            // Stop timer for restriction on event
            if (this->event_source_list.find(StmEvtNoRestrictionModeOn) !=
                this->event_source_list.end())
            {
                HMI_DEBUG("Stop timer for restriction on");
                sd_event_source *event_source = this->event_source_list[StmEvtNoRestrictionModeOn];
                int ret = sd_event_source_set_enabled(event_source, SD_EVENT_OFF);
                if (0 > ret)
                {
                    HMI_ERROR("Failed to stop timer");
                }
            }

            // Set event(restriction mode off)
            this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOff, 0, "");
        }
    }
}

int PolicyManager::transitionState(sd_event_source *source, void *data)
{
    HMI_DEBUG(">>>>>>>>>> START STATE TRANSITION");

    int event_id = *((int *)data);

    int event_no, category_no, area_no;
    event_no = STM_GET_EVENT_FROM_ID(event_id);
    category_no = STM_GET_CATEGORY_FROM_ID(event_id);
    area_no = STM_GET_AREA_FROM_ID(event_id);
    HMI_DEBUG(">>>>>>>>>> EVENT:%s CATEGORY:%s AREA:%s",
              kStmEventName[event_no],
              kStmCategoryName[category_no],
              kStmAreaName[area_no]);

    // Store current state
    *(this->p_prv_state) = *(this->p_crr_state);

    // Transition state
    int ret = stmTransitionState(event_id, this->p_crr_state);
    if (0 > ret)
    {
        HMI_ERROR("Failed transition state");
        if (nullptr != this->callback.onError)
        {
            json_object *json_out = json_object_new_object();
            json_object_object_add(json_out, "message",
                                   json_object_new_string("Failed to transition state"));
            json_object_object_add(json_out, "event",
                                   json_object_new_string(kStmEventName[event_no]));
            json_object_object_add(json_out, "role",
                                   json_object_new_string(this->req_role_list[event_id].c_str()));
            json_object_object_add(json_out, "area",
                                   json_object_new_string(kStmAreaName[area_no]));
            this->callback.onError(json_out);
            json_object_put(json_out);
        }
        return -1;
    }

    // Update state which is managed by PolicyManager
    this->updateState(event_id);

    // Create output information for ResourceManager
    json_object *json_out = json_object_new_object();
    this->createOutputInformation(&json_out);

    // Notify changed state
    if (nullptr != this->callback.onStateTransitioned)
    {
        this->callback.onStateTransitioned(json_out);
    }

    // Start/Stop timer events
    this->controlTimerEvent();

    // Release json_object
    json_object_put(json_out);

    // Release data
    delete (int *)data;

    // Destroy sd_event_source object
    sd_event_source_unref(source);

    // Remove event source from list
    if (this->event_source_list.find(event_id) != this->event_source_list.end())
    {
        this->event_source_list.erase(event_id);
    }

    HMI_DEBUG(">>>>>>>>>> FINISH STATE TRANSITION");
    return 0;
}

int PolicyManager::timerEvent(sd_event_source *source, uint64_t usec, void *data)
{
    HMI_DEBUG("Call");

    int ret = this->transitionState(source, data);
    return ret;
}

int PolicyManager::setStateTransitionProcessToSystemd(int event_id, uint64_t delay_ms, std::string role)
{
    struct sd_event_source *event_source;
    HMI_DEBUG("event_id:0x%x delay:%d role:%s", event_id, delay_ms, role.c_str());

    if (0 == delay_ms)
    {
        int ret = sd_event_add_defer(afb_daemon_get_event_loop(), &event_source,
                                     &pm::transitionStateWrapper, new int(event_id));
        if (0 > ret)
        {
            HMI_ERROR("Faild to sd_event_add_defer: errno:%d", ret);
            return -1;
        }
    }
    else
    {
        // Get current time
        struct timespec time_spec;
        clock_gettime(CLOCK_BOOTTIME, &time_spec);

        // Calculate timer fired time
        uint64_t usec = (time_spec.tv_sec * 1000000) + (time_spec.tv_nsec / 1000) + (delay_ms * 1000);

        // Set timer
        int ret = sd_event_add_time(afb_daemon_get_event_loop(), &event_source,
                                    CLOCK_BOOTTIME, usec, 1,
                                    &pm::timerEventWrapper, new int(event_id));
        if (0 > ret)
        {
            HMI_ERROR("Faild to sd_event_add_time: errno:%d", ret);
            return -1;
        }
    }
    // Store event source
    this->event_source_list[event_id] = event_source;
    // Store requested role
    this->req_role_list[event_id] = role;
    return 0;
}

bool PolicyManager::changedRestrictionModeTo2On()
{
    // TODO: If possible thie process should be include in zipc stm in the future
    if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
        (StmRestrictionModeSttNoOn != this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
        (StmRestrictionModeSttNoOn == this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
    {
        return true;
    }
    return false;
}

bool PolicyManager::changedRestrictionMode2OnToOther()
{
    // TODO: If possible thie process should be include in zipc stm in the future
    if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
        (StmRestrictionModeSttNoOn == this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
        (StmRestrictionModeSttNoOn != this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
    {
        return true;
    }
    return false;
}

bool PolicyManager::changedLightstatusBrakeOffToOn()
{
    // TODO: For master
    //       If possible thie process should be include in zipc stm in the future
    if (("master" == this->ecu_name) &&
        this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
        (StmLightstatusBrakeSttNoOff == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
        (StmLightstatusBrakeSttNoOn  == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
    {
        return true;
    }
    return false;
}

bool PolicyManager::changedLightstatusBrakeOnToOff()
{
    // TODO: For master
    //       If possible thie process should be include in zipc stm in the future
    if (("master" == this->ecu_name) &&
        this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
        (StmLightstatusBrakeSttNoOn == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
        (StmLightstatusBrakeSttNoOff  == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
    {
        return true;
    }
    return false;
}

int PolicyManager::loadRolesConfigFile()
{
    std::string file_name;

    // Get afm application installed dir
    char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
    HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);

    if (!afm_app_install_dir)
    {
        HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
    }
    else
    {
        file_name = std::string(afm_app_install_dir) + std::string(pm::kPathRolesConfigFile);
    }

    // Load roles config file
    json_object *json_obj;
    int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
    if (0 > ret)
    {
        HMI_ERROR("Could not open %s, so use default role information", pm::kPathRolesConfigFile);
        json_obj = json_tokener_parse(kDefaultRolesConfig);
    }
    HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));

    // Parse ecus
    json_object *json_cfg;
    if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
    {
        HMI_ERROR("Parse Error!!");
        return -1;
    }

    int num_ecu = json_object_array_length(json_cfg);
    HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);

    const char* c_ecu_name;
    json_object *json_ecu;
    for (int i = 0; i < num_ecu; i++)
    {
        json_ecu= json_object_array_get_idx(json_cfg, i);

        c_ecu_name = this->getStringFromJson(json_ecu, "name");
        if (nullptr == c_ecu_name)
        {
            HMI_ERROR("Parse Error!!");
            return -1;
        }

        if (std::string(c_ecu_name) == this->ecu_name)
        {
            break;
        }
        else
        {
            json_ecu = nullptr;
        }
    }

    if (!json_ecu)
    {
        HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
        return -1;
    }

    // Parse roles
    json_object *json_roles;
    if (!json_object_object_get_ex(json_ecu, "roles", &json_roles))
    {
        HMI_ERROR("Parse Error!!");
        return -1;
    }

    int len = json_object_array_length(json_roles);
    HMI_DEBUG("json_cfg len:%d", len);
    HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_roles));

    json_object *json_tmp;
    const char *category;
    const char *roles;
    const char *areas;
    const char *layer;
    for (int i = 0; i < len; i++)
    {
        json_tmp = json_object_array_get_idx(json_roles, i);

        category = this->getStringFromJson(json_tmp, "category");
        roles = this->getStringFromJson(json_tmp, "role");
        areas = this->getStringFromJson(json_tmp, "area");
        layer = this->getStringFromJson(json_tmp, "layer");

        if ((nullptr == category) || (nullptr == roles) ||
            (nullptr == areas) || (nullptr == layer))
        {
            HMI_ERROR("Parse Error!!");
            return -1;
        }

        // Parse roles by '|'
        std::vector<std::string> vct_roles;
        vct_roles = this->parseString(std::string(roles), '|');

        // Parse areas by '|'
        Areas vct_areas;
        vct_areas = this->parseString(std::string(areas), '|');

        // Set role, category, areas
        for (auto itr = vct_roles.begin(); itr != vct_roles.end(); ++itr)
        {
            this->role2category[*itr] = std::string(category);
        }
        this->category2role[category] = std::string(roles);
        this->category2areas[category] = vct_areas;
        this->layer2categories[layer].push_back(category);
    }

    // Check
    HMI_DEBUG("Check role2category");
    for (const auto &x : this->role2category)
    {
        HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
    }

    HMI_DEBUG("Check category2role");
    for (const auto &x : this->category2role)
    {
        HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
    }

    HMI_DEBUG("Check category2areas");
    for (const auto &x : this->category2areas)
    {
        for (const auto &y : x.second)
        {
            HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
        }
    }

    HMI_DEBUG("Check layer2categories");
    for (const auto &x : this->layer2categories)
    {
        for (const auto &y : x.second)
        {
            HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
        }
    }
    return 0;
}

int PolicyManager::loadLayoutsConfigFile()
{
    HMI_DEBUG("Call");

    // Get afm application installed dir
    char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
    HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);

    std::string file_name;
    if (!afm_app_install_dir)
    {
        HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
    }
    else
    {
        file_name = std::string(afm_app_install_dir) + std::string(pm::kPathLayoutsConfigFile);
    }

    // Load states config file
    json_object *json_obj;
    int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
    if (0 > ret)
    {
        HMI_DEBUG("Could not open %s, so use default layout information", pm::kPathLayoutsConfigFile);
        json_obj = json_tokener_parse(kDefaultLayoutsConfig);
    }
    HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));

    // Parse ecus
    json_object *json_cfg;
    if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
    {
        HMI_ERROR("Parse Error!!");
        return -1;
    }

    int num_ecu = json_object_array_length(json_cfg);
    HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);

    const char* c_ecu_name;
    json_object *json_ecu;
    for (int i = 0; i < num_ecu; i++)
    {
        json_ecu= json_object_array_get_idx(json_cfg, i);

        c_ecu_name = this->getStringFromJson(json_ecu, "name");
        if (nullptr == c_ecu_name)
        {
            HMI_ERROR("Parse Error!!");
            return -1;
        }

        if (std::string(c_ecu_name) == this->ecu_name)
        {
            break;
        }
        else
        {
            json_ecu = nullptr;
        }
    }

    if (!json_ecu)
    {
        HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
        return -1;
    }

    // Perse layouts
    HMI_DEBUG("Perse layouts");
    json_object *json_layouts;
    if (!json_object_object_get_ex(json_ecu, "layouts", &json_layouts))
    {
        HMI_ERROR("Parse Error!!");
        return -1;
    }

    int len = json_object_array_length(json_layouts);
    HMI_DEBUG("json_layouts len:%d", len);
    HMI_DEBUG("json_layouts dump:%s", json_object_get_string(json_layouts));

    const char *layout;
    const char *role;
    const char *category;
    for (int i = 0; i < len; i++)
    {
        json_object *json_tmp = json_object_array_get_idx(json_layouts, i);

        layout = this->getStringFromJson(json_tmp, "name");
        if (nullptr == layout)
        {
            HMI_ERROR("Parse Error!!");
            return -1;
        }
        HMI_DEBUG("> layout:%s", layout);

        json_object *json_area_array;
        if (!json_object_object_get_ex(json_tmp, "areas", &json_area_array))
        {
            HMI_ERROR("Parse Error!!");
            return -1;
        }

        int len_area = json_object_array_length(json_area_array);
        HMI_DEBUG("json_area_array len:%d", len_area);
        HMI_DEBUG("json_area_array dump:%s", json_object_get_string(json_area_array));

        LayoutState layout_state;
        AreaState area_state;
        std::map<std::string, int> category_num;
        for (int ctg_no = StmCtgNoMin;
             ctg_no <= StmCtgNoMax; ctg_no++)
        {
            const char *ctg_name = kStmCategoryName[ctg_no];
            category_num[ctg_name] = 0;
        }

        for (int j = 0; j < len_area; j++)
        {
            json_object *json_area = json_object_array_get_idx(json_area_array, j);

            // Get area name
            const char *area = this->getStringFromJson(json_area, "name");
            if (nullptr == area)
            {
                HMI_ERROR("Parse Error!!");
                return -1;
            }
            area_state.name = std::string(area);
            HMI_DEBUG(">> area:%s", area);

            // Get app attribute of the area
            category = this->getStringFromJson(json_area, "category");
            if (nullptr == category)
            {
                HMI_ERROR("Parse Error!!");
                return -1;
            }
            area_state.category = std::string(category);
            category_num[category]++;
            HMI_DEBUG(">>> category:%s", category);

            role = this->getStringFromJson(json_area, "role");
            if (nullptr != role)
            {
                // Role is NOT essential here
                area_state.role = std::string(role);
            }
            else
            {
                area_state.role = std::string("");
            }
            HMI_DEBUG(">>> role:%s", role);

            layout_state.area_list.push_back(area_state);
        }

        layout_state.name = layout;
        layout_state.category_num = category_num;
        this->default_layouts[layout] = layout_state;
    }

    // initialize for none layout
    LayoutState none_layout_state;
    memset(&none_layout_state, 0, sizeof(none_layout_state));
    none_layout_state.name = "none";
    this->default_layouts["none"] = none_layout_state;

    // Check
    for (auto itr_layout = this->default_layouts.begin();
         itr_layout != this->default_layouts.end(); ++itr_layout)
    {
        HMI_DEBUG(">>> layout:%s", itr_layout->first.c_str());

        for (auto itr_area = itr_layout->second.area_list.begin();
             itr_area != itr_layout->second.area_list.end(); ++itr_area)
        {
            HMI_DEBUG(">>> >>> area    :%s", itr_area->name.c_str());
            HMI_DEBUG(">>> >>> category:%s", itr_area->category.c_str());
            HMI_DEBUG(">>> >>> role    :%s", itr_area->role.c_str());
        }
    }

    // Release json_object
    json_object_put(json_obj);

    return 0;
}

void PolicyManager::pushInvisibleRoleHistory(std::string category, std::string role)
{
    auto i = std::remove_if(this->crr_invisible_role_history[category].begin(),
                            this->crr_invisible_role_history[category].end(),
                            [role](std::string x) { return (role == x); });

    if (this->crr_invisible_role_history[category].end() != i)
    {
        this->crr_invisible_role_history[category].erase(i);
    }

    this->crr_invisible_role_history[category].push_back(role);

    if (pm::kInvisibleRoleHistoryNum < crr_invisible_role_history[category].size())
    {
        this->crr_invisible_role_history[category].erase(
            this->crr_invisible_role_history[category].begin());
    }
}

std::string PolicyManager::popInvisibleRoleHistory(std::string category)
{
    std::string role;
    if (crr_invisible_role_history[category].empty())
    {
        role = "";
    }
    else
    {
        role = this->crr_invisible_role_history[category].back();
        this->crr_invisible_role_history[category].pop_back();
    }
    return role;
}

const char *PolicyManager::getStringFromJson(json_object *obj, const char *key)
{
    json_object *tmp;
    if (!json_object_object_get_ex(obj, key, &tmp))
    {
        HMI_DEBUG("Not found key \"%s\"", key);
        return nullptr;
    }

    return json_object_get_string(tmp);
}

int PolicyManager::inputJsonFilie(const char *file, json_object **obj)
{
    const int input_size = 128;
    int ret = -1;

    HMI_DEBUG("Input file: %s", file);

    // Open json file
    FILE *fp = fopen(file, "rb");
    if (nullptr == fp)
    {
        HMI_ERROR("Could not open file");
        return ret;
    }

    // Parse file data
    struct json_tokener *tokener = json_tokener_new();
    enum json_tokener_error json_error;
    char buffer[input_size];
    int block_cnt = 1;
    while (1)
    {
        size_t len = fread(buffer, sizeof(char), input_size, fp);
        *obj = json_tokener_parse_ex(tokener, buffer, len);
        if (nullptr != *obj)
        {
            HMI_DEBUG("File input is success");
            ret = 0;
            break;
        }

        json_error = json_tokener_get_error(tokener);
        if ((json_tokener_continue != json_error) || (input_size > len))
        {
            HMI_ERROR("Failed to parse file (byte:%d err:%s)",
                      (input_size * block_cnt), json_tokener_error_desc(json_error));
            HMI_ERROR("\n%s", buffer);
            *obj = nullptr;
            break;
        }
        block_cnt++;
    }

    // Close json file
    fclose(fp);

    // Free json_tokener
    json_tokener_free(tokener);

    return ret;
}

void PolicyManager::dumpLayerState(std::unordered_map<std::string, LayerState> &layers)
{
    HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
    HMI_DEBUG("|%-15s|%s|%-20s|%-20s|%-20s|%-20s|",
              "LAYER", "C", "LAYOUT", "AREA", "CATEGORY", "ROLE");
    for (const auto &itr : layers)
    {
        LayerState ls = itr.second;
        const char* layer   = ls.name.c_str();
        const char* changed = (ls.changed) ? "T" : "f";
        const char* layout  = ls.layout_state.name.c_str();
        bool first = true;
        for (const auto &as : ls.layout_state.area_list)
        {
            if (first)
            {
                first = false;
                HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
                          layer, changed, layout,
                          as.name.c_str(), as.category.c_str(), as.role.c_str());
            }
            else
                HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
                          "", "", "", as.name.c_str(), as.category.c_str(), as.role.c_str());
        }
    }
    HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
}

void PolicyManager::dumpInvisibleRoleHistory()
{
    HMI_DEBUG(">>>>>>>>>> DUMP INVISIBLE ROLE HISTORY ( category [older > newer] )");
    for (int ctg_no = StmCtgNoMin; ctg_no <= StmCtgNoMax; ctg_no++)
    {
        if (ctg_no == StmCtgNoNone)
            continue;

        std::string category = std::string(kStmCategoryName[ctg_no]);

        std::string str = category + " [ ";
        for (const auto &i : this->crr_invisible_role_history[category])
            str += (i + " > ");

        str += "]";
        HMI_DEBUG("%s", str.c_str());
    }
}

std::vector<std::string> PolicyManager::parseString(std::string str, char delimiter)
{
    // Parse string by delimiter
    std::vector<std::string> vct;
    std::stringstream ss{str};
    std::string buf;
    while (std::getline(ss, buf, delimiter))
    {
        if (!buf.empty())
        {
            // Delete space and push back to vector
            vct.push_back(this->deleteSpace(buf));
        }
    }
    return vct;
}

std::string PolicyManager::deleteSpace(std::string str)
{
    std::string ret = str;
    size_t pos;
    while ((pos = ret.find_first_of(" ")) != std::string::npos)
    {
        ret.erase(pos, 1);
    }
    return ret;
}

const char *PolicyManager::kDefaultRolesConfig = "{ \
    \"roles\":[ \
    { \
        \"category\": \"homescreen\", \
        \"role\": \"homescreen\", \
        \"area\": \"fullscreen\", \
    }, \
    { \
        \"category\": \"map\", \
        \"role\": \"map\", \
        \"area\": \"normal.full | split.main\", \
    }, \
    { \
        \"category\": \"general\", \
        \"role\": \"launcher | poi | browser | sdl | mixer | radio | hvac | debug | phone | video | music\", \
        \"area\": \"normal.full\", \
    }, \
    { \
        \"category\": \"system\", \
        \"role\": \"settings | dashboard\", \
        \"area\": \"normal.full\", \
    }, \
    { \
        \"category\": \"software_keyboard\", \
        \"role\": \"software_keyboard\", \
        \"area\": \"software_keyboard\", \
    }, \
    { \
        \"category\": \"restriction\", \
        \"role\": \"restriction\", \
        \"area\": \"restriction.normal | restriction.split.main | restriction.split.sub\", \
    }, \
    { \
        \"category\": \"pop_up\", \
        \"role\": \"pop_up\", \
        \"area\": \"on_screen\", \
    }, \
    { \
        \"category\": \"system_alert\", \
        \"role\": \"system_alert\", \
        \"area\": \"on_screen\", \
    } \
    ] \
}";

const char *PolicyManager::kDefaultLayoutsConfig = "{ \
    \"layouts\": [ \
        { \
            \"name\": \"homescreen\", \
            \"layer\": \"far_homescreen\", \
            \"areas\": [ \
                { \
                    \"name\": \"fullscreen\", \
                    \"category\": \"homescreen\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"map.normal\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"normal.full\", \
                    \"category\": \"map\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"map.split\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"split.main\", \
                    \"category\": \"map\" \
                }, \
                { \
                    \"name\": \"split.sub\", \
                    \"category\": \"splitable\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"map.fullscreen\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"fullscreen\", \
                    \"category\": \"map\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"splitable.normal\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"normal.full\", \
                    \"category\": \"splitable\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"splitable.split\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"split.main\", \
                    \"category\": \"splitable\" \
                }, \
                { \
                    \"name\": \"split.sub\", \
                    \"category\": \"splitable\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"general.normal\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"normal.full\", \
                    \"category\": \"general\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"system.normal\", \
            \"layer\": \"apps\", \
            \"areas\": [ \
                { \
                    \"name\": \"normal.full\", \
                    \"category\": \"system\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"software_keyboard\", \
            \"layer\": \"near_homescreen\", \
            \"areas\": [ \
                { \
                    \"name\": \"software_keyboard\", \
                    \"category\": \"software_keyboard\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"restriction.normal\", \
            \"layer\": \"restriction\", \
            \"areas\": [ \
                { \
                    \"name\": \"restriction.normal\", \
                    \"category\": \"restriction\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"restriction.split.main\", \
            \"layer\": \"restriction\", \
            \"areas\": [ \
                { \
                    \"name\": \"restriction.split.main\", \
                    \"category\": \"restriction\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"restriction.split.sub\", \
            \"layer\": \"restriction\", \
            \"areas\": [ \
                { \
                    \"name\": \"restriction.split.sub\", \
                    \"category\": \"restriction\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"pop_up\", \
            \"layer\": \"on_screen\", \
            \"areas\": [ \
                { \
                    \"name\": \"on_screen\", \
                    \"category\": \"pop_up\" \
                } \
            ] \
        }, \
        { \
            \"name\": \"system_alert\", \
            \"layer\": \"on_screen\", \
            \"areas\": [ \
                { \
                    \"name\": \"on_screen\", \
                    \"category\": \"system_alert\" \
                } \
            ] \
        } \
    ] \
}";