summaryrefslogtreecommitdiff
path: root/src/poi-service/poi-server-capi/main.cpp
blob: 1db75921225e6da7e8e3ff4cf192a71ffd1f1b9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
/**
* @licence app begin@
* SPDX-License-Identifier: MPL-2.0
*
* \copyright Copyright (C) 2013-2014, PCA Peugeot Citroen
*
* \file main.cpp
*
* \brief This file is part of the poi proof of concept.
*
* \author Philippe Colliot <philippe.colliot@mpsa.com>
*
* \version 1.1
*
* This Source Code Form is subject to the terms of the
* Mozilla Public License (MPL), v. 2.0.
* If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* For further information see http://www.genivi.org/.
*
* List of changes:
* 10-02-2014, Philippe Colliot, refinement and migration to the new repository
* <date>, <name>, <description of change>
*
* @licence end@
*/

#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <iostream>
#include <cmath>
#include <typeinfo>
#include <getopt.h>
#ifndef DBUS_HAS_RECURSIVE_MUTEX
#define DBUS_HAS_RECURSIVE_MUTEX
#endif
#include <dbus-c++/glib-integration.h>

#include <CommonAPI/CommonAPI.hpp>
#include <CommonTypes.hpp>
#include <NavigationTypes.hpp>
#include <NavigationCoreTypes.hpp>
#include <POISearchStubDefault.hpp>
#include <POIContentAccessStubDefault.hpp>
#include <POIConfigurationStubDefault.hpp>
#include <POIContentAccessModuleProxy.hpp>
#include <RoutingProxy.hpp>

#include "poi-common-database.h"
#include "poi-common-data-model.h"
#include "poi-datamodel.h"

using namespace v4::org::genivi::navigation::navigationcore;
using namespace v2::org::genivi::navigation::poiservice;
using namespace v4::org::genivi::navigation;
using namespace v4::org::genivi;

// string conversion to numeric: the third parameter of fromString() should be one of std::hex, std::dec or std::oct
template <class T>
bool fromString(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&))
{
  std::istringstream iss(s);
  return !(iss >> f >> t).fail();
}

static std::shared_ptr < CommonAPI::Runtime > runtime;
static const std::string domain = "local";

class  POISearchServerStub;

class RoutingClientProxy
{
    public:

    std::shared_ptr<RoutingProxyDefault> myServiceRouting;

    RoutingClientProxy(const std::string domain, const std::string instance)
    {
        myServiceRouting = runtime->buildProxy<RoutingProxy>(domain, instance);

// not working correctly (blocked) so removed for the moment
//        while (!myServiceEnhancedPosition->isAvailable()) {
//            usleep(10);
//        }
    }

    void setListeners()
    {
        myServiceRouting->getRouteDeletedEvent().subscribe([&](const uint32_t& routeHandle) {
            routeDeleted(routeHandle);});
        myServiceRouting->getRouteCalculationCancelledEvent().subscribe([&](const uint32_t& routeHandle) {
            routeCalculationCancelled(routeHandle);});
        myServiceRouting->getRouteCalculationSuccessfulEvent().subscribe([&](const uint32_t& routeHandle, const Routing::UnfullfilledRoutePreference& unfullfilledPreferences) {
            routeCalculationSuccessful(routeHandle,unfullfilledPreferences);});
        myServiceRouting->getRouteCalculationFailedEvent().subscribe([&](const uint32_t& routeHandle, const Routing::CalculationError errorCode, const Routing::UnfullfilledRoutePreference& unfullfilledPreferences) {
            routeCalculationFailed(routeHandle,errorCode,unfullfilledPreferences);});
        myServiceRouting->getRouteCalculationProgressUpdateEvent().subscribe([&](const uint32_t& routeHandle, const Routing::CalculationStatus& status, const uint8_t& percentage) {
            routeCalculationProgressUpdate(routeHandle,status,percentage);});
        myServiceRouting->getAlternativeRoutesAvailableEvent().subscribe([&](const std::vector<NavigationTypes::Handle>& routeHandlesList) {
            alternativeRoutesAvailable(routeHandlesList);});
    }

    void routeDeleted(const uint32_t& routeHandle)
    {

    }

    void routeCalculationCancelled(const uint32_t& routeHandle)
    {

    }

    void routeCalculationSuccessful(const uint32_t& routeHandle, const Routing::UnfullfilledRoutePreference& unfullfilledPreferences)
    {

    }

    void routeCalculationFailed(const uint32_t& routeHandle, const Routing::CalculationError& errorCode,const Routing::UnfullfilledRoutePreference& unfullfilledPreferences)
    {

    }

    void routeCalculationProgressUpdate(const uint32_t& routeHandle, const Routing::CalculationStatus& status, const uint8_t& percentage)
    {

    }

    void alternativeRoutesAvailable (const std::vector<NavigationTypes::Handle>& routeHandlesList)
    {

    }

};

class  POIContentAccessModuleClientProxy
{

public:

    std::shared_ptr<POIContentAccessModuleProxyDefault> myServicePOIContentAccessModule;

    POIContentAccessModuleClientProxy(const std::string domain, const std::string instance, const std::string& service)
    {
        myServicePOIContentAccessModule = runtime->buildProxy<POIContentAccessModuleProxy>(domain, instance);

// not working correctly (blocked) so removed for the moment
//        while (!myServiceEnhancedPosition->isAvailable()) {
//            usleep(10);
//        }
    }

    void setListeners()
    {
        myServicePOIContentAccessModule->getConfigurationChangedEvent().subscribe([&](const std::vector< POIServiceTypes::Settings >& changedSettings) {
            configurationChanged(changedSettings);});
        myServicePOIContentAccessModule->getCategoriesRemovedEvent().subscribe([&](const std::vector< CommonTypes::CategoryID >& categories) {
            categoriesRemoved(categories);});
        myServicePOIContentAccessModule->getPoiAddedEvent().subscribe([&](const std::vector< POIServiceTypes::POI_ID >& pois) {
            POIAdded(pois);});
        myServicePOIContentAccessModule->getPoiRemovedEvent().subscribe([&](const std::vector< POIServiceTypes::POI_ID >& pois) {
            POIRemoved(pois);});
        myServicePOIContentAccessModule->getSearchStatusChangedEvent().subscribe([&](const NavigationTypes::Handle& poiSearchHandle, const POIServiceTypes::SearchStatusState& statusValue, const std::vector< POIServiceTypes::POI_ID >& pois) {
            searchStatusChanged(poiSearchHandle,statusValue,pois);});
    }

    void configurationChanged(const std::vector< POIServiceTypes::Settings >& changedSettings)
    {

    }

    void categoriesRemoved(const std::vector< CommonTypes::CategoryID >& categories)
    {

    }

    void POIAdded(const std::vector< POIServiceTypes::POI_ID >& pois)
    {

    }

    void POIRemoved(const std::vector< POIServiceTypes::POI_ID >& pois)
    {

    }

    void searchStatusChanged(const NavigationTypes::Handle& poiSearchHandle, const POIServiceTypes::SearchStatusState& statusValue, const std::vector< POIServiceTypes::POI_ID >& pois)
    {

    }

private:

};

class  POIContentAccessServerStub
: public POIContentAccessStubDefault
{
    enum {
        INVALID_HANDLE = 0xFF,
        VALID_HANDLE = 1 //the POC manages only one handle !
    } CONSTANTS;

public:

    POIContentAccessServerStub();

    ~POIContentAccessServerStub();

    void ConnectToPOISearchServer(std::shared_ptr<POISearchServerStub> poiSearch);

    void ConnectTocontentAccessModuleClient(POIContentAccessModuleClientProxy *client);

    /**
     * description: Register to the POI provider module          When the CAM registers, it
     *   provides a name and then get a unique id. This id must be used everytime the
     *   CAM communicates with the POI service component.         After the
     *   registration is done, the CAM can start to update POI categories and POI
     *   attributes as well as registers POI categories to search for.
     */
    void registerContentAccessModule(const std::shared_ptr<CommonAPI::ClientId> _client, std::string _moduleName, registerContentAccessModuleReply_t _reply);

    /**
     * description: Remove CAM from POI provider module.
     */
    void unRegisterContentAccessModule(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, unRegisterContentAccessModuleReply_t _reply);

    /**
     * description: Register to the POI provider module the categories you can search for POI.
     *      The categories could be predifined one or customized ones. In order to
     *   register a customized category, you might need to create it before and add it
     *   to the POI service component.
     */
    void registerPoiCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _poiCategories, registerPoiCategoriesReply_t _reply);

    /**
     * description: Update categories in the POI service component. It could be a predifined or a
     *   customed one.         The CAM provides for each categories the list of
     *   attributes (mandatories like name or optional) it wants to update.
     *   Depending on the local database write policy, the CAM might only be able to
     *   update customized attributes for a category and not the predefined ones so
     *   some update could be rejected.
     */
    void updateCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::CAMCategoryUpdate> _poiCategories, updateCategoriesReply_t _reply);

    /**
     * description: Add new categories to the POI service component.         The CAM provides for
     *   each categories the name, the parent categories, the top level attribute, the
     *   list of attributes, the icons, ...  .
     */
    void addCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::CAMCategory> _poiCategories, addCategoriesReply_t _reply);

    /**
     * description: Remove categories from the POI service component. It could be a predifined or a
     *   customed one.         Depending on the local database write policy, the CAM
     *   might only not be able to remove some categories.
     */
    void removeCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _poiCategories, removeCategoriesReply_t _reply);


// Specific methods

    bool GetRegisteredContentAccessModule(camIdName_t *cam);

    bool GetRegisteredCategories(POIServiceTypes::ContentAccessModuleID camId, std::vector< POIServiceTypes::CategoryAndName > *categoryList);

    bool GetRegisteredCategoriesDetails(POIServiceTypes::ContentAccessModuleID camId, std::vector<POIServiceTypes::Category> *categoryList);

    void ResetRegisteredSearchCategoriesFlags(POIServiceTypes::ContentAccessModuleID camId);

    void ResetRegisteredAttributeCategoriesFlags(POIServiceTypes::ContentAccessModuleID camId);

    void SetRegisteredSearchCategory(POIServiceTypes::ContentAccessModuleID camId, POIServiceTypes::CategoryAndRadius category);

    void SetRegisteredAttributeCategoryFlag(POIServiceTypes::ContentAccessModuleID camId, CommonTypes::CategoryID categoryId, POIServiceTypes::AttributeID attributeId);

    void SetLocale(std::string languageCode, std::string countryCode, std::string scriptCode);

    uint16_t searchAroundALocation(NavigationTypes::Coordinate3D location, const std::string* inputString, POIServiceTypes::SortOption sortOption);

    void SetPoiSearchHandle(NavigationTypes::Handle poiSearchHandle);

    void ResetPoiSearchHandle();

    void PoiSearchCanceled(NavigationTypes::Handle poiSearchHandle);

    POIServiceTypes::PoiCAMDetails GetResultPoi(uint16_t index);

    POIServiceTypes::SearchResultDetails GetPoiDetails(POIServiceTypes::POI_ID id);

    bool isAttributeAvailable(POIServiceTypes::AttributeID attributeId);

    bool removeCategoryFromTables(CommonTypes::CategoryID id);

private:

    // data conversion routines

    uint32_t m_poiSearchHandle; // the POC is limited to the management of one handle !

    POIContentAccessModuleClientProxy *mp_contentAccessModule;
    std::shared_ptr<POISearchServerStub> mp_poiSearch;
    CommonTypes::Version m_version;
    std::string m_camName;
    POIServiceTypes::ContentAccessModuleID m_camId;
    POIContentAccessModuleClientProxy *mp_clientcontentAccessModule;
    std::vector< poi_category_t > m_poiCategoriesRegistered;
    std::vector< poi_category_t > m_poiCategoriesAdded;

    //DBus data
    std::vector< POIServiceTypes::PoiCAMDetails > m_poiTable;
    std::vector< POIServiceTypes::SearchResultDetails > m_poiDetailsTable;
    std::vector< POIServiceTypes::CategoryAndRadius > m_poiCategories;
    std::vector< POIServiceTypes::AttributeDetails > m_poiAttributes;

};

class  POISearchServerStub
: public POISearchStubDefault
{
    enum {
        INVALID_HANDLE = 0xFF,
        VALID_HANDLE = 1 //the POC manages only one handle !
    } CONSTANTS;

public:

    POISearchServerStub();

    ~POISearchServerStub();

    void InitDatabase(const char* poiDatabaseFileName);

    void ConnectToContentAccessServer(std::shared_ptr<POIContentAccessServerStub> poiContentAccess);

    void ConnectToRoutingClient(RoutingClientProxy *client);

    /**
     * description: This method returns the API version implemented by the content access module.
     */
    void getVersion(const std::shared_ptr<CommonAPI::ClientId> _client, getVersionReply_t _reply);

    /**
     * description: This method allows the application to validate that POI categories are
     *   supported by the POI component and the Content access modules.
     */
    void validateCategories(const std::shared_ptr<CommonAPI::ClientId> _client, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _categories, validateCategoriesReply_t _reply);

    /**
     * description: This method retrieves the list od POI categories available (pre-defined and
     *   custom).
     */
    void getAvailableCategories(const std::shared_ptr<CommonAPI::ClientId> _client, getAvailableCategoriesReply_t _reply);

    /**
     * description: Get the root category id. That would be ALL_CATEGORIES.
     */
    void getRootCategory(const std::shared_ptr<CommonAPI::ClientId> _client, getRootCategoryReply_t _reply);

    /**
     * description: Get the children categories id and type (top level) from the a parent unique id.
     */
    void getChildrenCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::CommonTypes::CategoryID _category, getChildrenCategoriesReply_t _reply);

    /**
     * description: Get the parent categories id and type (top level) from the a unique id.
     */
    void getParentCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::CommonTypes::CategoryID _category, getParentCategoriesReply_t _reply);

    /**
     * description: Get the categories that are marked with the given standard category.
     */
    void getCategoriesWithStandardCategoryId(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::StandardCategory _standardCategoryId, getCategoriesWithStandardCategoryIdReply_t _reply);

    /**
     * description: This method retrieves the details associated to one or more POI categories.
     *       It contains the name, the parent categories, the top level attribute, the
     *   list of attributes, the icons, ... .
     */
    void getCategoriesDetails(const std::shared_ptr<CommonAPI::ClientId> _client, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _categories, getCategoriesDetailsReply_t _reply);

    /**
     * description: This method creates a new search input and retrieves a handle .
     */
    void createPoiSearchHandle(const std::shared_ptr<CommonAPI::ClientId> _client, createPoiSearchHandleReply_t _reply);

    /**
     * description: This method deletes a search input and its associated resources.
     */
    void deletePoiSearchHandle(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, deletePoiSearchHandleReply_t _reply);

    /**
     * description: This method sets the location to start the search around.         If a route
     *   handle was defined before, it will be replaced by this location.
     */
    void setCenter(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, ::v4::org::genivi::navigation::NavigationTypes::Coordinate3D _location, setCenterReply_t _reply);

    /**
     * description: This method allows to start a POI search along a guided route.         The
     *   route handle must be valid or the POI search will failed.         If a search
     *   location was defined before, it will be replaced by the route.
     */
    void setRouteHandle(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, ::v4::org::genivi::navigation::NavigationTypes::Handle _sessionHandle, ::v4::org::genivi::navigation::NavigationTypes::Handle _routeHandle, uint32_t _startSearchOffset, uint32_t _endSearchOffset, setRouteHandleReply_t _reply);

    /**
     * description: This method sets the POI categories for the current search input and the
     *   corresponding result-lists for the current session .
     */
    void setCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::CategoryAndRadius> _poiCategories, setCategoriesReply_t _reply);

    /**
     * description: This method set POI attributes (optional) for the current search input and the
     *   corresponding result-lists for the current session         An attribute is
     *   attached to a category.
     */
    void setAttributes(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::AttributeDetails> _poiAttributes, setAttributesReply_t _reply);

    /**
     * description: This method sends the search input for the search handle.         The search
     *   will start with the either the location or the route handle.         If no
     *   positon or route handle were configured, the search will use the vehicle
     *   position are center location.
     */
    void startPoiSearch(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::string _inputString, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::SortOption _sortOption, startPoiSearchReply_t _reply);

    /**
     * description: This method cancels the search for the current session.
     */
    void cancelPoiSearch(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, cancelPoiSearchReply_t _reply);

    /**
     * description: This method starts to check for POI aound vehicle according to the criteria
     *   defined with the unique handle.         By default, it will search for POI
     *   around vehicle position with default radius defined for each categories.
     *     If a route handle was defined, it will search along the route with default
     *   categorie's radius.
     */
    void startPoiProximityAlert(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::string _inputString, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::SortOption _sortOption, startPoiProximityAlertReply_t _reply);

    /**
     * description: This method cancels the search for the current session.
     */
    void cancelPoiProximityAlert(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, cancelPoiProximityAlertReply_t _reply);

    /**
     * description: This method gets the poi result list (e.g. after a Search/Scroll call) .
     */
    void requestResultList(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, uint16_t _offset, uint16_t _maxWindowSize, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::AttributeID> _attributeList, requestResultListReply_t _reply);
    /**
     * description: This method retrieves the details associated to one or more POI.         It
     *   contains the name, the parent categories, the list of attributes, the icons,
     *   ... ..
     */
    void getPoiDetails(const std::shared_ptr<CommonAPI::ClientId> _client, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::POI_ID> _id, getPoiDetailsReply_t _reply);

    // Specific methods

    void SetLocale(std::string languageCode, std::string countryCode, std::string scriptCode);


private:

// error management

    void onError();

// search routines

    uint16_t searchAroundALocation(NavigationTypes::Coordinate3D location,const std::string* inputString);

    uint16_t searchPOIRequest(uint16_t categoryIndex, std::string search_string, NavigationTypes::Coordinate3D left_bottom_location, NavigationTypes::Coordinate3D right_top_location);

// category and attribute routines

    bool isCategoryAvailable(categoryId_t id, categoryId_t *categoryId_t);

    bool isAllCategoriesSelected(uint16_t* index);

    bool isAttributeRequired(POIServiceTypes::AttributeID attribute, std::vector<POIServiceTypes::AttributeID> attributes);

// geometrical routines

    uint32_t calculateDistance(const NavigationTypes::Coordinate3D origin, const NavigationTypes::Coordinate3D target);

    double calculateAngle(const uint32_t radius);

    bool calculateLineCoefficient(double* a, double* b, const NavigationTypes::Coordinate3D pointA, const NavigationTypes::Coordinate3D pointB);

    uint32_t calculateOrthoDistance(const double a,const double b,const NavigationTypes::Coordinate3D pointP);

// private data

// DBus data
    CommonTypes::Version m_version;
    std::string m_languageCode, m_countryCode, m_scriptCode;
    NavigationTypes::Handle m_poiSearchHandle; // the POC is limited to the management of one handle !
    CommonTypes::CategoryID m_rootCategory;
    uint8_t m_sessionHandle;
    NavigationTypes::Handle m_routeHandle;
    uint16_t m_startSearchOffset;
    uint16_t m_endSearchOffset;
    POIServiceTypes::SearchStatusState m_searchStatus;
    uint32_t m_totalNumberOfSegments;
    RoutingClientProxy *mp_Routing;
    std::shared_ptr<POIContentAccessServerStub> mp_poiContentAccess;

    uint16_t m_totalSize;

    NavigationTypes::Coordinate3D m_centerLocation;
    bool m_poiSearchProximity; // boolean set if search for proximity is chosen

// buffers
    std::vector<poi_t> m_poiTable;
    std::vector<route_vector_t> m_route;

// database access
    Database *mp_database;
    NavigationTypes::Coordinate3D m_leftBottomLocation;
    NavigationTypes::Coordinate3D m_rightTopLocation;

// category and attribute management
    uint16_t m_availableCategories;
    poi_category_t m_availableCategoryTable[MAX_CATEGORIES];
};

typedef struct  {
    const char *c3;
    const char *c2;
} map32_t;

static const map32_t language_map[] = {
    {"deu","de"},
    {"eng","en"},
    {"fra","fr"},
    {"jpn","jp"},
};

static const map32_t country_map[] = {
    {"CHE","CH"},
    {"DEU","DE"},
    {"FRA","FR"},
    {"USA","US"},
    {"JPN","JP"},
};

class  POIConfigurationServerStub
: public POIConfigurationStubDefault
{

public:

    POIConfigurationServerStub();

    ~POIConfigurationServerStub();

    void getVersion(const std::shared_ptr<CommonAPI::ClientId> _client, getVersionReply_t _reply);
    void setLocale(const std::shared_ptr<CommonAPI::ClientId> _client, std::string _languageCode, std::string _countryCode, std::string _scriptCode, setLocaleReply_t _reply);
    void getLocale(const std::shared_ptr<CommonAPI::ClientId> _client, getLocaleReply_t _reply);
    void getSupportedLocales(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedLocalesReply_t _reply);
    void setTimeFormat(const std::shared_ptr<CommonAPI::ClientId> _client, NavigationTypes::TimeFormat _format, setTimeFormatReply_t _reply);
    void getTimeFormat(const std::shared_ptr<CommonAPI::ClientId> _client, getTimeFormatReply_t _reply);
    void getSupportedTimeFormats(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedTimeFormatsReply_t _reply);
    void setCoordinatesFormat(const std::shared_ptr<CommonAPI::ClientId> _client, POIConfiguration::CoordinatesFormat _coordinatesFormat, setCoordinatesFormatReply_t _reply);
    void getCoordinatesFormat(const std::shared_ptr<CommonAPI::ClientId> _client, getCoordinatesFormatReply_t _reply);
    void getSupportedCoordinatesFormat(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedCoordinatesFormatReply_t _reply);
    void setUnitsOfMeasurement(const std::shared_ptr<CommonAPI::ClientId> _client, POIConfiguration::UnitsOfMeasurement _unitsOfMeasurementList, setUnitsOfMeasurementReply_t _reply);
    void getUnitsOfMeasurement(const std::shared_ptr<CommonAPI::ClientId> _client, getUnitsOfMeasurementReply_t _reply);
    void getSupportedUnitsOfMeasurement(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedUnitsOfMeasurementReply_t _reply);

// specific methods

    void ConnectToPOISearchServer(std::shared_ptr<POISearchServerStub> poiSearch);

private:
    std::shared_ptr<POISearchServerStub> mp_poiSearch;
    CommonTypes::Version m_version;
    POIConfiguration::UnitsOfMeasurement m_unitsOfMeasurement;
    POIConfiguration::UnitsOfMeasurementList m_SupportedUnitsOfMeasurement;
    std::vector< NavigationTypes::Locale> m_SupportedLocales;
    std::string m_languageCode, m_countryCode, m_scriptCode;
    NavigationTypes::TimeFormat m_timeFormat;
    std::vector<NavigationTypes::TimeFormat> m_SupportedTimeFormats;
    POIConfiguration::CoordinatesFormat m_coordinatesFormat;
    std::vector<POIConfiguration::CoordinatesFormat> m_SupportedCoordinatesFormats;
};

// SQL requests
static const char* SQL_REQUEST_GET_AVAILABLE_CATEGORIES = "SELECT Id,name FROM poicategory WHERE Id IN (SELECT poicategory_Id FROM belongsto GROUP BY poicategory_Id);";
static const char* SQL_REQUEST_GET_CATEGORY_ATTRIBUTES = "SELECT Id,name FROM poiattribute WHERE Id IN (SELECT poiattribute_Id FROM hasattribute WHERE poicategory_Id IS ";
static const char* SQL_REQUEST_GET_AVAILABLE_AREA = "SELECT leftlongitude,bottomlatitude,rightlongitude,toplatitude FROM availablearea;";
static const char* SQL_REQUEST_GET_PARENT_CATEGORIES = "SELECT parentId FROM poicategorykinship WHERE childId IS ";
static const char* SQL_REQUEST_GET_CHILD_CATEGORIES = "SELECT childId FROM poicategorykinship WHERE parentId IS ";
static const char* SQL_REQUEST_GET_CATEGORY_ICONS = "SELECT url,format FROM iconset WHERE Id IS (SELECT iconset_Id FROM isdisplayedas WHERE poicategory_Id IS  ";

// class  poiContentAccessServer

POIContentAccessServerStub::POIContentAccessServerStub()
{
    //version is hard coded
    m_version.setVersionMajor(3);
    m_version.setVersionMinor(0);
    m_version.setVersionMicro(0);
    m_version.setDate("21-01-2014");
    m_camName = "";
    m_camId = INVALID_HANDLE;
    mp_clientcontentAccessModule = NULL;
    m_poiSearchHandle = INVALID_HANDLE;
    m_poiCategoriesAdded.clear();
    m_poiCategoriesRegistered.clear();
}

POIContentAccessServerStub::~POIContentAccessServerStub()
{
    if (mp_clientcontentAccessModule)
	delete(mp_clientcontentAccessModule);
}

void POIContentAccessServerStub::registerContentAccessModule(const std::shared_ptr<CommonAPI::ClientId> _client, std::string _moduleName, registerContentAccessModuleReply_t _reply)
{
    // the POC is limited to the management of one CAM !
    if (m_camId != INVALID_HANDLE)
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMNotAvailable"); //to be discussed !
    else
    {
        m_camName = _moduleName;
        m_camId = CAM_ID;

        // create a client for contentAccessModule
        const std::string instancePOIContentAccessModule = "POIContentAccessModule";
        mp_clientcontentAccessModule = new POIContentAccessModuleClientProxy(domain,instancePOIContentAccessModule,_moduleName);
        mp_clientcontentAccessModule->setListeners();

        // connect it to the POISearch server
        ConnectTocontentAccessModuleClient(mp_clientcontentAccessModule);
    }
    _reply(m_camId);
}

void POIContentAccessServerStub::unRegisterContentAccessModule(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, unRegisterContentAccessModuleReply_t _reply)
{
    if ((m_camId == INVALID_HANDLE) || (_camId != m_camId))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMNotAvailable"); //to be discussed !
    else
    {
        m_poiCategoriesRegistered.clear();
        m_poiCategoriesAdded.clear();
        m_camName = "";
        m_camId = INVALID_HANDLE;
	ConnectTocontentAccessModuleClient(NULL);
	delete(mp_clientcontentAccessModule);
    }
}

void POIContentAccessServerStub::registerPoiCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _poiCategories, registerPoiCategoriesReply_t _reply)
{
    std::vector< POIServiceTypes::CategoryAndReason > poiCategoriesAndReason;
    POIServiceTypes::CategoryAndReason categoryAndReason;
    size_t category_index;

    if ((m_camId == INVALID_HANDLE) || (_camId != m_camId))
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMNotAvailable"); //to be discussed !
    else
    {
        if (m_poiCategoriesRegistered.size() < MAX_CATEGORIES)
        { //limitation of categories managed
            for (category_index=0;category_index<_poiCategories.size();category_index++)
            {
                if (_poiCategories.at(category_index) == (m_poiCategoriesAdded.at(category_index).id))
                { //category id has been added before, so register it
                    m_poiCategoriesRegistered.push_back(m_poiCategoriesAdded.at(category_index));
                    categoryAndReason.setUnique_id(m_poiCategoriesAdded.at(category_index).id);
                    categoryAndReason.setReason(POIServiceTypes::UpdateReason::ATTR_ADDED);
                    poiCategoriesAndReason.push_back(categoryAndReason);
                }
            }
            mp_poiSearch->fireCategoriesUpdatedEvent(poiCategoriesAndReason);
        }
        else
           throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMCategoryNotAvailable"); //to be discussed !
    }
    _reply();
}

void POIContentAccessServerStub::updateCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::CAMCategoryUpdate> _poiCategories, updateCategoriesReply_t _reply)
{
    if ((m_camId == INVALID_HANDLE) || (_camId != m_camId))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMNotAvailable"); //to be discussed !
    else
    {

    }
    _reply();
}

void POIContentAccessServerStub::addCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::CAMCategory> _poiCategories, addCategoriesReply_t _reply)
{
    POIServiceTypes::CAMCategory CAMCategory;
    std::vector<POIServiceTypes::CategoryAttribute> CAMCategoryAttributes;
    POIServiceTypes::Details details;
    poi_category_t category;
    category_attribute_t attribute;
    std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _poiCategoriesId;
    size_t category_index,attribute_index;

    _poiCategoriesId.clear();

    if ((m_camId == INVALID_HANDLE) || (_camId != m_camId))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMNotAvailable"); //to be discussed !
    else
    {
        if (m_poiCategoriesAdded.size() < MAX_CATEGORIES)
        { //limitation of categories managed
            for (category_index=0;category_index<_poiCategories.size();category_index++)
            {
                CAMCategory = _poiCategories.at(category_index);

                details = CAMCategory.getDetails();

                category.id = (_camId*CAM_CATEGORY_OFFSET) + category_index; //create an alias
                category.name = details.getName(); // get the category name
                category.icon = details.getIcons().get<std::string>();
                category.top_level = false; //additional categories, so false
                category.attributeList.clear();
                CAMCategoryAttributes = CAMCategory.getAttributeList();
                for (attribute_index=0;attribute_index<CAMCategoryAttributes.size();attribute_index++)
                {
                    attribute.name = (CAMCategoryAttributes.at(attribute_index)).getName();
                    attribute.id = (CAMCategoryAttributes.at(attribute_index)).getId();
                    attribute.isSearched = false;
                    category.attributeList.push_back(attribute);
                }
                m_poiCategoriesAdded.push_back(category);
                _poiCategoriesId.push_back(category.id);
            }
        }
        else
            throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMCategoriesOverflow"); //to be discussed !
    }
    _reply(_poiCategoriesId);
}

void POIContentAccessServerStub::removeCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::ContentAccessModuleID _camId, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _poiCategories, removeCategoriesReply_t _reply)
{
    std::vector< POIServiceTypes::CategoryAndReason > poiCategoriesAndReason;
    POIServiceTypes::CategoryAndReason categoryAndReason;
    size_t category_index;

    if ((m_camId == INVALID_HANDLE) || (_camId != m_camId))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CAMNotAvailable"); //to be discussed !
    else
    {
        if ((m_poiCategoriesAdded.size() > 0) && (_poiCategories.size() > 0))
        {
            if (_poiCategories.size() > m_poiCategoriesAdded.size())
                throw DBus::ErrorFailed("org.genivi.poiprovider.poiContentAccess.Error.CategoryError"); //to be discussed !
            else
            {
                for (category_index=0;category_index<_poiCategories.size();category_index++)
                {
                    categoryAndReason.setUnique_id(_poiCategories.at(category_index)); //prepare it before, because after it'll be erased !
                    categoryAndReason.setReason(POIServiceTypes::UpdateReason::ATTR_REMOVED);
                    if (removeCategoryFromTables(_poiCategories.at(category_index)) == true)
                        poiCategoriesAndReason.push_back(categoryAndReason);
                }
                //warn the clients
                mp_poiSearch->fireCategoriesUpdatedEvent(poiCategoriesAndReason);
            }
        }
    }
    _reply();
}

// Specific methods

void POIContentAccessServerStub::ConnectToPOISearchServer(std::shared_ptr<POISearchServerStub> poiSearch)
{
    mp_poiSearch = poiSearch; //link to the instance of poi search
}

void POIContentAccessServerStub::ConnectTocontentAccessModuleClient(POIContentAccessModuleClientProxy *client)
{
    mp_contentAccessModule = client; //link to the instance of contentAccessModule
}

bool POIContentAccessServerStub::GetRegisteredContentAccessModule(camIdName_t *cam)
{
    if (m_camId == INVALID_HANDLE)
        return(false);
    else
    {
        cam->id = m_camId;
        cam->name = m_camName;
        return(true);
    }
}

bool POIContentAccessServerStub::GetRegisteredCategories(POIServiceTypes::ContentAccessModuleID camId, std::vector<POIServiceTypes::CategoryAndName> *categoryList)
{
    POIServiceTypes::CategoryAndName category;
    size_t category_index;

    if (camId != m_camId)
        return(false);
    else
    { //only one cam managed
        for (category_index=0;category_index<m_poiCategoriesRegistered.size();category_index++)
        {
            category.setUniqueId((m_poiCategoriesRegistered.at(category_index)).id);
            category.setName((m_poiCategoriesRegistered.at(category_index)).name);
            category.setTopLevel((m_poiCategoriesRegistered.at(category_index)).top_level);
            categoryList->push_back(category);
        }
        return(true);
    }
}

bool POIContentAccessServerStub::GetRegisteredCategoriesDetails(POIServiceTypes::ContentAccessModuleID camId, std::vector<POIServiceTypes::Category> *categoryList)
{
    POIServiceTypes::Category category;
    POIServiceTypes::CategoryDetails categoryDetails;
    std::vector<POIServiceTypes::CategoryAttribute> categoryAttributeList;
    POIServiceTypes::CategoryAttribute categoryAttribute;
    std::vector<POIServiceTypes::Operator> operatorList;
    POIServiceTypes::Operator categoryOperator;
    std::vector<POIServiceTypes::CategorySortOption> categorySortOptionList;;
    POIServiceTypes::CategorySortOption categorySortOption;;
    std::vector<CommonTypes::CategoryID> parentsId;
    uint16_t index;
    size_t category_index;

    if (camId != m_camId)
        return(false);
    else
    { //only one cam managed
        for (category_index=0;category_index<m_poiCategoriesRegistered.size();category_index++)
        {
            categoryDetails.setUniqueId((m_poiCategoriesRegistered.at(category_index)).id);
            parentsId.clear();

            for (index=0;index<(m_poiCategoriesRegistered.at(category_index)).parentList.size();index++)
            { //parents
                parentsId.push_back((m_poiCategoriesRegistered.at(category_index)).parentList.at(index));
            }
            categoryDetails.setParentsId(parentsId);
            categoryDetails.setIcons((m_poiCategoriesRegistered.at(category_index)).icon);
            categoryDetails.setName((m_poiCategoriesRegistered.at(category_index)).name);
            categoryDetails.setTopLevel((m_poiCategoriesRegistered.at(category_index)).top_level);
            categoryDetails.setDescription("no description available");
            categoryDetails.setMedia(std::string("no media"));
            categoryAttributeList.clear();
            for (index=0;index<((m_poiCategoriesRegistered.at(category_index)).attributeList.size());index++)
            {
                categoryAttribute.setName(((m_poiCategoriesRegistered.at(category_index)).attributeList.at(index)).name);
                categoryAttribute.setId(((m_poiCategoriesRegistered.at(category_index)).attributeList.at(index)).id);
                categoryAttribute.setType(POIServiceTypes::AttributeType::BOOLEAN);
                categoryOperator.setType(POIServiceTypes::OperatorType::EQUAL);
                categoryOperator.setName("EQUAL"); //redondancy
                categoryOperator.setValue(std::string(""));
                operatorList.push_back(categoryOperator);
                categoryAttribute.setOperators(operatorList);
                categoryAttributeList.push_back(categoryAttribute);
            }
            categorySortOptionList.clear();
            categorySortOption.setId(POIServiceTypes::SortOption::SORT_DEFAULT);
            categorySortOption.setName("DEFAULT"); //redondancy
            categorySortOptionList.push_back(categorySortOption);

            category.setDetails(categoryDetails);
            category.setAttributeList(categoryAttributeList);
            category.setSortOptions(categorySortOptionList);
            categoryList->push_back(category);
        }
        return(true);
    }
}

void POIContentAccessServerStub::ResetRegisteredSearchCategoriesFlags(POIServiceTypes::ContentAccessModuleID camId)
{
    size_t index;

    if (camId == m_camId)
    { //only one cam managed
        //firstly clean up the list used for the search
        m_poiCategories.clear();
        for (index=0;index<m_poiCategoriesRegistered.size();index++)
        {
            (m_poiCategoriesRegistered.at(index)).isSearch = false;
        }
    }
}

void POIContentAccessServerStub::ResetRegisteredAttributeCategoriesFlags(POIServiceTypes::ContentAccessModuleID camId)
{
    size_t index,sub_index;

    if (camId == m_camId)
    { //only one cam managed
        //firstly clean up the list used for the search
        m_poiAttributes.clear();
        for (index=0;index<m_poiCategoriesRegistered.size();index++)
        {
            for (sub_index=0;sub_index<((m_poiCategoriesRegistered.at(index)).attributeList).size();sub_index++)
                (m_poiCategoriesRegistered.at(index)).attributeList.at(sub_index).isSearched =false;
        }
    }
}

void POIContentAccessServerStub::SetRegisteredSearchCategory(POIServiceTypes::ContentAccessModuleID camId, POIServiceTypes::CategoryAndRadius category)
{
    size_t index;

    if (camId == m_camId)
    { //only one cam managed
        //firstly clean up the list used for the search
        m_poiCategories.clear();
        for (index=0;index<m_poiCategoriesRegistered.size();index++)
        {
            if ((m_poiCategoriesRegistered.at(index)).id == category.getId())
            {
                (m_poiCategoriesRegistered.at(index)).isSearch = true;
                (m_poiCategoriesRegistered.at(index)).id= category.getId();
                (m_poiCategoriesRegistered.at(index)).radius = category.getRadius();
                m_poiCategories.push_back(category); //populate the list used for the search
            }
        }
    }
}

void POIContentAccessServerStub::SetRegisteredAttributeCategoryFlag(POIServiceTypes::ContentAccessModuleID camId, CommonTypes::CategoryID categoryId, POIServiceTypes::AttributeID attributeId)
{
    size_t index, sub_index;
    POIServiceTypes::AttributeDetails attribute;

    if (camId == m_camId)
    { //only one cam managed
        for (index=0;index<m_poiCategoriesRegistered.size();index++)
        {
            if ((m_poiCategoriesRegistered.at(index)).id == categoryId)
            {
                for (sub_index=0;sub_index<((m_poiCategoriesRegistered.at(index)).attributeList).size();sub_index++)
                {
                    if ((m_poiCategoriesRegistered.at(index)).attributeList.at(sub_index).id == attributeId)
                    {
                        (m_poiCategoriesRegistered.at(index)).attributeList.at(sub_index).isSearched =true;
                        attribute.setId(attributeId);
                        attribute.setCategoryId(categoryId);
                        attribute.setMandatory(TRUE);
                        attribute.setOper(POIServiceTypes::OperatorType::INVALID);
                        attribute.setType(POIServiceTypes::AttributeType::BOOLEAN);
                        attribute.setValue(TRUE);
                        m_poiAttributes.push_back(attribute);
                    }
                }
            }
        }
    }
}

void POIContentAccessServerStub::SetLocale(std::string languageCode, std::string countryCode, string scriptCode)
{
    if (m_camId != INVALID_HANDLE)
    { //only one cam managed
        CommonAPI::CallStatus _internalCallStatus;
        mp_contentAccessModule->myServicePOIContentAccessModule->setLocale(languageCode,countryCode, scriptCode,_internalCallStatus);
    }
}

void POIContentAccessServerStub::SetPoiSearchHandle(NavigationTypes::Handle poiSearchHandle)
{
    m_poiSearchHandle =  poiSearchHandle;
}

void POIContentAccessServerStub::ResetPoiSearchHandle()
{
    m_poiSearchHandle = INVALID_HANDLE;
}

void POIContentAccessServerStub::PoiSearchCanceled(NavigationTypes::Handle poiSearchHandle)
{
    m_poiTable.clear();
    m_poiDetailsTable.clear();
    CommonAPI::CallStatus _internalCallStatus;
    mp_contentAccessModule->myServicePOIContentAccessModule->poiSearchCanceled(poiSearchHandle,_internalCallStatus);
}

POIServiceTypes::PoiCAMDetails POIContentAccessServerStub::GetResultPoi(uint16_t index)
{
    return(m_poiTable.at(index));
}

POIServiceTypes::SearchResultDetails POIContentAccessServerStub::GetPoiDetails(POIServiceTypes::POI_ID id)
{
    uint16_t index;
    bool isPOIFound;
    POIServiceTypes::SearchResultDetails searchResDetails;
    isPOIFound = false;
    index=0;
    while ((isPOIFound == false) && (index<m_poiDetailsTable.size()))
    {
        searchResDetails = m_poiDetailsTable.at(index);
        if (searchResDetails.getDetails().getId() == id)
            isPOIFound = true;
        else
            index++;
    }
    return(m_poiDetailsTable.at(index));
}

uint16_t POIContentAccessServerStub::searchAroundALocation(NavigationTypes::Coordinate3D location, const std::string* inputString, POIServiceTypes::SortOption sortOption)
{
    uint16_t maxSize;
    std::vector< POIServiceTypes::AttributeID > attributes;
    POIServiceTypes::SearchStatusState statusValue;
    uint16_t resultListSize;
    std::vector<POIServiceTypes::POI_ID > poiList;
    uint16_t index;
    CommonAPI::CallStatus _internalCallStatus;

    resultListSize = 0;

    if (m_camId != INVALID_HANDLE)
    { //only one cam managed
        m_poiTable.clear(); //clean up the table of poi
        m_poiDetailsTable.clear(); //clean up the table of details

        //prepare the data for the Poi Search on the CAM
        maxSize = 255; //by default, to be discussed why it's needed to define it ?
        mp_contentAccessModule->myServicePOIContentAccessModule->poiSearchStarted(m_poiSearchHandle,maxSize,location,m_poiCategories,m_poiAttributes,*inputString,sortOption,_internalCallStatus);

        //wait for end of search on the CAM
        do
        {
           mp_contentAccessModule->myServicePOIContentAccessModule->resultListRequested(m_camId,m_poiSearchHandle,attributes,_internalCallStatus, statusValue,resultListSize,m_poiTable);
        } while(statusValue == POIServiceTypes::SearchStatusState::SEARCHING);

        //get details now !
        //build list of poi to get
        for (index=0;index<resultListSize;index++)
            poiList.push_back(m_poiTable.at(index).getSourceId());

        mp_contentAccessModule->myServicePOIContentAccessModule->poiDetailsRequested(poiList,_internalCallStatus,m_poiDetailsTable);
    }

    return(resultListSize);
}

bool POIContentAccessServerStub::isAttributeAvailable(POIServiceTypes::AttributeID attributeId)
{
    //to do
    return(true);
}

bool POIContentAccessServerStub::removeCategoryFromTables(CommonTypes::CategoryID id)
{
    size_t index;
    bool isFound;

    //check if category has been registered and remove it
    isFound = false;
    index = 0;
    do {
        if ((m_poiCategoriesRegistered.at(index)).id == id)
        {
            m_poiCategoriesRegistered.erase(m_poiCategoriesRegistered.begin()+index);
            isFound = true;
        }
        else
            index++;
    } while ((isFound==false) && (index<m_poiCategoriesRegistered.size()));

    if (isFound == true)
    {
        //remove the category that has been added
         isFound = false;
         index = 0;
         do {
             if ((m_poiCategoriesAdded.at(index)).id == id)
             {
                 m_poiCategoriesAdded.erase(m_poiCategoriesAdded.begin()+index);
                 isFound = true;
             }
             else
                 index++;
         } while ((isFound==false) && (index<m_poiCategoriesAdded.size()));
         return(true);
    }
    return(false);
}

// class  POISearchServerStub

POISearchServerStub::POISearchServerStub()
{
        //version is hard coded
        m_version.setVersionMajor(1);
        m_version.setVersionMinor(0);
        m_version.setVersionMicro(0);
        m_version.setDate("19-12-2012");
        m_poiSearchHandle = INVALID_HANDLE;
        m_poiSearchProximity = false; //by default search around the current location
        m_availableCategories = 0;
        m_rootCategory = 0;
        m_searchStatus = POIServiceTypes::SearchStatusState::NOT_STARTED;
        m_routeHandle = INVALID_HANDLE;
        m_languageCode = "eng";
        m_countryCode = "USA";
        m_scriptCode = "Latn";

    }

POISearchServerStub::~POISearchServerStub()
    {
        delete mp_database;
    }

void POISearchServerStub::InitDatabase(const char* poiDatabaseFileName)
{
    std::string sqlQuery; //SQL request on database
    std::ostringstream  strStream; //temporary stream used for transformation into string
    vector<vector<string> > query_result, additionnal_query_result;
    vector<string >  query_line, additionnal_query_line;
    size_t index,sub_index;
    category_attribute_t attribute;
    categoryId_t value;
    categoryId_t parent,child;

    // all the pois and the related stuff are included into the database at the startup
    // so we can update some tables into the constructor
    mp_database = new Database(poiDatabaseFileName);

    // retrieve the available categories (the ones that have at least one record)
    query_result = mp_database->query(SQL_REQUEST_GET_AVAILABLE_CATEGORIES);
    if (query_result.empty())
    {
        onError(); //database is not well populated
        //todo something with table ?
    }
    else
    { // Id,name
        m_availableCategories = query_result.size(); //store the number of categories
        for (index = 0; index < m_availableCategories; index++)
        {
            // read the result of the query and store it
            query_line = query_result.at(index);
            fromString<categoryId_t>(value,query_line[0], std::dec);
            m_availableCategoryTable[index].id = value;

            // retrieve the associated icons (for the moment, just one)
            sqlQuery = SQL_REQUEST_GET_CATEGORY_ICONS;
            strStream.str("");
            strStream << value;
            sqlQuery += strStream.str();
            sqlQuery += ");";
            additionnal_query_result = mp_database->query(sqlQuery.c_str());
            if (additionnal_query_result.empty())
            {
                onError(); //database is not well populated
                //todo something with table ?
            }
            else
            {
                additionnal_query_line = additionnal_query_result.at(0);
                m_availableCategoryTable[index].icon = additionnal_query_line[0] + '.' + additionnal_query_line[1];
            }

            m_availableCategoryTable[index].name = query_line[1];

            // retrieve the associated attributes
            sqlQuery = SQL_REQUEST_GET_CATEGORY_ATTRIBUTES;
            strStream.str("");
            strStream << m_availableCategoryTable[index].id;
            sqlQuery += strStream.str();
            sqlQuery += ");";
            additionnal_query_result = mp_database->query(sqlQuery.c_str());
            if (additionnal_query_result.empty())
            {
                onError(); //database is not well populated
                //todo something with table ?
            }
            else
            {
                for (sub_index = 0; sub_index <additionnal_query_result.size(); sub_index++)
                {
                    additionnal_query_line = additionnal_query_result.at(sub_index);
                    fromString<attributeId_t>(attribute.id,additionnal_query_line[0], std::dec);
                    attribute.name = additionnal_query_line[1];
                    attribute.isSearched = false;
                    m_availableCategoryTable[index].attributeList.push_back(attribute);
                }
            }
            m_availableCategoryTable[index].top_level = true; //this POC only manages predefined categories
            m_availableCategoryTable[index].isSearch = false; //for the moment no categories selected
        }
    }

    //retrieve the parents of the categories
    //root category is the only one that is its own parent
    for (index = 0; index < m_availableCategories; index++)
    {
        sqlQuery = SQL_REQUEST_GET_PARENT_CATEGORIES;
        strStream.str("");
        strStream << m_availableCategoryTable[index].id;
        sqlQuery += strStream.str();
        sqlQuery += ";";
        query_result = mp_database->query(sqlQuery.c_str());
        if (query_result.empty())
        {
            onError(); //database is not well populated
            //todo something with table ?
        }
        else
        {
            for (parent=0;parent<query_result.size();parent++)
            {
                query_line = query_result.at(parent);
                fromString<categoryId_t>(value,query_line[0], std::dec);
                if (index == value)
                    m_rootCategory = index; //child is parent, so it's the root
                m_availableCategoryTable[index].parentList.push_back(value);
            }
        }
    }

    //retrieve the children of the categories
    for (index = 0; index < m_availableCategories; index++)
    {
        sqlQuery = SQL_REQUEST_GET_CHILD_CATEGORIES;
        strStream.str("");
        strStream << m_availableCategoryTable[index].id;
        sqlQuery += strStream.str();
        sqlQuery += ";";
        query_result = mp_database->query(sqlQuery.c_str());
        if (query_result.empty())
        {
            //no child
        }
        else
        {
            for (child=0;child<query_result.size();child++)
            {
                query_line = query_result.at(child);
                fromString<categoryId_t>(value,query_line[0], std::dec);
                m_availableCategoryTable[index].childList.push_back(value);
            }
        }
    }

    //retrieve the available area into the database
    query_result = mp_database->query(SQL_REQUEST_GET_AVAILABLE_AREA);
    if (query_result.empty())
    {
        onError(); //database is not well populated
        //todo something with table ?
    }
    else
    {
        // read the result of the query, for the moment only the first area !
        query_line = query_result.at(0);
        double value;
        fromString<double>(value,query_line[0], std::dec);
        m_leftBottomLocation.setLatitude(value);
        fromString<double>(value,query_line[1], std::dec);
        m_leftBottomLocation.setLongitude(value);
        fromString<double>(value,query_line[2], std::dec);
        m_rightTopLocation.setLatitude(value);
        fromString<double>(value,query_line[3], std::dec);
        m_rightTopLocation.setLongitude(value);
    }
    m_centerLocation.setLatitude(48.85792); //by default center of Paris
    m_centerLocation.setLongitude(2.3383145);
    m_centerLocation.setAltitude(0);
}

void POISearchServerStub::ConnectToContentAccessServer(std::shared_ptr<POIContentAccessServerStub> poiContentAccessServer)
{
    mp_poiContentAccess = poiContentAccessServer;
}

void POISearchServerStub::getVersion(const std::shared_ptr<CommonAPI::ClientId> _client, getVersionReply_t _reply)
{
    _reply(m_version);
}

void POISearchServerStub::validateCategories(const std::shared_ptr<CommonAPI::ClientId> _client, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _categories, validateCategoriesReply_t _reply){
    std::vector< POIServiceTypes::CategoryAndStatus > _results;
    POIServiceTypes::CategoryAndStatus categoryAndStatus;
    size_t index;
    categoryAndStatus.setStatus(TRUE); //by default
    for(index=0;index<_categories.size();index++)
    {
        categoryAndStatus.setUniqueId(_categories[index]);
        _results.push_back(categoryAndStatus);
    }
    _reply(_results);
}

void POISearchServerStub::getAvailableCategories(const std::shared_ptr<CommonAPI::ClientId> _client, getAvailableCategoriesReply_t _reply)
{
    std::vector< POIServiceTypes::CategoryAndName> _categories;
    std::vector< POIServiceTypes::CategoryAndName > categoryCAMList;
    POIServiceTypes::CategoryAndName category;
    uint16_t index;
    camIdName_t cam;

    // load categories from the embedded database
    for (index = 0; index < m_availableCategories; index++)
    {
        category.setUniqueId(m_availableCategoryTable[index].id);
        category.setTopLevel(m_availableCategoryTable[index].top_level);
        category.setName(m_availableCategoryTable[index].name);
        _categories.push_back(category);
    }

    // load categories from the additional database
    if (mp_poiContentAccess->GetRegisteredContentAccessModule(&cam))
    {
        if (mp_poiContentAccess->GetRegisteredCategories(cam.id,&categoryCAMList) == true)
        {
            _categories.insert(_categories.end(),categoryCAMList.begin(),categoryCAMList.end());
        }
    }

    _reply(_categories);
}

void POISearchServerStub::getRootCategory(const std::shared_ptr<CommonAPI::ClientId> _client, getRootCategoryReply_t _reply)
{
    _reply(m_rootCategory);
}

void POISearchServerStub::getChildrenCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::CommonTypes::CategoryID _category, getChildrenCategoriesReply_t _reply)
{
    std::vector< POIServiceTypes::CategoryAndLevel> _categories;
    POIServiceTypes::CategoryAndLevel child_category;
    size_t index;

    for (index=0;index<m_availableCategoryTable[_category].childList.size();index++)
    {
        child_category.setUniqueId(m_availableCategoryTable[_category].childList[index]);
        child_category.setTopLevel(m_availableCategoryTable[child_category.getUniqueId()].top_level);
        _categories.push_back(child_category);
    }
    _reply(_categories);
}

void POISearchServerStub::getParentCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::CommonTypes::CategoryID _category, getParentCategoriesReply_t _reply)
{
    std::vector< POIServiceTypes::CategoryAndLevel> _categories;
    POIServiceTypes::CategoryAndLevel parent_category;
    size_t index;

    for (index=0;index<m_availableCategoryTable[_category].parentList.size();index++)
    {
        parent_category.setUniqueId(m_availableCategoryTable[_category].parentList[index]);
        parent_category.setTopLevel(m_availableCategoryTable[parent_category.getUniqueId()].top_level);
        _categories.push_back(parent_category);
    }
    _reply(_categories);
}

void POISearchServerStub::getCategoriesDetails(const std::shared_ptr<CommonAPI::ClientId> _client, std::vector< ::v4::org::genivi::CommonTypes::CategoryID> _categories, getCategoriesDetailsReply_t _reply)
{
    std::vector<POIServiceTypes::Category> _results;
    std::vector<POIServiceTypes::Category> categoryCAMList;
    POIServiceTypes::Category category;
    POIServiceTypes::CategoryDetails categoryDetails;
    std::vector<POIServiceTypes::CategoryAttribute> categoryAttributeList;
    POIServiceTypes::CategoryAttribute categoryAttribute;
    std::vector<POIServiceTypes::Operator> operatorList;
    POIServiceTypes::Operator categoryOperator;
    std::vector<POIServiceTypes::CategorySortOption> categorySortOptionList;;
    POIServiceTypes::CategorySortOption categorySortOption;;
    std::vector<CommonTypes::CategoryID> parentsId;
    size_t index,sub_index;
    CommonTypes::CategoryID category_index;
    camIdName_t cam;

    // load categories details from the embedded database
    index=0;

    while ((index<_categories.size())&&(index < m_availableCategories))
    {
        if ( isCategoryAvailable(_categories.at(index),&category_index) == true)
        { //category found into the embedded data!
            categoryDetails.setUniqueId(m_availableCategoryTable[category_index].id);
            categoryDetails.setStandardCategoryId(POIServiceTypes::StandardCategory::NOT_STANDARD_CATEGORY);
            parentsId.clear();

            for (sub_index=0;sub_index<m_availableCategoryTable[category_index].parentList.size();sub_index++)
            { //parents
                parentsId.push_back(m_availableCategoryTable[category_index].parentList.at(sub_index));
            }
            categoryDetails.setParentsId(parentsId);
            categoryDetails.setIcons(m_availableCategoryTable[category_index].icon);
            categoryDetails.setName(m_availableCategoryTable[category_index].name);
            categoryDetails.setTopLevel(m_availableCategoryTable[category_index].top_level);
            categoryDetails.setDescription("no description available");
            categoryDetails.setMedia(std::string("no media"));
            categoryAttributeList.clear();
            //scan the attributes
            for (sub_index=0;sub_index<m_availableCategoryTable[category_index].attributeList.size();sub_index++)
            {
                categoryAttribute.setId((m_availableCategoryTable[category_index].attributeList.at(sub_index)).id);
                categoryAttribute.setName((m_availableCategoryTable[category_index].attributeList.at(sub_index)).name);
                categoryAttribute.setType(POIServiceTypes::AttributeType::BOOLEAN);
                operatorList.clear();
                categoryOperator.setType(POIServiceTypes::OperatorType::EQUAL);
                categoryOperator.setName("EQUAL"); //redondancy
                categoryOperator.setValue(std::string(""));
                operatorList.push_back(categoryOperator);
                categoryAttribute.setOperators(operatorList);
                categoryAttributeList.push_back(categoryAttribute);
            }

            categorySortOptionList.clear();
            categorySortOption.setId(POIServiceTypes::SortOption::SORT_DEFAULT);
            categorySortOption.setName("DEFAULT");
            categorySortOptionList.push_back(categorySortOption);

            category.setDetails(categoryDetails);
            category.setAttributeList(categoryAttributeList);
            category.setSortOptions(categorySortOptionList);
            _results.push_back(category);
        }
        index++;
    }

    // load categories details from the additional database
    if (mp_poiContentAccess->GetRegisteredContentAccessModule(&cam))
    {
        if (mp_poiContentAccess->GetRegisteredCategoriesDetails(cam.id,&categoryCAMList) == true)
        {
            for (index=0;index<categoryCAMList.size();index++)
                _results.push_back(categoryCAMList.at(index));
        }
    }

    _reply(_results);
}

void POISearchServerStub::getCategoriesWithStandardCategoryId(const std::shared_ptr<CommonAPI::ClientId> _client, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::StandardCategory _standardCategoryId, getCategoriesWithStandardCategoryIdReply_t _reply)
{
    std::vector< CommonTypes::CategoryID > _categories;
    _reply(_categories);
}

void POISearchServerStub::createPoiSearchHandle(const std::shared_ptr<CommonAPI::ClientId> _client, createPoiSearchHandleReply_t _reply)
{
    // the POC is limited to the management of one handle !
    if (m_poiSearchHandle != INVALID_HANDLE)
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        m_poiSearchHandle = VALID_HANDLE;
        //set the handle for the content access server
        mp_poiContentAccess->SetPoiSearchHandle(m_poiSearchHandle);
        //set the language used by the content access server
         mp_poiContentAccess->SetLocale(m_languageCode,m_countryCode, m_scriptCode);
    }
    _reply(m_poiSearchHandle);
}

void POISearchServerStub::deletePoiSearchHandle(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, deletePoiSearchHandleReply_t _reply)
{
    camIdName_t cam;
    bool status;
    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
   {
        m_poiSearchHandle = INVALID_HANDLE;
        status = mp_poiContentAccess->GetRegisteredContentAccessModule(&cam);
        if (status == true)
        {
             //reset the handle
             mp_poiContentAccess->ResetPoiSearchHandle();
        }

    }
    _reply();
}

void POISearchServerStub::setCenter(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, ::v4::org::genivi::navigation::NavigationTypes::Coordinate3D _location, setCenterReply_t _reply)
{
    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        m_centerLocation = _location;
    }
    _reply();
}

void POISearchServerStub::setRouteHandle(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, ::v4::org::genivi::navigation::NavigationTypes::Handle _sessionHandle, ::v4::org::genivi::navigation::NavigationTypes::Handle _routeHandle, uint32_t _startSearchOffset, uint32_t _endSearchOffset, setRouteHandleReply_t _reply)
{
    uint32_t index;
    int16_t detailLevel;
    std::vector< Routing::RouteSegmentType > valuesToReturn;
    uint32_t numberOfSegments;
    uint32_t offset;
    uint32_t totalNumberOfSegments;
    std::vector< Routing::RouteSegment > routeSegments;
    Routing::RouteSegment element;
    Routing::RouteSegment::iterator iter;
    route_vector_t routeVector;

    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        m_sessionHandle = _sessionHandle;
        m_routeHandle = _routeHandle;
        m_startSearchOffset = _startSearchOffset;
        m_endSearchOffset = _endSearchOffset;

        //Get the route segments
        m_route.clear(); //clear the existing route
        detailLevel = 0; //to be clarified
        valuesToReturn.push_back(Routing::RouteSegmentType::START_LATITUDE);
        valuesToReturn.push_back(Routing::RouteSegmentType::END_LATITUDE);
        valuesToReturn.push_back(Routing::RouteSegmentType::START_LONGITUDE);
        valuesToReturn.push_back(Routing::RouteSegmentType::END_LONGITUDE);
        offset = 0;

        //First get the total amount of segments
        numberOfSegments = 0;
        CommonAPI::CallStatus _internalCallStatus;
        mp_Routing->myServiceRouting->getRouteSegments(m_routeHandle,detailLevel,valuesToReturn,numberOfSegments,offset,_internalCallStatus, totalNumberOfSegments,routeSegments);
        m_totalNumberOfSegments = totalNumberOfSegments;

        // Get all the segments
        numberOfSegments = m_totalNumberOfSegments;
        mp_Routing->myServiceRouting->getRouteSegments(m_routeHandle,detailLevel,valuesToReturn,numberOfSegments,offset,_internalCallStatus,totalNumberOfSegments,routeSegments);
        for (index=0;index<routeSegments.size();index++)
        {
            element = routeSegments.at(index);
            iter = element.find(Routing::RouteSegmentType::START_LATITUDE);
            if (iter != element.end())
                routeVector.startPoint.setLatitude(element.at(Routing::RouteSegmentType::START_LATITUDE).get<double>());
            iter = element.find(Routing::RouteSegmentType::START_LONGITUDE);
            if (iter != element.end())
                routeVector.startPoint.setLongitude(element.at(Routing::RouteSegmentType::START_LONGITUDE).get<double>());
            iter = element.find(Routing::RouteSegmentType::END_LATITUDE);
            if (iter != element.end())
                routeVector.endPoint.setLatitude(element.at(Routing::RouteSegmentType::END_LATITUDE).get<double>());
            iter = element.find(Routing::RouteSegmentType::END_LONGITUDE);
            if (iter != element.end())
                routeVector.endPoint.setLongitude(element.at(Routing::RouteSegmentType::END_LONGITUDE).get<double>());
            m_route.push_back(routeVector);
        }
    }
    _reply();
}

void POISearchServerStub::setCategories(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::CategoryAndRadius> _poiCategories, setCategoriesReply_t _reply)
{
    size_t index;
    CommonTypes::CategoryID category_index;
    camIdName_t cam;
    POIServiceTypes::CategoryAndRadius categoryRadius;

    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        //reset of the flags of the categories into the embedded database
        for (index=0;index<m_availableCategories;index++)
        {
            m_availableCategoryTable[index].isSearch = false;
        }

        //reset the flags of the categories into the additional database
       if ((mp_poiContentAccess->GetRegisteredContentAccessModule(&cam)) == true)
       {
           mp_poiContentAccess->ResetRegisteredSearchCategoriesFlags(cam.id);
       }

        for (index=0; index < _poiCategories.size();index++)
        {
            categoryRadius = _poiCategories.at(index);
            if ( isCategoryAvailable(categoryRadius.getId() ,&category_index) == true)
            { //category found into the embedded data !
                m_availableCategoryTable[category_index].isSearch = true;
                m_availableCategoryTable[category_index].radius = (categoryRadius.getRadius())*10; //get the radius (unit is 10 m)
                m_availableCategoryTable[category_index].angle = calculateAngle(m_availableCategoryTable[category_index].radius);
            }
            else
            {
                if ((mp_poiContentAccess->GetRegisteredContentAccessModule(&cam)) == true)
                {
                    mp_poiContentAccess->SetRegisteredSearchCategory(cam.id,categoryRadius);
                }
            }
        }
    }
    _reply();
}

void POISearchServerStub::setAttributes(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::AttributeDetails> _poiAttributes, setAttributesReply_t _reply)
{
    POIServiceTypes::AttributeDetails attributeDetails;
    size_t index,sub_index;
    CommonTypes::CategoryID category_index;
    camIdName_t cam;

    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        //reset flags for all the attributes of the categories into the embedded database
        for (index=0;index<m_availableCategories;index++)
        {
            for (category_index=0;category_index<((m_availableCategoryTable[index]).attributeList).size();category_index++)
                (m_availableCategoryTable[index]).attributeList.at(category_index).isSearched =false;
        }

        //reset the flags of all the attributes of the categories into the additional database
        if ((mp_poiContentAccess->GetRegisteredContentAccessModule(&cam)) == true)
        {
           mp_poiContentAccess->ResetRegisteredAttributeCategoriesFlags(cam.id);
        }

        //set the flags of attributes to be searched for the given categories
        for (index=0;index<_poiAttributes.size();index++)
        {
            attributeDetails = _poiAttributes[index];
            if ( isCategoryAvailable(attributeDetails.getCategoryId(),&category_index) == true)
            { //category found into the embedded database!
                for (sub_index=0;sub_index<(m_availableCategoryTable[category_index].attributeList.size());sub_index++)
                { //check attribute by name
                    if ((m_availableCategoryTable[category_index].attributeList.at(sub_index)).id == attributeDetails.getId())
                        (m_availableCategoryTable[category_index].attributeList.at(sub_index)).isSearched =true;
                }
            }
            else
            { //set the flags of attributes to be searched into the additional database
                if ((mp_poiContentAccess->GetRegisteredContentAccessModule(&cam)) == true)
                {
                    mp_poiContentAccess->SetRegisteredAttributeCategoryFlag(cam.id,attributeDetails.getCategoryId(),attributeDetails.getId());
                }
            }
        }
    }
    _reply();
}

void POISearchServerStub::startPoiSearch(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::string _inputString, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::SortOption _sortOption, startPoiSearchReply_t _reply)
{

    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        m_totalSize = 0;
        if (m_poiSearchProximity == false)
        { //no proximity search started on this session !
            m_searchStatus = POIServiceTypes::SearchStatusState::SEARCHING;
            firePoiStatusEvent(_poiSearchHandle,m_searchStatus);
            //sortOption is not used yet
            //for the moment, no thread used, because just one handle managed
            // search on the embedded database first
            m_totalSize = searchAroundALocation(m_centerLocation,&_inputString); //search around the current location of the vehicle
            //and now search on the additional database if the cam has been registered before the creation of the poi search handle
            m_totalSize += mp_poiContentAccess->searchAroundALocation(m_centerLocation,&_inputString,_sortOption);
            m_searchStatus = POIServiceTypes::SearchStatusState::FINISHED;
            firePoiStatusEvent(_poiSearchHandle,m_searchStatus);
            fireResultListChangedEvent(_poiSearchHandle,m_totalSize);
        }
    }
    _reply();
}

void POISearchServerStub::cancelPoiSearch(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, cancelPoiSearchReply_t _reply)
{
    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        if (m_poiSearchProximity == false)
        { //no proximity search started on this session !
            m_searchStatus = POIServiceTypes::SearchStatusState::NOT_STARTED;
            firePoiStatusEvent(_poiSearchHandle,m_searchStatus);
        }
    }
    _reply();
}

void POISearchServerStub::startPoiProximityAlert(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, std::string _inputString, ::v2::org::genivi::navigation::poiservice::POIServiceTypes::SortOption _sortOption, startPoiProximityAlertReply_t _reply)
{
    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        if (m_poiSearchProximity == false)
        {
            m_poiSearchProximity = true; //start proximity search !
            m_searchStatus = POIServiceTypes::SearchStatusState::SEARCHING;
            firePoiStatusEvent(_poiSearchHandle,m_searchStatus);
        }
    }
    _reply();
}

void POISearchServerStub::cancelPoiProximityAlert(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, cancelPoiProximityAlertReply_t _reply)
{
    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        if (m_poiSearchProximity == true)
        {
            m_poiSearchProximity = false; //stop proximity search !
            m_searchStatus = POIServiceTypes::SearchStatusState::NOT_STARTED;
            firePoiStatusEvent(_poiSearchHandle,m_searchStatus);
        }
    }
    _reply();
}

void POISearchServerStub::requestResultList(const std::shared_ptr<CommonAPI::ClientId> _client, ::v4::org::genivi::navigation::NavigationTypes::Handle _poiSearchHandle, uint16_t _offset, uint16_t _maxWindowSize, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::AttributeID> _attributeList, requestResultListReply_t _reply)
{
    POIServiceTypes::SearchStatusState _statusValue;
    uint16_t _resultListSize;
    std::vector< POIServiceTypes::SearchResult> _resultListWindow;
    POIServiceTypes::SearchResult element; //id distance status attributes[]
    POIServiceTypes::PoiCAMDetails camElement; //id name category location distance attributes[]
    std::vector<POIServiceTypes::PoiAttribute> attributes;
    POIServiceTypes::PoiAttribute attribute; //name type value
    size_t index,size,sub_index;
    size_t attribute_index;
    poi_t poi;

    if ((m_poiSearchHandle == INVALID_HANDLE) || (_poiSearchHandle != m_poiSearchHandle))
        // to do send an error message
        throw DBus::ErrorFailed("org.genivi.poiprovider.poiSearch.Error.HandleNotAvailable"); //to be discussed !
    else
    {
        _statusValue = m_searchStatus;
        if (m_searchStatus == POIServiceTypes::SearchStatusState::FINISHED)
        { //consider that the search is finished for the CAM too

            if ((_offset+1)>m_totalSize)
                index=0;
            else
                index=_offset;
            if ((index+_maxWindowSize)>m_totalSize)
                size=m_totalSize-index;
            else
                size=_maxWindowSize;
            _resultListSize = size;

            while (size>0)
            { //load the poi into the vector
                if ((index+1)>m_poiTable.size())
                {
                    //no more data into the embedded table, so pick data from the additional table
                    camElement = mp_poiContentAccess->GetResultPoi(index-m_poiTable.size());
                    element.setId(camElement.getSourceId()); //id
                    element.setDistance(camElement.getDistance()); //distance
                    element.setRouteStatus(POIServiceTypes::RouteStatus::OFF_ROUTE);
                    attributes = camElement.getAttributeList();
                    element.setAttributeList(attributes);
                    _resultListWindow.push_back(element);
                    index++;
                    size-=1;
                }
                else
                { // pick data from the embedded table
                    poi = m_poiTable.at(index);
                    element.setId(poi.segment);
                    element.setDistance(poi.distance);
                    element.setRouteStatus(POIServiceTypes::RouteStatus::OFF_ROUTE);
                    attributes.clear(); //clean list of attributes

                    for (attribute_index=0;attribute_index<m_availableCategoryTable[poi.categoryIndex].attributeList.size();attribute_index++)
                    { //scan the attributes for the category
                        if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_SOURCE)
                        {
                            attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                            if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                            {
                                attribute.setType(POIServiceTypes::AttributeType::STRING);
                                attribute.setValue(poi.source);
                                attributes.push_back(attribute);
                            }
                        }
                        else
                        {
                            if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_WEBSITE)
                            {
                                attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                {
                                    attribute.setType(POIServiceTypes::AttributeType::STRING);
                                    attribute.setValue(poi.website);
                                    attributes.push_back(attribute);
                                }
                            }
                            else
                            {
                                if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_PHONE)
                                {
                                    attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                    if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                    {
                                        attribute.setType(POIServiceTypes::AttributeType::STRING);
                                        attribute.setValue(poi.phone);
                                        attributes.push_back(attribute);
                                    }
                                }
                                else
                                {
                                    if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_STARS)
                                    {
                                        attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                        if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                        {
                                            attribute.setType(POIServiceTypes::AttributeType::INTEGER);
                                            attribute.setValue((int32_t)poi.stars);
                                            attributes.push_back(attribute);
                                        }
                                    }
                                    else
                                    {
                                        if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_OPENINGHOURS)
                                        {
                                            attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                            if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                            {
                                                attribute.setType(POIServiceTypes::AttributeType::STRING);
                                                attribute.setValue(poi.openinghours);
                                                attributes.push_back(attribute);
                                            }
                                        }
                                        else
                                        {
                                            if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRHOUSENUMBER)
                                            {
                                                attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                                if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                                {
                                                    attribute.setType(POIServiceTypes::AttributeType::STRING);
                                                    attribute.setValue(poi.addr_house_number);
                                                    attributes.push_back(attribute);
                                                }
                                            }
                                            else
                                            {
                                                if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRSTREET)
                                                {
                                                    attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                                    if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                                    {
                                                        attribute.setType(POIServiceTypes::AttributeType::STRING);
                                                        attribute.setValue(poi.addr_street);
                                                        attributes.push_back(attribute);
                                                    }
                                                }
                                                else
                                                {
                                                    if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRPOSTCODE)
                                                    {
                                                        attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                                        if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                                        {
                                                            attribute.setType(POIServiceTypes::AttributeType::INTEGER);
                                                            attribute.setValue((int32_t)poi.addr_postcode);
                                                            attributes.push_back(attribute);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRCITY)
                                                        {
                                                            attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                                            if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                                            {
                                                                attribute.setType(POIServiceTypes::AttributeType::STRING);
                                                                attribute.setValue(poi.addr_city);
                                                                attributes.push_back(attribute);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_BRAND)
                                                            {
                                                                attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                                                if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                                                {
                                                                    attribute.setType(POIServiceTypes::AttributeType::STRING);
                                                                    attribute.setValue(poi.brand);
                                                                    attributes.push_back(attribute);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_OPERATEUR)
                                                                {
                                                                    attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                                                    if (isAttributeRequired(attribute.getId(),_attributeList)==true)
                                                                    {
                                                                        attribute.setType(POIServiceTypes::AttributeType::STRING);
                                                                        attribute.setValue(poi.operateur);
                                                                        attributes.push_back(attribute);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    element.setAttributeList(attributes);
                    _resultListWindow.push_back(element);
                    index++;
                    size-=1;
                }
            }
        }        
    }
    _reply(_statusValue,_resultListSize,_resultListWindow);
}

void POISearchServerStub::getPoiDetails(const std::shared_ptr<CommonAPI::ClientId> _client, std::vector< ::v2::org::genivi::navigation::poiservice::POIServiceTypes::POI_ID> _id, getPoiDetailsReply_t _reply)
{
    std::vector< POIServiceTypes::SearchResultDetails> _results;
    POIServiceTypes::SearchResultDetails searchResDetails;
    POIServiceTypes::PoiDetails poiDetails;
    NavigationTypes::Coordinate3D coordinate3D;
    std::vector<POIServiceTypes::PoiAttribute> attributes;
    POIServiceTypes::PoiAttribute attribute;
    std::vector<CommonTypes::CategoryID> categories;
    uint16_t indexPOIList,indexIDList;
    size_t attribute_index;
    poi_t poi;
    bool isPOIFound;
    std::ostringstream  strStream; //temporary stream used for transformation into string

    //for the moment, no optimization so it needs to be improved a little :-)

    for (indexIDList=0;indexIDList<_id.size();indexIDList++)
    { //scan the list of poi to detail
        isPOIFound = false;

        //scan the embedded table
        //'while' first because the table could be empty in case of additional data only !
        indexPOIList=0;
        while((isPOIFound == false) && (indexPOIList<m_poiTable.size()))
        {
            poi = m_poiTable.at(indexPOIList);
            if (poi.segment == _id.at(indexIDList))
            {
                isPOIFound = true;
                poiDetails.setId(poi.segment);
                poiDetails.setName(poi.name);
                coordinate3D.setLatitude(poi.coordinate.getLatitude());
                coordinate3D.setLongitude(poi.coordinate.getLongitude());
                coordinate3D.setAltitude(poi.coordinate.getAltitude());
                poiDetails.setLocation(coordinate3D);
                searchResDetails.setDetails(poiDetails);
                categories.clear();
                categories.push_back(m_availableCategoryTable[poi.categoryIndex].id); //POI only owns to one category for the moment !
                searchResDetails.setCategories(categories);

                // check the attributes for the category and get the value
                for (attribute_index=0;attribute_index<m_availableCategoryTable[poi.categoryIndex].attributeList.size();attribute_index++)
                { //scan the attributes for the category
                    if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_SOURCE)
                    {
                        attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                        attribute.setType(POIServiceTypes::AttributeType::STRING);
                        attribute.setValue(poi.source);
                        attributes.push_back(attribute);
                    }
                    else
                    {
                        if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_WEBSITE)
                        {
                            attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                            attribute.setType(POIServiceTypes::AttributeType::STRING);
                            attribute.setValue(poi.website);
                            attributes.push_back(attribute);
                        }
                        else
                        {
                            if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_PHONE)
                            {
                                attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                attribute.setType(POIServiceTypes::AttributeType::STRING);
                                attribute.setValue(poi.phone);
                                attributes.push_back(attribute);
                            }
                            else
                            {
                                if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_STARS)
                                {
                                    attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                    attribute.setType(POIServiceTypes::AttributeType::INTEGER);
                                    attribute.setValue((int32_t)poi.stars);
                                    attributes.push_back(attribute);
                                }
                                else
                                {
                                    if ((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_OPENINGHOURS)
                                    {
                                        attribute.setId((m_availableCategoryTable[poi.categoryIndex].attributeList.at(attribute_index)).id);
                                        attribute.setType(POIServiceTypes::AttributeType::STRING);
                                        attribute.setValue(poi.openinghours);
                                        attributes.push_back(attribute);
                                    }
                                }
                            }
                        }
                    }
                }

                searchResDetails.setAttributeList(attributes);
                _results.push_back(searchResDetails);
            }
            else
                ++indexPOIList;
        }

        if (isPOIFound == false)
        {
            //not found in embedded table, so get it into  the additional data
            //we consider that the element exists into the additional data (no check)
            _results.push_back(mp_poiContentAccess->GetPoiDetails(_id.at(indexIDList)));
        }
    }

    _reply(_results);
}

// Specific methods

void POISearchServerStub::SetLocale(std::string languageCode, std::string countryCode, std::string scriptCode)
{
    m_languageCode = languageCode;
    m_countryCode = countryCode;
    m_scriptCode = scriptCode;

    mp_poiContentAccess->SetLocale(languageCode,countryCode,scriptCode); //update poi content access data (to set the cam data)
}

void POISearchServerStub::ConnectToRoutingClient(RoutingClientProxy *client)
{
    mp_Routing = client; //link to the instance of routing
}

void POISearchServerStub::onError()
{
}

uint16_t POISearchServerStub::searchAroundALocation(NavigationTypes::Coordinate3D location,const std::string* inputString)
{
    uint16_t index, all_categories_index;
    uint16_t total_size;
    NavigationTypes::Coordinate3D left_bottom_location,right_top_location;

    total_size = 0;

    m_poiTable.clear(); //clean the table of poi

    if (isAllCategoriesSelected(&all_categories_index))
    {
        left_bottom_location.setLatitude(location.getLatitude() - m_availableCategoryTable[all_categories_index].angle);
        left_bottom_location.setLongitude(location.getLongitude() - m_availableCategoryTable[all_categories_index].angle);
        right_top_location.setLatitude(location.getLatitude() + m_availableCategoryTable[all_categories_index].angle);
        right_top_location.setLongitude(location.getLongitude() + m_availableCategoryTable[all_categories_index].angle);
        for (index=0;index<m_availableCategories;index++)
        {
            total_size += searchPOIRequest(index, *inputString,left_bottom_location,right_top_location);
        }
    }
    else
    {
        for (index=0;index<m_availableCategories;index++)
        {
            if (m_availableCategoryTable[index].isSearch)
            {
                left_bottom_location.setLatitude(location.getLatitude() - m_availableCategoryTable[index].angle);
                left_bottom_location.setLongitude(location.getLongitude() - m_availableCategoryTable[index].angle);
                right_top_location.setLatitude(location.getLatitude() + m_availableCategoryTable[index].angle);
                right_top_location.setLongitude(location.getLongitude() + m_availableCategoryTable[index].angle);
                total_size += searchPOIRequest(index, *inputString,left_bottom_location,right_top_location);
            }
        }

    }
    return(total_size);
}

uint16_t POISearchServerStub::searchPOIRequest(uint16_t categoryIndex, std::string search_string, NavigationTypes::Coordinate3D left_bottom_location,NavigationTypes::Coordinate3D right_top_location)
{
    std::string sqlQuery; //SQL request on database
    vector<vector<string> > sqlQueryResult; //result of the query on database
    vector<string>  sqlQueryLine;
    std::ostringstream  strStream; //temporary stream used for transformation into string
    size_t index,sub_index,attribute_index;
    poi_t poi;
    std::string name;

    name = m_availableCategoryTable[categoryIndex].name;

    sqlQuery = "SELECT name,segment,latitude,longitude,altitude";

    for (attribute_index=0;attribute_index<m_availableCategoryTable[categoryIndex].attributeList.size();attribute_index++)
    {
        if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).isSearched == true)
        {
            sqlQuery += ",";
            sqlQuery += (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).name;
        }

    }
    sqlQuery += " FROM poi WHERE (Id IN (SELECT poi_Id FROM belongsto,poicategory WHERE (belongsto.poicategory_Id = poicategory.Id) AND (poicategory.name = '";
    sqlQuery += name;
    sqlQuery += "'))) AND ((latitude > ";
    strStream.str(""); //to clean before !
    strStream << left_bottom_location.getLatitude();
    sqlQuery += strStream.str();
    sqlQuery += ") AND (latitude < ";
    strStream.str(""); //to clean before !
    strStream << right_top_location.getLatitude();
    sqlQuery += strStream.str();
    sqlQuery += ")) AND ((longitude > ";
    strStream.str(""); //to clean before !
    strStream << left_bottom_location.getLongitude();
    sqlQuery += strStream.str();
    sqlQuery += ") AND (longitude < ";
    strStream.str(""); //to clean before !
    strStream << right_top_location.getLongitude();
    sqlQuery += strStream.str();
    sqlQuery += ")) AND (name LIKE '%";
    sqlQuery += search_string;
    sqlQuery += "%');";
    sqlQueryResult = mp_database->query(sqlQuery.c_str());

    //populate the table of poi
    poi.categoryIndex = categoryIndex;

    for (index=0;index<sqlQueryResult.size();index++)
    {
        sqlQueryLine = sqlQueryResult.at(index);
        poi.name = sqlQueryLine[0];
        fromString<uint64_t>(poi.segment,sqlQueryLine[1], std::dec);
        double value;
        fromString<double>(value,sqlQueryLine[2], std::dec);
        poi.coordinate.setLatitude(value);
        fromString<double>(value,sqlQueryLine[3], std::dec);
        poi.coordinate.setLongitude(value);
        fromString<double>(value,sqlQueryLine[4], std::dec);
        poi.coordinate.setAltitude(value);
        sub_index = 5;

        for (attribute_index=0;attribute_index<m_availableCategoryTable[categoryIndex].attributeList.size();attribute_index++)
        {
            if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).isSearched == true)
            {
                if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_SOURCE)
                    poi.source = sqlQueryLine[sub_index];
                else
                    if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_WEBSITE)
                        poi.website = sqlQueryLine[sub_index];
                    else
                        if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_PHONE)
                            poi.phone = sqlQueryLine[sub_index];
                        else
                            if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_STARS)
                                fromString<uint16_t>(poi.stars,sqlQueryLine[sub_index], std::dec);
                            else
                                if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_OPENINGHOURS)
                                    poi.openinghours = sqlQueryLine[sub_index];
                                else
                                    if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRHOUSENUMBER)
                                        poi.addr_house_number = sqlQueryLine[sub_index];
                                    else
                                        if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRSTREET)
                                            poi.addr_street = sqlQueryLine[sub_index];
                                        else
                                            if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRPOSTCODE)
                                                fromString<uint16_t>(poi.addr_postcode,sqlQueryLine[sub_index], std::dec);
                                            else
                                                if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_ADDRCITY)
                                                    poi.addr_city = sqlQueryLine[sub_index];
                                                else
                                                    if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_BRAND)
                                                        poi.brand = sqlQueryLine[sub_index];
                                                    else
                                                        if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_OPERATEUR)
                                                            poi.operateur = sqlQueryLine[sub_index];
                sub_index++;
            }

        }

        //calculate distance from the center location
        poi.distance = calculateDistance(m_centerLocation,poi.coordinate);
        m_poiTable.push_back(poi);
    }

    return(sqlQueryResult.size());
}

bool POISearchServerStub::isCategoryAvailable(categoryId_t id, categoryId_t *category_id)
{
    bool isFound = false;
    categoryId_t index = 0;
    do
    {
        if (m_availableCategoryTable[index].id == id)
        {
            *category_id = index;
            isFound = true;
        }
        else
            ++index;
    } while ((isFound==false) && (index < m_availableCategories));

    return(isFound);
}

bool POISearchServerStub::isAllCategoriesSelected(uint16_t* index)
{
    bool isSelected = false;
    *index = 0;
    do
    {
        if ((m_availableCategoryTable[*index].name == "all categories") && m_availableCategoryTable[*index].isSearch)
        {
            isSelected = true;
        }
        else
            *index += 1;
    } while ((isSelected==false) && (*index < m_availableCategories));

    return(isSelected);
}

bool POISearchServerStub::isAttributeRequired(POIServiceTypes::AttributeID attribute,std::vector<POIServiceTypes::AttributeID> attributes)
{
    bool isRequired = false;
    size_t index;
    index=0;
    while((isRequired==false)&&(index < attributes.size()))
    {
        if (attributes.at(index) == attribute)
            isRequired = true;
        else
            index++;
    };

    return(isRequired);
}

uint32_t POISearchServerStub::calculateDistance(const NavigationTypes::Coordinate3D origin, const NavigationTypes::Coordinate3D target)
{
    //this piece of software is based on an haversine formula given by:
    // - Doctors Rick and Peterson, The Math Forum
    // http://mathforum.org/dr.math/
    // haversine of angle A is (1-cos(A))/2 that is equal to sin^2(A/2)

    //earth is considered to be a perfect spĥere, in order to simplify calculation
    const double PI = 4.0*atan(1.0);
    const double earth=6378137; //IUGG value for the equatorial radius of the Earth in m
    NavigationTypes::Coordinate3D pointA, pointB;
    double buffer;

    pointA.setLatitude(origin.getLatitude() * (PI/180));
    pointA.setLongitude(origin.getLongitude() * (PI/180));
    pointB.setLatitude(target.getLatitude() * (PI/180));
    pointB.setLongitude(target.getLongitude() * (PI/180));

    buffer= pow(sin((pointA.getLatitude()-pointB.getLatitude())/2.0),2.0)+cos(pointA.getLatitude())*cos(pointB.getLatitude())*pow(sin((pointA.getLongitude()-pointB.getLongitude())/2),2);
    buffer = 2*atan2(sqrt(buffer),sqrt(1.0-buffer));
    buffer=earth*buffer;
    return ((uint32_t) buffer); //return distance in meters
}

double POISearchServerStub::calculateAngle(const uint32_t radius)
{
    //N is the point on the sphere for the origin
    //M is a point of the sphere at the distance radius (NM = radius)
    //O is the center of the earth
    //ON=OM so the triangle is isosceles
    //alpha is the angle ON,OM
    //beta is the angle NM,NO
    //OM*sin(alpha)=NM*sin(beta)
    //alpha+beta+beta=PI (because of isoceles)
    //beta=(PI-alpha)/2
    //sin(beta) = cos(alpha/2)
    //sin(alpha)=2*sin(alpha/2)*cos(alpha/2)
    //alpha=2*arcsin(NM/(2*OM))

    //earth is considered to be a perfect spĥere, in order to simplify calculation
    const double PI = 4.0*atan(1.0);
    const double earth=6378137; //IUGG value for the equatorial radius of the Earth in m
    double angle;
    angle=2*asin(radius/(2*earth));
    angle = (angle*180)/PI; //in degrees
    return(angle);
}

bool POISearchServerStub::calculateLineCoefficient(double* a,double* b,const NavigationTypes::Coordinate3D pointA,const NavigationTypes::Coordinate3D pointB)
{
   /* longitude on the x axis, latitude on the y axis
    * segment line y = a*x + b
    * pointA and pointB points of the segment
    * if xA is different of xB
    * a = (yA-yB)/(xA-xB)
    * b = (xA*yB - xB*yA)/(xA-xB)
    */
    if (pointA.getLongitude() == pointB.getLongitude())
    { //equation x = constant
        *b = pointA.getLongitude(); //constant into *b
        return(false);
    }
    else
    {
        *a = (pointA.getLatitude()-pointB.getLatitude())/(pointA.getLongitude()-pointB.getLongitude());
        *b = (pointA.getLongitude()*pointB.getLatitude() - pointB.getLongitude()*pointA.getLatitude())/(pointA.getLongitude()-pointB.getLongitude());
        return(true);
    }
}

/**
 * \fn double calculateOrthoDistance(const double a,const double b,const DBus_geoCoordinate3D::geoCoordinate3D_t pointP)
 * \brief calculate ortho distance between a point P and a line defined by the slope a and the y intercept b.
 *
 * \param  double a -slope
 * \param  double b -y intercept
 * \param  NavigationTypes::Coordinate3D pointP -point
 * \return uint32_t distance.
 */
uint32_t POISearchServerStub::calculateOrthoDistance(const double a, const double b, const NavigationTypes::Coordinate3D pointP)
{
    /* longitude on the x axis, latitude on the y axis
     * segment line y = a*x + b
     * projection line y = c*x + d
     * pointP point and pointI ortho projection
     * ortho projection => c = (-1)/a
     * P point of projection line so yP = c*xP + d
     * => d = yP + xP/a
     * I point of segment and projection lines
     * so yI = a*xI  + b
     * and yI = c*xI + d
     * => xI = (d-b)/(a-c)
     * and yI = (a*d - b*c)/(a-c)
     * so xI = (a*yP + xP -a*b)/(1+a*a)
     * and yI = (a*a*yP + a*xP + b)/(1+a*a)
     * distance = sqrt((xP-xI)*(xP-xI) + (yP-yI)*(yP-yI))
     * distance = (a*xP - yP + b)/sqrt(1 + a*a)
     */
    return ((uint32_t)((a*pointP.getLongitude() - pointP.getLatitude() + b)/sqrt(1 + a*a)));
}

// class  POIConfigurationServerStub

POIConfigurationServerStub::POIConfigurationServerStub()
{
    POIConfiguration::UnitsOfMeasurementListValue valueList;

    m_version.setVersionMajor(3);
    m_version.setVersionMinor(0);
    m_version.setVersionMicro(0);
    m_version.setDate("21-01-2014");

    NavigationTypes::Locale en_US { "eng","USA", "Latn" };
    NavigationTypes::Locale fr_FR { "fra","FRA", "Latn" };
    NavigationTypes::Locale de_DE { "deu","DEU", "Latn" };
    NavigationTypes::Locale jp_JP { "jpn","JPN", "Hrkt" };

    m_SupportedLocales.push_back(en_US);
    m_SupportedLocales.push_back(fr_FR);
    m_SupportedLocales.push_back(de_DE);
    m_SupportedLocales.push_back(jp_JP);

    valueList.push_back(POIConfiguration::UnitsOfMeasurementValue::MILE);
    valueList.push_back(POIConfiguration::UnitsOfMeasurementValue::METER);

    m_SupportedUnitsOfMeasurement[POIConfiguration::UnitsOfMeasurementAttribute::LENGTH]=valueList;

    m_SupportedTimeFormats.push_back(NavigationTypes::TimeFormat::TWELVEH);
    m_SupportedTimeFormats.push_back(NavigationTypes::TimeFormat::TWENTYFOURH);

    m_SupportedCoordinatesFormats.push_back(POIConfiguration::CoordinatesFormat::DEGREES);

    //default init
    m_languageCode = m_SupportedLocales.at(0).getLanguageCode();
    m_countryCode = m_SupportedLocales.at(0).getCountryCode();
    m_scriptCode = m_SupportedLocales.at(0).getScriptCode();
    m_coordinatesFormat = m_SupportedCoordinatesFormats.at(0);

    m_unitsOfMeasurement[POIConfiguration::UnitsOfMeasurementAttribute::LENGTH] = POIConfiguration::UnitsOfMeasurementValue::METER;

    m_timeFormat = m_SupportedTimeFormats.at(0);
}

POIConfigurationServerStub::~POIConfigurationServerStub()
{

}

void POIConfigurationServerStub::getVersion(const std::shared_ptr<CommonAPI::ClientId> _client, getVersionReply_t _reply)
{
    _reply(m_version);
}

void POIConfigurationServerStub::setLocale(const std::shared_ptr<CommonAPI::ClientId> _client, std::string _languageCode, std::string _countryCode, std::string _scriptCode, setLocaleReply_t _reply)
{
    std::vector<POIServiceTypes::Settings> changedSettings;

    m_languageCode = _languageCode;
    m_countryCode = _countryCode;
    m_scriptCode = _scriptCode;

    changedSettings.push_back(POIServiceTypes::Settings::LOCALE);
    fireConfigurationChangedEvent(changedSettings);
    _reply();
}

void POIConfigurationServerStub::getLocale(const std::shared_ptr<CommonAPI::ClientId> _client, getLocaleReply_t _reply)
{
    _reply(m_languageCode,m_countryCode,m_scriptCode);
}

void POIConfigurationServerStub::getSupportedLocales(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedLocalesReply_t _reply)
{
    _reply(m_SupportedLocales);
}

void POIConfigurationServerStub::setTimeFormat(const std::shared_ptr<CommonAPI::ClientId> _client, NavigationTypes::TimeFormat _format, setTimeFormatReply_t _reply)
{
    std::vector<POIServiceTypes::Settings> changedSettings;

    m_timeFormat = _format;

    changedSettings.push_back(POIServiceTypes::Settings::TIME_FORMAT);
    fireConfigurationChangedEvent(changedSettings);
    _reply();
}

void POIConfigurationServerStub::getTimeFormat(const std::shared_ptr<CommonAPI::ClientId> _client, getTimeFormatReply_t _reply)
{
    _reply(m_timeFormat);
}

void POIConfigurationServerStub::getSupportedTimeFormats(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedTimeFormatsReply_t _reply)
{
    _reply(m_SupportedTimeFormats);
}

void POIConfigurationServerStub::setCoordinatesFormat(const std::shared_ptr<CommonAPI::ClientId> _client, POIConfiguration::CoordinatesFormat _coordinatesFormat, setCoordinatesFormatReply_t _reply)
{
    std::vector<POIServiceTypes::Settings> changedSettings;

    m_coordinatesFormat = _coordinatesFormat;

    changedSettings.push_back(POIServiceTypes::Settings::COORDINATES_FORMAT);
    fireConfigurationChangedEvent(changedSettings);
    _reply();
}

void POIConfigurationServerStub::getCoordinatesFormat(const std::shared_ptr<CommonAPI::ClientId> _client, getCoordinatesFormatReply_t _reply)
{
    _reply(m_coordinatesFormat);
}

void POIConfigurationServerStub::getSupportedCoordinatesFormat(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedCoordinatesFormatReply_t _reply)
{
    _reply(m_SupportedCoordinatesFormats);
}

void POIConfigurationServerStub::setUnitsOfMeasurement(const std::shared_ptr<CommonAPI::ClientId> _client, POIConfiguration::UnitsOfMeasurement _unitsOfMeasurementList, setUnitsOfMeasurementReply_t _reply)
{
    std::vector<POIServiceTypes::Settings> changedSettings;

    m_unitsOfMeasurement = _unitsOfMeasurementList;

    changedSettings.push_back(POIServiceTypes::Settings::UNITS_OF_MEASUREMENT);
    fireConfigurationChangedEvent(changedSettings);
    _reply();
}

void POIConfigurationServerStub::getUnitsOfMeasurement(const std::shared_ptr<CommonAPI::ClientId> _client, getUnitsOfMeasurementReply_t _reply)
{
    _reply(m_unitsOfMeasurement);
}

void POIConfigurationServerStub::getSupportedUnitsOfMeasurement(const std::shared_ptr<CommonAPI::ClientId> _client, getSupportedUnitsOfMeasurementReply_t _reply)
{
    _reply(m_SupportedUnitsOfMeasurement);
}

//specific methods

void POIConfigurationServerStub::ConnectToPOISearchServer(std::shared_ptr<POISearchServerStub> poiSearch)
{
    mp_poiSearch = poiSearch;  //link to the instance of poi search
}


const char* program_name; //file to sink outputs

/**
 * \fn is_readable (const std::string & file)
 * \brief Check if file can be opened.
 *
 * \param  const std::string & file	-name of the file
 * \return true if file readable.
 */
bool is_readable( const std::string & file )
{
    std::ifstream fi( file.c_str() );
    return !fi.fail();
}

/**
 * \fn print_usage (FILE* stream, int exit_code)
 * \brief Display the available options.
 *
 * \param  const FILE* stream	-name of stream to use
 * \param  int exit_code	-exit code
 * \return void.
 */
void print_usage (FILE* stream, int exit_code)
{
  fprintf (stream, "Use: %s options [database]\n",program_name);
  fprintf (stream,
           " -h --help               Display this message.\n"
           " -f --file database   Open the database.\n");
  exit (exit_code);
}

/**
 * \fn int main (int  argc , char**  argv)
 * \brief POI Server  implements the component of POI Service "POISearch" that includes search and content access.
 *
 * \param  int  argc
 * \param  char**  argv
 * \return EXIT_SUCCESS, EXIT_FAILURE.
 */
int main(int  argc , char**  argv )
{
    GMainLoop * mainloop ;

    // Set the global C and C++ locale to the user-configured locale,
    // so we can use std::cout with UTF-8, via Glib::ustring, without exceptions.
    std::locale::global(std::locale(""));

    // Common API data init
    runtime = CommonAPI::Runtime::get();
    bool successfullyRegistered;

    const std::string instancePOISearch = "POISearch";
    std::shared_ptr<POISearchServerStub> myServicePOISearch = std::make_shared<POISearchServerStub>();
    successfullyRegistered = runtime->registerService(domain, instancePOISearch, myServicePOISearch);
    while (!successfullyRegistered) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        successfullyRegistered = runtime->registerService(domain, instancePOISearch, myServicePOISearch);
    }

    const std::string instancePOIConfiguration = "POIConfiguration";
    std::shared_ptr<POIConfigurationServerStub> myServicePOIConfiguration = std::make_shared<POIConfigurationServerStub>();
    successfullyRegistered = runtime->registerService(domain, instancePOIConfiguration, myServicePOIConfiguration);
    while (!successfullyRegistered) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        successfullyRegistered = runtime->registerService(domain, instancePOIConfiguration, myServicePOIConfiguration);
    }

    const std::string instancePOIContentAccess = "POIContentAccess";
    std::shared_ptr<POIContentAccessServerStub> myServicePOIContentAccess = std::make_shared<POIContentAccessServerStub>();
    successfullyRegistered = runtime->registerService(domain, instancePOIContentAccess, myServicePOIContentAccess);
    while (!successfullyRegistered) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        successfullyRegistered = runtime->registerService(domain, instancePOIContentAccess, myServicePOIContentAccess);
    }

    const std::string instanceRouting = "Routing";
    RoutingClientProxy* mp_routingClientProxy = new RoutingClientProxy(domain,instanceRouting);
    mp_routingClientProxy->setListeners();

    //index used for argument analysis
    int next_option;

    /* Valid letters for short options. */
    const char* const short_options = "hf:";
    /* Valid string for long options. */
    const struct option long_options[] = {
        { "help",     0, NULL, 'h' },
        { "file", 2, NULL, 'f' },
        { NULL,       0, NULL, 0   }   /* Always at the end of the table.  */
    };
    char* database_filename = NULL; //database filename passed as first argument
    program_name = argv[0];

    do {
        next_option = getopt_long (argc, argv, short_options,
                                  long_options, NULL);
        switch (next_option)
        {
        case 'h':   /* -h --help */
            print_usage (stdout, 0);
            break;
        case 'f':   /* -f --file database*/
            database_filename = argv[2];
            if (!is_readable(database_filename))
                print_usage (stderr, 1);
            else
            {
                // init the database
                myServicePOISearch->InitDatabase(database_filename);

                // connect myServicePOISearch to myServicePOIContentAccess
                myServicePOIContentAccess->ConnectToPOISearchServer(myServicePOISearch);
                myServicePOISearch->ConnectToContentAccessServer(myServicePOIContentAccess);

                // connect myServicePOISearch to myServicePOIConfiguration
                myServicePOIConfiguration->ConnectToPOISearchServer(myServicePOISearch);

                // connect mp_routingClientProxy to myServicePOISearch
                myServicePOISearch->ConnectToRoutingClient(mp_routingClientProxy);

                // Create a new GMainLoop with default context and initial state of "not running "
                mainloop = g_main_loop_new (g_main_context_default() , FALSE );

                // Send a feedback to the user
                cout << "poi server started" << endl;

                // loop listening

                g_main_loop_run ( mainloop );

                // clean memory
                delete mp_routingClientProxy;
            }
            break;
        case '?':   /* Invalid option. */
            print_usage (stderr, 1);
        case -1:    /* End of options.  */
            break;
        default:    /* Error  */
            print_usage (stderr, 1);
        }
    }
    while (next_option != -1);

    return EXIT_SUCCESS;
}