summaryrefslogtreecommitdiffstats
path: root/src/com/android/bluetooth/map/BluetoothMapContent.java
blob: 2d27c6b87c0a63dab7bbacfd9f69b4f6d607de5a (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
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
/*
* Copyright (C) 2014 Samsung System LSI
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.bluetooth.map;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.CanonicalAddressesColumns;
import android.provider.Telephony.Threads;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.util.Rfc822Token;
import android.text.util.Rfc822Tokenizer;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;

import com.android.bluetooth.SignedLongLong;
import com.android.bluetooth.map.BluetoothMapContentObserver.Msg;
import com.android.bluetooth.map.BluetoothMapUtils.TYPE;
import com.android.bluetooth.map.BluetoothMapbMessageMime.MimePart;
import com.android.bluetooth.mapapi.BluetoothMapContract;
import com.android.bluetooth.mapapi.BluetoothMapContract.ConversationColumns;
import com.google.android.mms.pdu.CharacterSets;
import com.google.android.mms.pdu.PduHeaders;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@TargetApi(19)
public class BluetoothMapContent {

    private static final String TAG = "BluetoothMapContent";

    private static final boolean D = BluetoothMapService.DEBUG;
    private static final boolean V = Log.isLoggable(BluetoothMapService.LOG_TAG, Log.VERBOSE);

    // Parameter Mask for selection of parameters to return in listings
    private static final int MASK_SUBJECT               = 0x00000001;
    private static final int MASK_DATETIME              = 0x00000002;
    private static final int MASK_SENDER_NAME           = 0x00000004;
    private static final int MASK_SENDER_ADDRESSING     = 0x00000008;
    private static final int MASK_RECIPIENT_NAME        = 0x00000010;
    private static final int MASK_RECIPIENT_ADDRESSING  = 0x00000020;
    private static final int MASK_TYPE                  = 0x00000040;
    private static final int MASK_SIZE                  = 0x00000080;
    private static final int MASK_RECEPTION_STATUS      = 0x00000100;
    private static final int MASK_TEXT                  = 0x00000200;
    private static final int MASK_ATTACHMENT_SIZE       = 0x00000400;
    private static final int MASK_PRIORITY              = 0x00000800;
    private static final int MASK_READ                  = 0x00001000;
    private static final int MASK_SENT                  = 0x00002000;
    private static final int MASK_PROTECTED             = 0x00004000;
    private static final int MASK_REPLYTO_ADDRESSING    = 0x00008000;
    // TODO: Duplicate in proposed spec
    // private static final int MASK_RECEPTION_STATE       = 0x00010000;
    private static final int MASK_DELIVERY_STATUS       = 0x00020000;
    private static final int MASK_CONVERSATION_ID       = 0x00040000;
    private static final int MASK_CONVERSATION_NAME     = 0x00080000;
    private static final int MASK_FOLDER_TYPE           = 0x00100000;
    // TODO: about to be removed from proposed spec
    // private static final int MASK_SEQUENCE_NUMBER       = 0x00200000;
    private static final int MASK_ATTACHMENT_MIME       = 0x00400000;

    private static final int  CONVO_PARAM_MASK_CONVO_NAME              = 0x00000001;
    private static final int  CONVO_PARAM_MASK_CONVO_LAST_ACTIVITY     = 0x00000002;
    private static final int  CONVO_PARAM_MASK_CONVO_READ_STATUS       = 0x00000004;
    private static final int  CONVO_PARAM_MASK_CONVO_VERSION_COUNTER   = 0x00000008;
    private static final int  CONVO_PARAM_MASK_CONVO_SUMMARY           = 0x00000010;
    private static final int  CONVO_PARAM_MASK_PARTTICIPANTS           = 0x00000020;
    private static final int  CONVO_PARAM_MASK_PART_UCI                = 0x00000040;
    private static final int  CONVO_PARAM_MASK_PART_DISP_NAME          = 0x00000080;
    private static final int  CONVO_PARAM_MASK_PART_CHAT_STATE         = 0x00000100;
    private static final int  CONVO_PARAM_MASK_PART_LAST_ACTIVITY      = 0x00000200;
    private static final int  CONVO_PARAM_MASK_PART_X_BT_UID           = 0x00000400;
    private static final int  CONVO_PARAM_MASK_PART_NAME               = 0x00000800;
    private static final int  CONVO_PARAM_MASK_PART_PRESENCE           = 0x00001000;
    private static final int  CONVO_PARAM_MASK_PART_PRESENCE_TEXT      = 0x00002000;
    private static final int  CONVO_PARAM_MASK_PART_PRIORITY           = 0x00004000;

    /* Default values for omitted or 0 parameterMask application parameters */
    // MAP specification states that the default value for parameter mask are
    // the #REQUIRED attributes in the DTD, and not all enabled
    public static final long PARAMETER_MASK_ALL_ENABLED = 0xFFFFFFFFL;
    public static final long PARAMETER_MASK_DEFAULT = 0x5EBL;
    public static final long CONVO_PARAMETER_MASK_ALL_ENABLED = 0xFFFFFFFFL;
    public static final long CONVO_PARAMETER_MASK_DEFAULT =
            CONVO_PARAM_MASK_CONVO_NAME |
            CONVO_PARAM_MASK_PARTTICIPANTS |
            CONVO_PARAM_MASK_PART_UCI |
            CONVO_PARAM_MASK_PART_DISP_NAME;




    private static final int FILTER_READ_STATUS_UNREAD_ONLY = 0x01;
    private static final int FILTER_READ_STATUS_READ_ONLY   = 0x02;
    private static final int FILTER_READ_STATUS_ALL         = 0x00;

    /* Type of MMS address. From Telephony.java it must be one of PduHeaders.BCC, */
    /* PduHeaders.CC, PduHeaders.FROM, PduHeaders.TO. These are from PduHeaders.java */
    public static final int MMS_FROM    = 0x89;
    public static final int MMS_TO      = 0x97;
    public static final int MMS_BCC     = 0x81;
    public static final int MMS_CC      = 0x82;

    public static final String INSERT_ADDRES_TOKEN = "insert-address-token";
    private static final String HONDA_CARKIT = "64:D4:BD";

    private final Context mContext;
    private final ContentResolver mResolver;
    private final String mBaseUri;
    private final BluetoothMapAccountItem mAccount;
    /* The MasInstance reference is used to update persistent (over a connection) version counters*/
    private final BluetoothMapMasInstance mMasInstance;
    private String mMessageVersion = BluetoothMapUtils.MAP_V10_STR;

    private int mRemoteFeatureMask = BluetoothMapUtils.MAP_FEATURE_DEFAULT_BITMASK;
    private int mMsgListingVersion = BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V10;

    static final String[] SMS_PROJECTION = new String[] {
        BaseColumns._ID,
        Sms.THREAD_ID,
        Sms.ADDRESS,
        Sms.BODY,
        Sms.DATE,
        Sms.READ,
        Sms.TYPE,
        Sms.STATUS,
        Sms.LOCKED,
        Sms.ERROR_CODE
    };

    static final String[] MMS_PROJECTION = new String[] {
        BaseColumns._ID,
        Mms.THREAD_ID,
        Mms.MESSAGE_ID,
        Mms.MESSAGE_SIZE,
        Mms.SUBJECT,
        Mms.CONTENT_TYPE,
        Mms.TEXT_ONLY,
        Mms.DATE,
        Mms.DATE_SENT,
        Mms.READ,
        Mms.MESSAGE_BOX,
        Mms.STATUS,
        Mms.PRIORITY,
    };

    static final String[] SMS_CONVO_PROJECTION = new String[] {
        BaseColumns._ID,
        Sms.THREAD_ID,
        Sms.ADDRESS,
        Sms.DATE,
        Sms.READ,
        Sms.TYPE,
        Sms.STATUS,
        Sms.LOCKED,
        Sms.ERROR_CODE
    };

    static final String[] MMS_CONVO_PROJECTION = new String[] {
        BaseColumns._ID,
        Mms.THREAD_ID,
        Mms.MESSAGE_ID,
        Mms.MESSAGE_SIZE,
        Mms.SUBJECT,
        Mms.CONTENT_TYPE,
        Mms.TEXT_ONLY,
        Mms.DATE,
        Mms.DATE_SENT,
        Mms.READ,
        Mms.MESSAGE_BOX,
        Mms.STATUS,
        Mms.PRIORITY,
        Mms.Addr.ADDRESS
    };

    /* CONVO LISTING projections and column indexes */
    private static final String[] MMS_SMS_THREAD_PROJECTION = {
        Threads._ID,
        Threads.DATE,
        Threads.SNIPPET,
        Threads.SNIPPET_CHARSET,
        Threads.READ,
        Threads.RECIPIENT_IDS
    };

    private static final String[] CONVO_VERSION_PROJECTION = new String[] {
        /* Thread information */
        ConversationColumns.THREAD_ID,
        ConversationColumns.THREAD_NAME,
        ConversationColumns.READ_STATUS,
        ConversationColumns.LAST_THREAD_ACTIVITY,
        ConversationColumns.SUMMARY,
    };

    /* Optimize the Cursor access to avoid the need to do a getColumnIndex() */
    private static final int MMS_SMS_THREAD_COL_ID;
    private static final int MMS_SMS_THREAD_COL_DATE;
    private static final int MMS_SMS_THREAD_COL_SNIPPET;
    private static final int MMS_SMS_THREAD_COL_SNIPPET_CS;
    private static final int MMS_SMS_THREAD_COL_READ;
    private static final int MMS_SMS_THREAD_COL_RECIPIENT_IDS;
    static {
        // TODO: This might not work, if the projection is mapped in the content provider...
        //       Change to init at first query? (Current use in the AOSP code is hard coded values
        //       unrelated to the projection used)
        List<String> projection = Arrays.asList(MMS_SMS_THREAD_PROJECTION);
        MMS_SMS_THREAD_COL_ID = projection.indexOf(Threads._ID);
        MMS_SMS_THREAD_COL_DATE = projection.indexOf(Threads.DATE);
        MMS_SMS_THREAD_COL_SNIPPET = projection.indexOf(Threads.SNIPPET);
        MMS_SMS_THREAD_COL_SNIPPET_CS = projection.indexOf(Threads.SNIPPET_CHARSET);
        MMS_SMS_THREAD_COL_READ = projection.indexOf(Threads.READ);
        MMS_SMS_THREAD_COL_RECIPIENT_IDS = projection.indexOf(Threads.RECIPIENT_IDS);
    }

    private class FilterInfo {
        public static final int TYPE_SMS    = 0;
        public static final int TYPE_MMS    = 1;
        public static final int TYPE_EMAIL  = 2;
        public static final int TYPE_IM     = 3;

        // TODO: Change to ENUM, to ensure correct usage
        int mMsgType = TYPE_SMS;
        int mPhoneType = 0;
        String mPhoneNum = null;
        String mPhoneAlphaTag = null;
        /*column indices used to optimize queries */
        public int mMessageColId                = -1;
        public int mMessageColDate              = -1;
        public int mMessageColBody              = -1;
        public int mMessageColSubject           = -1;
        public int mMessageColFolder            = -1;
        public int mMessageColRead              = -1;
        public int mMessageColSize              = -1;
        public int mMessageColFromAddress       = -1;
        public int mMessageColToAddress         = -1;
        public int mMessageColCcAddress         = -1;
        public int mMessageColBccAddress        = -1;
        public int mMessageColReplyTo           = -1;
        public int mMessageColAccountId         = -1;
        public int mMessageColAttachment        = -1;
        public int mMessageColAttachmentSize    = -1;
        public int mMessageColAttachmentMime    = -1;
        public int mMessageColPriority          = -1;
        public int mMessageColProtected         = -1;
        public int mMessageColReception         = -1;
        public int mMessageColDelivery          = -1;
        public int mMessageColThreadId          = -1;
        public int mMessageColThreadName        = -1;

        public int mSmsColFolder            = -1;
        public int mSmsColRead              = -1;
        public int mSmsColId                = -1;
        public int mSmsColSubject           = -1;
        public int mSmsColAddress           = -1;
        public int mSmsColDate              = -1;
        public int mSmsColType              = -1;
        public int mSmsColThreadId          = -1;

        public int mMmsColRead              = -1;
        public int mMmsColFolder            = -1;
        public int mMmsColAttachmentSize    = -1;
        public int mMmsColTextOnly          = -1;
        public int mMmsColId                = -1;
        public int mMmsColSize              = -1;
        public int mMmsColDate              = -1;
        public int mMmsColSubject           = -1;
        public int mMmsColThreadId          = -1;

        public int mConvoColConvoId         = -1;
        public int mConvoColLastActivity    = -1;
        public int mConvoColName            = -1;
        public int mConvoColRead            = -1;
        public int mConvoColVersionCounter  = -1;
        public int mConvoColSummary         = -1;
        public int mContactColBtUid         = -1;
        public int mContactColChatState     = -1;
        public int mContactColContactUci    = -1;
        public int mContactColNickname      = -1;
        public int mContactColLastActive    = -1;
        public int mContactColName          = -1;
        public int mContactColPresenceState = -1;
        public int mContactColPresenceText  = -1;
        public int mContactColPriority      = -1;


        public void setMessageColumns(Cursor c) {
            mMessageColId               = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns._ID);
            mMessageColDate             = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.DATE);
            mMessageColSubject          = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.SUBJECT);
            mMessageColFolder           = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.FOLDER_ID);
            mMessageColRead             = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.FLAG_READ);
            mMessageColSize             = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.MESSAGE_SIZE);
            mMessageColFromAddress      = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.FROM_LIST);
            mMessageColToAddress        = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.TO_LIST);
            mMessageColAttachment       = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT);
            mMessageColAttachmentSize   = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE);
            mMessageColPriority         = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY);
            mMessageColProtected        = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.FLAG_PROTECTED);
            mMessageColReception        = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.RECEPTION_STATE);
            mMessageColDelivery         = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.DEVILERY_STATE);
            mMessageColThreadId         = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.THREAD_ID);
        }

        public void setEmailMessageColumns(Cursor c) {
            setMessageColumns(c);
            mMessageColCcAddress        = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.CC_LIST);
            mMessageColBccAddress       = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.BCC_LIST);
            mMessageColReplyTo          = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.REPLY_TO_LIST);
        }

        public void setImMessageColumns(Cursor c) {
            setMessageColumns(c);
            mMessageColThreadName       = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.THREAD_NAME);
            mMessageColAttachmentMime   = c.getColumnIndex(
                    BluetoothMapContract.MessageColumns.ATTACHMENT_MINE_TYPES);
            //TODO this is temporary as text should come from parts table instead
            mMessageColBody = c.getColumnIndex(BluetoothMapContract.MessageColumns.BODY);

        }

        public void setEmailImConvoColumns(Cursor c) {
            mConvoColConvoId            = c.getColumnIndex(
                    BluetoothMapContract.ConversationColumns.THREAD_ID);
            mConvoColLastActivity       = c.getColumnIndex(
                    BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY);
            mConvoColName               = c.getColumnIndex(
                    BluetoothMapContract.ConversationColumns.THREAD_NAME);
            mConvoColRead               = c.getColumnIndex(
                    BluetoothMapContract.ConversationColumns.READ_STATUS);
            mConvoColVersionCounter     = c.getColumnIndex(
                    BluetoothMapContract.ConversationColumns.VERSION_COUNTER);
            mConvoColSummary            = c.getColumnIndex(
                    BluetoothMapContract.ConversationColumns.SUMMARY);
            setEmailImConvoContactColumns(c);
        }

        public void setEmailImConvoContactColumns(Cursor c){
            mContactColBtUid         = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.X_BT_UID);
            mContactColChatState     = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.CHAT_STATE);
            mContactColContactUci     = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.UCI);
            mContactColNickname      = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.NICKNAME);
            mContactColLastActive    = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE);
            mContactColName          = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.NAME);
            mContactColPresenceState = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE);
            mContactColPresenceText = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.STATUS_TEXT);
            mContactColPriority      = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.PRIORITY);
        }

        public void setSmsColumns(Cursor c) {
            mSmsColId      = c.getColumnIndex(BaseColumns._ID);
            mSmsColFolder  = c.getColumnIndex(Sms.TYPE);
            mSmsColRead    = c.getColumnIndex(Sms.READ);
            mSmsColSubject = c.getColumnIndex(Sms.BODY);
            mSmsColAddress = c.getColumnIndex(Sms.ADDRESS);
            mSmsColDate    = c.getColumnIndex(Sms.DATE);
            mSmsColType    = c.getColumnIndex(Sms.TYPE);
            mSmsColThreadId= c.getColumnIndex(Sms.THREAD_ID);
        }

        public void setMmsColumns(Cursor c) {
            mMmsColId              = c.getColumnIndex(BaseColumns._ID);
            mMmsColFolder          = c.getColumnIndex(Mms.MESSAGE_BOX);
            mMmsColRead            = c.getColumnIndex(Mms.READ);
            mMmsColAttachmentSize  = c.getColumnIndex(Mms.MESSAGE_SIZE);
            mMmsColTextOnly        = c.getColumnIndex(Mms.TEXT_ONLY);
            mMmsColSize            = c.getColumnIndex(Mms.MESSAGE_SIZE);
            mMmsColDate            = c.getColumnIndex(Mms.DATE);
            mMmsColSubject         = c.getColumnIndex(Mms.SUBJECT);
            mMmsColThreadId        = c.getColumnIndex(Mms.THREAD_ID);
        }
    }

    public BluetoothMapContent(final Context context, BluetoothMapAccountItem account,
            BluetoothMapMasInstance mas) {
        mContext = context;
        mResolver = mContext.getContentResolver();
        mMasInstance = mas;
        if (mResolver == null) {
            if (D) Log.d(TAG, "getContentResolver failed");
        }

        if(account != null){
            mBaseUri = account.mBase_uri + "/";
            mAccount = account;
        } else {
            mBaseUri = null;
            mAccount = null;
        }
    }
    private static void close(Closeable c) {
        try {
          if (c != null) c.close();
        } catch (IOException e) {
        }
    }
    private void setProtected(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_PROTECTED) != 0) {
            String protect = "no";
            if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                fi.mMsgType == FilterInfo.TYPE_IM) {
                int flagProtected = c.getInt(fi.mMessageColProtected);
                if (flagProtected == 1) {
                    protect = "yes";
                }
            }
            if (V) Log.d(TAG, "setProtected: " + protect + "\n");
            e.setProtect(protect);
        }
    }

    private void setThreadId(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_CONVERSATION_ID) != 0) {
            long threadId = 0;
            TYPE type = TYPE.SMS_GSM; // Just used for handle encoding
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                threadId = c.getLong(fi.mSmsColThreadId);
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                threadId = c.getLong(fi.mMmsColThreadId);
                type = TYPE.MMS;// Just used for handle encoding
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                threadId = c.getLong(fi.mMessageColThreadId);
                type = TYPE.EMAIL;// Just used for handle encoding
            }
            e.setThreadId(threadId,type);
            if (V) Log.d(TAG, "setThreadId: " + threadId + "\n");
        }
    }

    private void setThreadName(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        // TODO: Maybe this should be valid for SMS/MMS
        if ((ap.getParameterMask() & MASK_CONVERSATION_NAME) != 0) {
            if (fi.mMsgType == FilterInfo.TYPE_IM) {
                String threadName = c.getString(fi.mMessageColThreadName);
                e.setThreadName(threadName);
                if (V) Log.d(TAG, "setThreadName: " + threadName + "\n");
            }
        }
    }


    private void setSent(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_SENT) != 0) {
            int msgType = 0;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                msgType = c.getInt(fi.mSmsColFolder);
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                msgType = c.getInt(fi.mMmsColFolder);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                msgType = c.getInt(fi.mMessageColFolder);
            }
            String sent = null;
            if (msgType == 2) {
                sent = "yes";
            } else {
                sent = "no";
            }
            if (V) Log.d(TAG, "setSent: " + sent);
            e.setSent(sent);
        }
    }

    private void setRead(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        int read = 0;
        if (fi.mMsgType == FilterInfo.TYPE_SMS) {
            read = c.getInt(fi.mSmsColRead);
        } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
            read = c.getInt(fi.mMmsColRead);
        } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                   fi.mMsgType == FilterInfo.TYPE_IM) {
            read = c.getInt(fi.mMessageColRead);
        }
        String setread = null;

        if (V) Log.d(TAG, "setRead: " + setread);
        e.setRead((read==1?true:false), ((ap.getParameterMask() & MASK_READ) != 0));
    }
    private void setConvoRead(BluetoothMapConvoListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        String setread = null;
        int read = 0;
            read = c.getInt(fi.mConvoColRead);


        if (V) Log.d(TAG, "setRead: " + setread);
        e.setRead((read==1?true:false), ((ap.getParameterMask() & MASK_READ) != 0));
    }

    private void setPriority(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_PRIORITY) != 0) {
            String priority = "no";
            if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                fi.mMsgType == FilterInfo.TYPE_IM) {
                int highPriority = c.getInt(fi.mMessageColPriority);
                if (highPriority == 1) {
                    priority = "yes";
                }
            }
            int pri = 0;
            if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                pri = c.getInt(c.getColumnIndex(Mms.PRIORITY));
            }
            if (pri == PduHeaders.PRIORITY_HIGH) {
                priority = "yes";
            }
            if (V) Log.d(TAG, "setPriority: " + priority);
            e.setPriority(priority);
        }
    }

    /**
     * For SMS we set the attachment size to 0, as all data will be text data, hence
     * attachments for SMS is not possible.
     * For MMS all data is actually attachments, hence we do set the attachment size to
     * the total message size. To provide a more accurate attachment size, one could
     * extract the length (in bytes) of the text parts.
     */
    private void setAttachment(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_ATTACHMENT_SIZE) != 0) {
            int size = 0;
            String attachmentMimeTypes = null;
            if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                if(c.getInt(fi.mMmsColTextOnly) == 0) {
                    size = c.getInt(fi.mMmsColAttachmentSize);
                    if(size <= 0) {
                        // We know there are attachments, since it is not TextOnly
                        // Hence the size in the database must be wrong.
                        // Set size to 1 to indicate to the client, that attachments are present
                        if (D) Log.d(TAG, "Error in message database, size reported as: " + size
                                + " Changing size to 1");
                        size = 1;
                    }
                    // TODO: Add handling of attachemnt mime types
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
                int attachment = c.getInt(fi.mMessageColAttachment);
                size = c.getInt(fi.mMessageColAttachmentSize);
                if(attachment == 1 && size == 0) {
                    if (D) Log.d(TAG, "Error in message database, attachment size reported as: " + size
                            + " Changing size to 1");
                    size = 1; /* Ensure we indicate we have attachments in the size, if the
                                 message has attachments, in case the e-mail client do not
                                 report a size */
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_IM) {
                int attachment = c.getInt(fi.mMessageColAttachment);
                size = c.getInt(fi.mMessageColAttachmentSize);
                if(attachment == 1 && size == 0) {
                    size = 1; /* Ensure we indicate we have attachments in the size, it the
                                  message has attachments, in case the e-mail client do not
                                  report a size */
                    attachmentMimeTypes =  c.getString(fi.mMessageColAttachmentMime);
                }
            }
            if (V) Log.d(TAG, "setAttachmentSize: " + size + "\n" +
                              "setAttachmentMimeTypes: " + attachmentMimeTypes );
            e.setAttachmentSize(size);

            if( (mMsgListingVersion > BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V10)
                    && ((ap.getParameterMask() & MASK_ATTACHMENT_MIME) != 0) ){
                e.setAttachmentMimeTypes(attachmentMimeTypes);
            }
        }
    }

    private void setText(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_TEXT) != 0) {
            String hasText = "";
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                hasText = "yes";
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                int textOnly = c.getInt(fi.mMmsColTextOnly);
                if (textOnly == 1) {
                    hasText = "yes";
                } else {
                    long id = c.getLong(fi.mMmsColId);
                    String text = getTextPartsMms(mResolver, id);
                    if (text != null && text.length() > 0) {
                        hasText = "yes";
                    } else {
                        hasText = "no";
                    }
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                hasText = "yes";
            }
            if (V) Log.d(TAG, "setText: " + hasText);
            e.setText(hasText);
        }
    }

    private void setReceptionStatus(BluetoothMapMessageListingElement e, Cursor c,
        FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_RECEPTION_STATUS) != 0) {
            String status = "complete";
            if (V) Log.d(TAG, "setReceptionStatus: " + status);
            e.setReceptionStatus(status);
        }
    }

    private void setDeliveryStatus(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_DELIVERY_STATUS) != 0) {
            String deliveryStatus = "delivered";
            // TODO: Should be handled for SMS and MMS as well
            if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                fi.mMsgType == FilterInfo.TYPE_IM) {
                deliveryStatus = c.getString(fi.mMessageColDelivery);
            }
            if (V) Log.d(TAG, "setDeliveryStatus: " + deliveryStatus);
            e.setDeliveryStatus(deliveryStatus);
        }
    }

    private void setSize(BluetoothMapMessageListingElement e, Cursor c,
        FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_SIZE) != 0) {
            int size = 0;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                String subject = c.getString(fi.mSmsColSubject);
                size = subject.length();
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                size = c.getInt(fi.mMmsColSize);
                //MMS complete size = attachment_size + subject length
                String subject = e.getSubject();
                if (subject == null || subject.length() == 0 ) {
                    // Handle setSubject if not done case
                    setSubject(e, c, fi, ap);
                }
                if (subject != null && subject.length() != 0 )
                    size += subject.length();
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                size = c.getInt(fi.mMessageColSize);
            }
            if(size <= 0) {
                // A message cannot have size 0
                // Hence the size in the database must be wrong.
                // Set size to 1 to indicate to the client, that the message has content.
                if (D) Log.d(TAG, "Error in message database, size reported as: " + size
                        + " Changing size to 1");
                size = 1;
            }
            if (V) Log.d(TAG, "setSize: " + size);
            e.setSize(size);
        }
    }

    private TYPE getType(Cursor c, FilterInfo fi) {
        TYPE type = null;
        if (V) Log.d(TAG, "getType: for filterMsgType" + fi.mMsgType);
        if (fi.mMsgType == FilterInfo.TYPE_SMS) {
            if (V) Log.d(TAG, "getType: phoneType for SMS " + fi.mPhoneType);
            if (fi.mPhoneType == TelephonyManager.PHONE_TYPE_CDMA) {
                type = TYPE.SMS_CDMA;
            } else {
                type = TYPE.SMS_GSM;
            }
        } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
            type = TYPE.MMS;
        } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
            type = TYPE.EMAIL;
        } else if (fi.mMsgType == FilterInfo.TYPE_IM) {
            type = TYPE.IM;
        }
        if (V) Log.d(TAG, "getType: " + type);

        return type;
    }
    private void setFolderType(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_FOLDER_TYPE) != 0) {
            String folderType = null;
            int folderId = 0;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                folderId = c.getInt(fi.mSmsColFolder);
                if (folderId == 1)
                    folderType = BluetoothMapContract.FOLDER_NAME_INBOX;
                else if (folderId == 2)
                    folderType = BluetoothMapContract.FOLDER_NAME_SENT;
                else if (folderId == 3)
                    folderType = BluetoothMapContract.FOLDER_NAME_DRAFT;
                else if (folderId == 4 || folderId == 5 || folderId == 6)
                    folderType = BluetoothMapContract.FOLDER_NAME_OUTBOX;
                else
                    folderType = BluetoothMapContract.FOLDER_NAME_DELETED;
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                folderId = c.getInt(fi.mMmsColFolder);
                if (folderId == 1)
                    folderType = BluetoothMapContract.FOLDER_NAME_INBOX;
                else if (folderId == 2)
                    folderType = BluetoothMapContract.FOLDER_NAME_SENT;
                else if (folderId == 3)
                    folderType = BluetoothMapContract.FOLDER_NAME_DRAFT;
                else if (folderId == 4)
                    folderType = BluetoothMapContract.FOLDER_NAME_OUTBOX;
                else
                    folderType = BluetoothMapContract.FOLDER_NAME_DELETED;
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
                // TODO: need to find name from id and then set folder type
            } else if (fi.mMsgType == FilterInfo.TYPE_IM) {
                folderId = c.getInt(fi.mMessageColFolder);
                if (folderId == BluetoothMapContract.FOLDER_ID_INBOX)
                    folderType = BluetoothMapContract.FOLDER_NAME_INBOX;
                else if (folderId == BluetoothMapContract.FOLDER_ID_SENT)
                    folderType = BluetoothMapContract.FOLDER_NAME_SENT;
                else if (folderId == BluetoothMapContract.FOLDER_ID_DRAFT)
                    folderType = BluetoothMapContract.FOLDER_NAME_DRAFT;
                else if (folderId == BluetoothMapContract.FOLDER_ID_OUTBOX)
                    folderType = BluetoothMapContract.FOLDER_NAME_OUTBOX;
                else if (folderId == BluetoothMapContract.FOLDER_ID_DELETED)
                    folderType = BluetoothMapContract.FOLDER_NAME_DELETED;
                else
                    folderType = BluetoothMapContract.FOLDER_NAME_OTHER;
            }
            if (V) Log.d(TAG, "setFolderType: " + folderType);
            e.setFolderType(folderType);
        }
    }

 private String getRecipientNameEmail(BluetoothMapMessageListingElement e,
                                      Cursor c,
                                      FilterInfo fi) {

        String toAddress, ccAddress, bccAddress;
        toAddress = c.getString(fi.mMessageColToAddress);
        ccAddress = c.getString(fi.mMessageColCcAddress);
        bccAddress = c.getString(fi.mMessageColBccAddress);

        StringBuilder sb = new StringBuilder();
        if (toAddress != null) {
            Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(toAddress);
            if (tokens.length != 0) {
                if(D) Log.d(TAG, "toName count= " + tokens.length);
                int i = 0;
                boolean first = true;
                while (i < tokens.length) {
                    if(V) Log.d(TAG, "ToName = " + tokens[i].toString());
                    String name = tokens[i].getName();
                    if(!first) sb.append("; "); //Delimiter
                    sb.append(name);
                    first = false;
                    i++;
                }
            }

            if (ccAddress != null) {
                sb.append("; ");
            }
        }
        if (ccAddress != null) {
            Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(ccAddress);
            if (tokens.length != 0) {
                if(D) Log.d(TAG, "ccName count= " + tokens.length);
                int i = 0;
                boolean first = true;
                while (i < tokens.length) {
                    if(V) Log.d(TAG, "ccName = " + tokens[i].toString());
                    String name = tokens[i].getName();
                    if(!first) sb.append("; "); //Delimiter
                    sb.append(name);
                    first = false;
                    i++;
                }
            }
            if (bccAddress != null) {
                sb.append("; ");
            }
        }
        if (bccAddress != null) {
            Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(bccAddress);
            if (tokens.length != 0) {
                if(D) Log.d(TAG, "bccName count= " + tokens.length);
                int i = 0;
                boolean first = true;
                while (i < tokens.length) {
                    if(V) Log.d(TAG, "bccName = " + tokens[i].toString());
                    String name = tokens[i].getName();
                    if(!first) sb.append("; "); //Delimiter
                    sb.append(name);
                    first = false;
                    i++;
                }
            }
        }
        return sb.toString();
    }

    private String getRecipientAddressingEmail(BluetoothMapMessageListingElement e,
                                               Cursor c,
                                               FilterInfo fi) {
        String toAddress, ccAddress, bccAddress;
        toAddress = c.getString(fi.mMessageColToAddress);
        ccAddress = c.getString(fi.mMessageColCcAddress);
        bccAddress = c.getString(fi.mMessageColBccAddress);

        StringBuilder sb = new StringBuilder();
        if (toAddress != null) {
            Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(toAddress);
            if (tokens.length != 0) {
                if(D) Log.d(TAG, "toAddress count= " + tokens.length);
                int i = 0;
                boolean first = true;
                while (i < tokens.length) {
                    if(V) Log.d(TAG, "ToAddress = " + tokens[i].toString());
                    String email = tokens[i].getAddress();
                    if(!first) sb.append("; "); //Delimiter
                    sb.append(email);
                    first = false;
                    i++;
                }
            }

            if (ccAddress != null) {
                sb.append("; ");
            }
        }
        if (ccAddress != null) {
            Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(ccAddress);
            if (tokens.length != 0) {
                if(D) Log.d(TAG, "ccAddress count= " + tokens.length);
                int i = 0;
                boolean first = true;
                while (i < tokens.length) {
                    if(V) Log.d(TAG, "ccAddress = " + tokens[i].toString());
                    String email = tokens[i].getAddress();
                    if(!first) sb.append("; "); //Delimiter
                    sb.append(email);
                    first = false;
                    i++;
                }
            }
            if (bccAddress != null) {
                sb.append("; ");
            }
        }
        if (bccAddress != null) {
            Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(bccAddress);
            if (tokens.length != 0) {
                if(D) Log.d(TAG, "bccAddress count= " + tokens.length);
                int i = 0;
                boolean first = true;
                while (i < tokens.length) {
                    if(V) Log.d(TAG, "bccAddress = " + tokens[i].toString());
                    String email = tokens[i].getAddress();
                    if(!first) sb.append("; "); //Delimiter
                    sb.append(email);
                    first = false;
                    i++;
                }
            }
        }
        return sb.toString();
    }

    private void setRecipientAddressing(BluetoothMapMessageListingElement e, Cursor c,
        FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_RECIPIENT_ADDRESSING) != 0) {
            String address = null;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                int msgType = c.getInt(fi.mSmsColType);
                if (msgType == Sms.MESSAGE_TYPE_INBOX ) {
                    address = fi.mPhoneNum;
                } else {
                    address = c.getString(c.getColumnIndex(Sms.ADDRESS));
                }
                if ((address == null) && msgType == Sms.MESSAGE_TYPE_DRAFT) {
                    //Fetch address for Drafts folder from "canonical_address" table
                    int threadIdInd = c.getColumnIndex(Sms.THREAD_ID);
                    String threadIdStr = c.getString(threadIdInd);
                    address = getCanonicalAddressSms(mResolver, Integer.valueOf(threadIdStr));
                    if(V)  Log.v(TAG, "threadId = " + threadIdStr + " adress:" + address +"\n");
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
                address = getAddressMms(mResolver, id, MMS_TO);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
                /* Might be another way to handle addresses */
                address = getRecipientAddressingEmail(e, c,fi);
            }
            if (V) Log.v(TAG, "setRecipientAddressing: " + address);
            if(address == null)
                address = "";
            e.setRecipientAddressing(address);
        }
    }

    private void setRecipientName(BluetoothMapMessageListingElement e, Cursor c,
        FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_RECIPIENT_NAME) != 0) {
            String name = null;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                int msgType = c.getInt(fi.mSmsColType);
                if (msgType != 1) {
                    String phone = c.getString(fi.mSmsColAddress);
                    if (phone != null && !phone.isEmpty())
                        name = getContactNameFromPhone(phone, mResolver);
                } else {
                    name = fi.mPhoneAlphaTag;
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                long id = c.getLong(fi.mMmsColId);
                String phone;
                if(e.getRecipientAddressing() != null){
                    phone = getAddressMms(mResolver, id, MMS_TO);
                } else {
                    phone = e.getRecipientAddressing();
                }
                if (phone != null && !phone.isEmpty())
                    name = getContactNameFromPhone(phone, mResolver);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
                /* Might be another way to handle address and names */
                name = getRecipientNameEmail(e,c,fi);
            }
            if (V) Log.v(TAG, "setRecipientName: " + name);
            if(name == null)
                name = "";
            e.setRecipientName(name);
        }
    }

    private void setSenderAddressing(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_SENDER_ADDRESSING) != 0) {
            String address = "";
            String tempAddress;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                int msgType = c.getInt(fi.mSmsColType);
                if (msgType == 1) { // INBOX
                    tempAddress = c.getString(fi.mSmsColAddress);
                } else {
                    tempAddress = fi.mPhoneNum;
                }
                if(tempAddress == null) {
                    /* This can only happen on devices with no SIM -
                       hence will typically not have any SMS messages. */
                } else {
                    address = PhoneNumberUtils.extractNetworkPortion(tempAddress);
                    /* extractNetworkPortion can return N if the number is a service "number" =
                     * a string with the a name in (i.e. "Some-Tele-company" would return N
                     * because of the N in compaNy)
                     * Hence we need to check if the number is actually a string with alpha chars.
                     * */
                    Boolean alpha = PhoneNumberUtils.stripSeparators(tempAddress).matches(
                            "[0-9]*[a-zA-Z]+[0-9]*");

                    if(address == null || address.length() < 2 || alpha) {
                        address = tempAddress; // if the number is a service acsii text just use it
                    }
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                long id = c.getLong(fi.mMmsColId);
                tempAddress = getAddressMms(mResolver, id, MMS_FROM);
                address = PhoneNumberUtils.extractNetworkPortion(tempAddress);
                if(address == null || address.length() < 1){
                    address = tempAddress; // if the number is a service acsii text just use it
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL/* ||
                       fi.mMsgType == FilterInfo.TYPE_IM*/) {
                String nameEmail = c.getString(fi.mMessageColFromAddress);
                Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(nameEmail);
                if (tokens.length != 0) {
                    if(D) Log.d(TAG, "Originator count= " + tokens.length);
                    int i = 0;
                    boolean first = true;
                    while (i < tokens.length) {
                        if(V) Log.d(TAG, "SenderAddress = " + tokens[i].toString());
                        String[] emails = new String[1];
                        emails[0] = tokens[i].getAddress();
                        String name = tokens[i].getName();
                        if(!first) address += "; "; //Delimiter
                        address += emails[0];
                        first = false;
                        i++;
                    }
                }
            } else if(fi.mMsgType == FilterInfo.TYPE_IM) {
                // TODO: For IM we add the contact ID in the addressing
                long contact_id = c.getLong(fi.mMessageColFromAddress);
                // TODO: This is a BAD hack, that we map the contact ID to a conversation ID!!!
                //       We need to reach a conclusion on what to do
                Uri contactsUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_CONVOCONTACT);
                Cursor contacts = mResolver.query(contactsUri,
                                           BluetoothMapContract.BT_CONTACT_PROJECTION,
                                           BluetoothMapContract.ConvoContactColumns.CONVO_ID
                                           + " = " + contact_id, null, null);
                try {
                    // TODO this will not work for group-chats
                    if(contacts != null && contacts.moveToFirst()){
                        address = contacts.getString(
                                contacts.getColumnIndex(
                                        BluetoothMapContract.ConvoContactColumns.UCI));
                    }
                } finally {
                    if (contacts != null) contacts.close();
                }

            }
            if (V) Log.v(TAG, "setSenderAddressing: " + address);
            if(address == null)
                address = "";
            e.setSenderAddressing(address);
        }
    }

    private void setSenderName(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_SENDER_NAME) != 0) {
            String name = "";
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                int msgType = c.getInt(c.getColumnIndex(Sms.TYPE));
                if (msgType == 1) {
                    String phone = c.getString(fi.mSmsColAddress);
                    if (phone != null && !phone.isEmpty())
                        name = getContactNameFromPhone(phone, mResolver);
                } else {
                    name = fi.mPhoneAlphaTag;
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                long id = c.getLong(fi.mMmsColId);
                String phone;
                if(e.getSenderAddressing() != null){
                    phone = getAddressMms(mResolver, id, MMS_FROM);
                } else {
                    phone = e.getSenderAddressing();
                }
                if (phone != null && !phone.isEmpty() )
                    name = getContactNameFromPhone(phone, mResolver);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL/*  ||
                       fi.mMsgType == FilterInfo.TYPE_IM*/) {
                String nameEmail = c.getString(fi.mMessageColFromAddress);
                Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(nameEmail);
                if (tokens.length != 0) {
                    if(D) Log.d(TAG, "Originator count= " + tokens.length);
                    int i = 0;
                    boolean first = true;
                    while (i < tokens.length) {
                        if(V) Log.d(TAG, "senderName = " + tokens[i].toString());
                        String[] emails = new String[1];
                        emails[0] = tokens[i].getAddress();
                        String nameIn = tokens[i].getName();
                        if(!first) name += "; "; //Delimiter
                        name += nameIn;
                        first = false;
                        i++;
                    }
                }
            } else if(fi.mMsgType == FilterInfo.TYPE_IM) {
                // For IM we add the contact ID in the addressing
                long contact_id = c.getLong(fi.mMessageColFromAddress);
                Uri contactsUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_CONVOCONTACT);
                Cursor contacts = mResolver.query(contactsUri,
                                           BluetoothMapContract.BT_CONTACT_PROJECTION,
                                           BluetoothMapContract.ConvoContactColumns.CONVO_ID
                                           + " = " + contact_id, null, null);
                try {
                    // TODO this will not work for group-chats
                    if(contacts != null && contacts.moveToFirst()){
                        name = contacts.getString(
                                contacts.getColumnIndex(
                                        BluetoothMapContract.ConvoContactColumns.NAME));
                    }
                } finally {
                    if (contacts != null) contacts.close();
                }
            }
            if (V) Log.v(TAG, "setSenderName: " + name);
            if(name == null)
                name = "";
            e.setSenderName(name);
        }
    }




    private void setDateTime(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        if ((ap.getParameterMask() & MASK_DATETIME) != 0) {
            long date = 0;
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                date = c.getLong(fi.mSmsColDate);
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                /* Use Mms.DATE for all messages. Although contract class states */
                /* Mms.DATE_SENT are for outgoing messages. But that is not working. */
                date = c.getLong(fi.mMmsColDate) * 1000L;

                /* int msgBox = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX)); */
                /* if (msgBox == Mms.MESSAGE_BOX_INBOX) { */
                /*     date = c.getLong(c.getColumnIndex(Mms.DATE)) * 1000L; */
                /* } else { */
                /*     date = c.getLong(c.getColumnIndex(Mms.DATE_SENT)) * 1000L; */
                /* } */
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                date = c.getLong(fi.mMessageColDate);
            }
            e.setDateTime(date);
        }
    }


    private void setLastActivity(BluetoothMapConvoListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        long date = 0;
        if (fi.mMsgType == FilterInfo.TYPE_SMS ||
                fi.mMsgType == FilterInfo.TYPE_MMS ) {
            date = c.getLong(MMS_SMS_THREAD_COL_DATE);
        } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL||
                fi.mMsgType == FilterInfo.TYPE_IM) {
            date = c.getLong(fi.mConvoColLastActivity);
        }
        e.setLastActivity(date);
        if (V) Log.v(TAG, "setDateTime: " + e.getLastActivityString());

    }

    static public String getTextPartsMms(ContentResolver r, long id) {
        String text = "";
        String selection = new String("mid=" + id);
        String uriStr = new String(Mms.CONTENT_URI + "/" + id + "/part");
        Uri uriAddress = Uri.parse(uriStr);
        // TODO: maybe use a projection with only "ct" and "text"
        Cursor c = r.query(uriAddress, null, selection,
            null, null);
        try {
            if (c != null && c.moveToFirst()) {
                do {
                    String ct = c.getString(c.getColumnIndex("ct"));
                    if (ct.equals("text/plain")) {
                        String part = c.getString(c.getColumnIndex("text"));
                        if(part != null) {
                            text += part;
                        }
                    }
                } while(c.moveToNext());
            }
        } finally {
            if (c != null) c.close();
        }

        return text;
    }

    private void setSubject(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        String subject = "";
        int subLength = ap.getSubjectLength();
        if(subLength == BluetoothMapAppParams.INVALID_VALUE_PARAMETER)
            subLength = 256;
        //Fix Subject Display issue with HONDA Carkit - Ignore subject Mask.
        if (BluetoothMapService.getRemoteDevice().getAddress().startsWith(HONDA_CARKIT) ||
                         (ap.getParameterMask() & MASK_SUBJECT) != 0) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                subject = c.getString(fi.mSmsColSubject);
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                subject = c.getString(fi.mMmsColSubject);
                if (subject == null || subject.length() == 0) {
                    /* Get subject from mms text body parts - if any exists */
                    long id = c.getLong(fi.mMmsColId);
                    subject = getTextPartsMms(mResolver, id);
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL  ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                subject = c.getString(fi.mMessageColSubject);
            }
            if (subject != null && subject.length() > subLength) {
                subject = subject.substring(0, subLength);
            } else if (subject == null ) {
                subject = "";
            }
            if (V) Log.d(TAG, "setSubject: " + subject);
            e.setSubject(subject);
        }
    }

    private void setHandle(BluetoothMapMessageListingElement e, Cursor c,
            FilterInfo fi, BluetoothMapAppParams ap) {
        long handle = -1;
        if (fi.mMsgType == FilterInfo.TYPE_SMS) {
            handle = c.getLong(fi.mSmsColId);
        } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
            handle = c.getLong(fi.mMmsColId);
        } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                   fi.mMsgType == FilterInfo.TYPE_IM) {
            handle = c.getLong(fi.mMessageColId);
        }
        if (V) Log.d(TAG, "setHandle: " + handle );
        e.setHandle(handle);
    }

    private BluetoothMapMessageListingElement element(Cursor c, FilterInfo fi,
            BluetoothMapAppParams ap) {
        BluetoothMapMessageListingElement e = new BluetoothMapMessageListingElement();
        setHandle(e, c, fi, ap);
        setDateTime(e, c, fi, ap);
        e.setType(getType(c, fi), ((ap.getParameterMask() & MASK_TYPE) != 0) ? true : false);
        setRead(e, c, fi, ap);
        // we set number and name for sender/recipient later
        // they require lookup on contacts so no need to
        // do it for all elements unless they are to be used.
        e.setCursorIndex(c.getPosition());
        return e;
    }

    private BluetoothMapConvoListingElement createConvoElement(Cursor c, FilterInfo fi,
            BluetoothMapAppParams ap) {
        BluetoothMapConvoListingElement e = new BluetoothMapConvoListingElement();
        setLastActivity(e, c, fi, ap);
        e.setType(getType(c, fi));
//        setConvoRead(e, c, fi, ap);
        e.setCursorIndex(c.getPosition());
        return e;
    }

    /* TODO: Change to use SmsMmsContacts.getContactNameFromPhone() with proper use of
     *       caching. */
    public static String getContactNameFromPhone(String phone, ContentResolver resolver) {
        String name = null;
        //Handle possible exception for empty phone address
        if (TextUtils.isEmpty(phone)) {
            return name;
        }

        Uri uri = Uri.withAppendedPath(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI,
                Uri.encode(phone));

        String[] projection = {Contacts._ID, Contacts.DISPLAY_NAME};
        String selection = Contacts.IN_VISIBLE_GROUP + "=1";
        String orderBy = Contacts.DISPLAY_NAME + " ASC";
        Cursor c = null;
        try {
            c = resolver.query(uri, projection, selection, null, orderBy);
            if(c != null) {
                int colIndex = c.getColumnIndex(Contacts.DISPLAY_NAME);
                if (c.getCount() >= 1) {
                    c.moveToFirst();
                    name = c.getString(colIndex);
                }
            }
        } finally {
            if(c != null) c.close();
        }
        return name;
    }
    /**
     * Get SMS RecipientAddresses for DRAFT folder based on threadId
     *
    */
    static public String getCanonicalAddressSms(ContentResolver r,  int threadId) {
       String [] RECIPIENT_ID_PROJECTION = { Threads.RECIPIENT_IDS };
        /*
         1. Get Recipient Ids from Threads.CONTENT_URI
         2. Get Recipient Address for corresponding Id from canonical-addresses table.
        */

        //Uri sAllCanonical = Uri.parse("content://mms-sms/canonical-addresses");
        Uri sAllCanonical =
                MmsSms.CONTENT_URI.buildUpon().appendPath("canonical-addresses").build();
        Uri sAllThreadsUri =
                Threads.CONTENT_URI.buildUpon().appendQueryParameter("simple", "true").build();
        Cursor cr = null;
        String recipientAddress = "";
        String recipientIds = null;
        String whereClause = "_id="+threadId;
        if (V) Log.v(TAG, "whereClause is "+ whereClause);
        try {
            cr = r.query(sAllThreadsUri, RECIPIENT_ID_PROJECTION, whereClause, null, null);
            if (cr != null && cr.moveToFirst()) {
                recipientIds = cr.getString(0);
                if (V) Log.v(TAG, "cursor.getCount(): " + cr.getCount() + "recipientIds: "
                        + recipientIds + "selection: "+ whereClause );
            }
        } finally {
            if(cr != null) {
                cr.close();
                cr = null;
            }
        }
        if (V) Log.v(TAG, "recipientIds with spaces: "+ recipientIds +"\n");
        if(recipientIds != null) {
            String recipients[] = null;
            whereClause = "";
            recipients = recipientIds.split(" ");
            for (String id: recipients) {
                if(whereClause.length() != 0)
                    whereClause +=" OR ";
                whereClause +="_id="+id;
            }
            if (V) Log.v(TAG, "whereClause is "+ whereClause);
            try {
                cr = r.query(sAllCanonical , null, whereClause, null, null);
                if (cr != null && cr.moveToFirst()) {
                    do {
                        //TODO: Multiple Recipeints are appended with ";" for now.
                        if(recipientAddress.length() != 0 )
                           recipientAddress+=";";
                        recipientAddress += cr.getString(
                                cr.getColumnIndex(CanonicalAddressesColumns.ADDRESS));
                    } while(cr.moveToNext());
                }
           } finally {
               if(cr != null)
                   cr.close();
           }
        }

        if(V) Log.v(TAG,"Final recipientAddress : "+ recipientAddress);
        return recipientAddress;
     }

    static public String getAddressMms(ContentResolver r, long id, int type) {
        String selection = new String("msg_id=" + id + " AND type=" + type);
        String uriStr = new String(Mms.CONTENT_URI + "/" + id + "/addr");
        Uri uriAddress = Uri.parse(uriStr);
        String addr = null;
        String[] projection = {Mms.Addr.ADDRESS};
        Cursor c = null;
        try {
            c = r.query(uriAddress, projection, selection, null, null); // TODO: Add projection
            int colIndex = c.getColumnIndex(Mms.Addr.ADDRESS);
            if (c != null) {
                if(c.moveToFirst()) {
                    addr = c.getString(colIndex);
                    if(addr.equals(INSERT_ADDRES_TOKEN)) {
                        addr  = "";
                    }
                }
            }
        } finally {
            if (c != null) c.close();
        }
        return addr;
    }

    /**
     * Matching functions for originator and recipient for MMS
     * @return true if found a match
     */
    private boolean matchRecipientMms(Cursor c, FilterInfo fi, String recip) {
        boolean res;
        long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
        String phone = getAddressMms(mResolver, id, MMS_TO);
        if (phone != null && phone.length() > 0) {
            if (phone.matches(recip)) {
                if (V) Log.v(TAG, "matchRecipientMms: match recipient phone = " + phone);
                res = true;
            } else {
                String name = getContactNameFromPhone(phone, mResolver);
                if (name != null && name.length() > 0 && name.matches(recip)) {
                    if (V) Log.v(TAG, "matchRecipientMms: match recipient name = " + name);
                    res = true;
                } else {
                    res = false;
                }
            }
        } else {
            res = false;
        }
        return res;
    }

    private boolean matchRecipientSms(Cursor c, FilterInfo fi, String recip) {
        boolean res;
        int msgType = c.getInt(c.getColumnIndex(Sms.TYPE));
        if (msgType == 1) {
            String phone = fi.mPhoneNum;
            String name = fi.mPhoneAlphaTag;
            if (phone != null && phone.length() > 0 && phone.matches(recip)) {
                if (V) Log.v(TAG, "matchRecipientSms: match recipient phone = " + phone);
                res = true;
            } else if (name != null && name.length() > 0 && name.matches(recip)) {
                if (V) Log.v(TAG, "matchRecipientSms: match recipient name = " + name);
                res = true;
            } else {
                res = false;
            }
        } else {
            String phone = c.getString(c.getColumnIndex(Sms.ADDRESS));
            if (phone != null && phone.length() > 0) {
                if (phone.matches(recip)) {
                    if (V) Log.v(TAG, "matchRecipientSms: match recipient phone = " + phone);
                    res = true;
                } else {
                    String name = getContactNameFromPhone(phone, mResolver);
                    if (name != null && name.length() > 0 && name.matches(recip)) {
                        if (V) Log.v(TAG, "matchRecipientSms: match recipient name = " + name);
                        res = true;
                    } else {
                        res = false;
                    }
                }
            } else {
                res = false;
            }
        }
        return res;
    }

    private boolean matchRecipient(Cursor c, FilterInfo fi, BluetoothMapAppParams ap) {
        boolean res;
        String recip = ap.getFilterRecipient();
        if (recip != null && recip.length() > 0) {
            recip = recip.replace("*", ".*");
            recip = ".*" + recip + ".*";
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                res = matchRecipientSms(c, fi, recip);
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                res = matchRecipientMms(c, fi, recip);
            } else {
                if (D) Log.d(TAG, "matchRecipient: Unknown msg type: " + fi.mMsgType);
                res = false;
            }
        } else {
            res = true;
        }
        return res;
    }

    private boolean matchOriginatorMms(Cursor c, FilterInfo fi, String orig) {
        boolean res;
        long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
        String phone = getAddressMms(mResolver, id, MMS_FROM);
        if (phone != null && phone.length() > 0) {
            if (phone.matches(orig)) {
                if (V) Log.v(TAG, "matchOriginatorMms: match originator phone = " + phone);
                res = true;
            } else {
                String name = getContactNameFromPhone(phone, mResolver);
                if (name != null && name.length() > 0 && name.matches(orig)) {
                    if (V) Log.v(TAG, "matchOriginatorMms: match originator name = " + name);
                    res = true;
                } else {
                    res = false;
                }
            }
        } else {
            res = false;
        }
        return res;
    }

    private boolean matchOriginatorSms(Cursor c, FilterInfo fi, String orig) {
        boolean res;
        int msgType = c.getInt(c.getColumnIndex(Sms.TYPE));
        if (msgType == 1) {
            String phone = c.getString(c.getColumnIndex(Sms.ADDRESS));
            if (phone !=null && phone.length() > 0) {
                if (phone.matches(orig)) {
                    if (V) Log.v(TAG, "matchOriginatorSms: match originator phone = " + phone);
                    res = true;
                } else {
                    String name = getContactNameFromPhone(phone, mResolver);
                    if (name != null && name.length() > 0 && name.matches(orig)) {
                        if (V) Log.v(TAG, "matchOriginatorSms: match originator name = " + name);
                        res = true;
                    } else {
                        res = false;
                    }
                }
            } else {
                res = false;
            }
        } else {
            String phone = fi.mPhoneNum;
            String name = fi.mPhoneAlphaTag;
            if (phone != null && phone.length() > 0 && phone.matches(orig)) {
                if (V) Log.v(TAG, "matchOriginatorSms: match originator phone = " + phone);
                res = true;
            } else if (name != null && name.length() > 0 && name.matches(orig)) {
                if (V) Log.v(TAG, "matchOriginatorSms: match originator name = " + name);
                res = true;
            } else {
                res = false;
            }
        }
        return res;
    }

   private boolean matchOriginator(Cursor c, FilterInfo fi, BluetoothMapAppParams ap) {
        boolean res;
        String orig = ap.getFilterOriginator();
        if (orig != null && orig.length() > 0) {
            orig = orig.replace("*", ".*");
            orig = ".*" + orig + ".*";
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                res = matchOriginatorSms(c, fi, orig);
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                res = matchOriginatorMms(c, fi, orig);
            } else {
                if(D) Log.d(TAG, "matchOriginator: Unknown msg type: " + fi.mMsgType);
                res = false;
            }
        } else {
            res = true;
        }
        return res;
    }

    private boolean matchAddresses(Cursor c, FilterInfo fi, BluetoothMapAppParams ap) {
        if (matchOriginator(c, fi, ap) && matchRecipient(c, fi, ap)) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * Where filter functions
     * */
    private String setWhereFilterFolderTypeSms(String folder) {
        String where = "";
        if (BluetoothMapContract.FOLDER_NAME_INBOX.equalsIgnoreCase(folder)) {
            where = Sms.TYPE + " = 1 AND " + Sms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_OUTBOX.equalsIgnoreCase(folder)) {
            where = "(" + Sms.TYPE + " = 4 OR " + Sms.TYPE + " = 5 OR "
                    + Sms.TYPE + " = 6) AND " + Sms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_SENT.equalsIgnoreCase(folder)) {
            where = Sms.TYPE + " = 2 AND " + Sms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_DRAFT.equalsIgnoreCase(folder)) {
            where = Sms.TYPE + " = 3 AND " + Sms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_DELETED.equalsIgnoreCase(folder)) {
            where = Sms.THREAD_ID + " = -1";
        }

        return where;
    }

    private String setWhereFilterFolderTypeMms(String folder) {
        String where = "";
        if (BluetoothMapContract.FOLDER_NAME_INBOX.equalsIgnoreCase(folder)) {
            where = Mms.MESSAGE_BOX + " = 1 AND " + Mms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_OUTBOX.equalsIgnoreCase(folder)) {
            where = Mms.MESSAGE_BOX + " = 4 AND " + Mms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_SENT.equalsIgnoreCase(folder)) {
            where = Mms.MESSAGE_BOX + " = 2 AND " + Mms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_DRAFT.equalsIgnoreCase(folder)) {
            where = Mms.MESSAGE_BOX + " = 3 AND " + Mms.THREAD_ID + " <> -1";
        } else if (BluetoothMapContract.FOLDER_NAME_DELETED.equalsIgnoreCase(folder)) {
            where = Mms.THREAD_ID + " = -1";
        }

        return where;
    }

    private String setWhereFilterFolderTypeEmail(long folderId) {
        String where = "";
        if (folderId >= 0) {
            where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + folderId;
        } else {
            Log.e(TAG, "setWhereFilterFolderTypeEmail: not valid!" );
            throw new IllegalArgumentException("Invalid folder ID");
        }
        return where;
    }

    private String setWhereFilterFolderTypeIm(long folderId) {
        String where = "";
        if (folderId > BluetoothMapContract.FOLDER_ID_OTHER) {
            where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + folderId;
        } else {
            Log.e(TAG, "setWhereFilterFolderTypeIm: not valid!" );
            throw new IllegalArgumentException("Invalid folder ID");
        }
        return where;
    }

    private String setWhereFilterFolderType(BluetoothMapFolderElement folderElement,
                                            FilterInfo fi) {
        String where = "";
        if(folderElement.shouldIgnore()) {
            where = "1=1";
        } else {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                where = setWhereFilterFolderTypeSms(folderElement.getName());
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where = setWhereFilterFolderTypeMms(folderElement.getName());
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
                where = setWhereFilterFolderTypeEmail(folderElement.getFolderId());
            } else if (fi.mMsgType == FilterInfo.TYPE_IM) {
                where = setWhereFilterFolderTypeIm(folderElement.getFolderId());
            }
        }
        return where;
    }

    private String setWhereFilterReadStatus(BluetoothMapAppParams ap, FilterInfo fi) {
        String where = "";
        if (ap.getFilterReadStatus() != -1) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                if ((ap.getFilterReadStatus() & 0x01) != 0) {
                    where = " AND " + Sms.READ + "= 0";
                }

                if ((ap.getFilterReadStatus() & 0x02) != 0) {
                    where = " AND " + Sms.READ + "= 1";
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                if ((ap.getFilterReadStatus() & 0x01) != 0) {
                    where = " AND " + Mms.READ + "= 0";
                }

                if ((ap.getFilterReadStatus() & 0x02) != 0) {
                    where = " AND " + Mms.READ + "= 1";
                }
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                if ((ap.getFilterReadStatus() & 0x01) != 0) {
                    where = " AND " + BluetoothMapContract.MessageColumns.FLAG_READ + "= 0";
                }
                if ((ap.getFilterReadStatus() & 0x02) != 0) {
                    where = " AND " + BluetoothMapContract.MessageColumns.FLAG_READ + "= 1";
                }
            }
        }
        return where;
    }

    private String setWhereFilterPeriod(BluetoothMapAppParams ap, FilterInfo fi) {
        String where = "";

        if ((ap.getFilterPeriodBegin() != -1)) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                where = " AND " + Sms.DATE + " >= " + ap.getFilterPeriodBegin();
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where = " AND " + Mms.DATE + " >= " + (ap.getFilterPeriodBegin() / 1000L);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                where = " AND " + BluetoothMapContract.MessageColumns.DATE +
                        " >= " + (ap.getFilterPeriodBegin());
            }
        }

        if ((ap.getFilterPeriodEnd() != -1)) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                where += " AND " + Sms.DATE + " < " + ap.getFilterPeriodEnd();
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where += " AND " + Mms.DATE + " < " + (ap.getFilterPeriodEnd() / 1000L);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                where += " AND " + BluetoothMapContract.MessageColumns.DATE +
                        " < " + (ap.getFilterPeriodEnd());
            }
        }
        return where;
    }
    private String setWhereFilterLastActivity(BluetoothMapAppParams ap, FilterInfo fi) {
            String where = "";
        if ((ap.getFilterLastActivityBegin() != -1)) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                where = " AND " + Sms.DATE + " >= " + ap.getFilterLastActivityBegin();
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where = " AND " + Mms.DATE + " >= " + (ap.getFilterLastActivityBegin() / 1000L);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL||
                      fi.mMsgType == FilterInfo.TYPE_IM ) {
                where = " AND " + BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY +
                        " >= " + (ap.getFilterPeriodBegin());
            }
        }
        if ((ap.getFilterLastActivityEnd() != -1)) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
                where += " AND " + Sms.DATE + " < " + ap.getFilterLastActivityEnd();
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where += " AND " + Mms.DATE + " < " + (ap.getFilterPeriodEnd() / 1000L);
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL||fi.mMsgType == FilterInfo.TYPE_IM) {
                where += " AND " + BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY
                      + " < " + (ap.getFilterLastActivityEnd());
            }
        }
        return where;
    }


    private String setWhereFilterOriginatorEmail(BluetoothMapAppParams ap) {
        String where = "";
        String orig = ap.getFilterOriginator();

        /* Be aware of wild cards in the beginning of string, may not be valid? */
        if (orig != null && orig.length() > 0) {
            orig = orig.replace("*", "%");
            where = " AND " + BluetoothMapContract.MessageColumns.FROM_LIST
                    + " LIKE '%" +  orig + "%'";
        }
        return where;
    }

    private String setWhereFilterOriginatorIM(BluetoothMapAppParams ap) {
        String where = "";
        String orig = ap.getFilterOriginator();

        /* Be aware of wild cards in the beginning of string, may not be valid? */
        if (orig != null && orig.length() > 0) {
            orig = orig.replace("*", "%");
            where = " AND " + BluetoothMapContract.MessageColumns.FROM_LIST
                    + " LIKE '%" +  orig + "%'";
        }
        return where;
    }

    private String setWhereFilterPriority(BluetoothMapAppParams ap, FilterInfo fi) {
        String where = "";
        int pri = ap.getFilterPriority();
        /*only MMS have priority info */
        if(fi.mMsgType == FilterInfo.TYPE_MMS)
        {
            if(pri == 0x0002)
            {
                where += " AND " + Mms.PRIORITY + "<=" +
                    Integer.toString(PduHeaders.PRIORITY_NORMAL);
            }else if(pri == 0x0001) {
                where += " AND " + Mms.PRIORITY + "=" +
                    Integer.toString(PduHeaders.PRIORITY_HIGH);
            }
        }
        if(fi.mMsgType == FilterInfo.TYPE_EMAIL ||
           fi.mMsgType == FilterInfo.TYPE_IM)
        {
            if(pri == 0x0002)
            {
                where += " AND " + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY + "!=1";
            }else if(pri == 0x0001) {
                where += " AND " + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY + "=1";
            }
        }
        // TODO: no priority filtering in IM
        return where;
    }

    private String setWhereFilterRecipientEmail(BluetoothMapAppParams ap) {
        String where = "";
        String recip = ap.getFilterRecipient();

        /* Be aware of wild cards in the beginning of string, may not be valid? */
        if (recip != null && recip.length() > 0) {
            recip = recip.replace("*", "%");
            where = " AND ("
            + BluetoothMapContract.MessageColumns.TO_LIST  + " LIKE '%" + recip + "%' OR "
            + BluetoothMapContract.MessageColumns.CC_LIST  + " LIKE '%" + recip + "%' OR "
            + BluetoothMapContract.MessageColumns.BCC_LIST + " LIKE '%" + recip + "%' )";
        }
        return where;
    }

    private String setWhereFilterMessageHandle(BluetoothMapAppParams ap, FilterInfo fi) {
        String where = "";
        long id = -1;
        String msgHandle = ap.getFilterMsgHandleString();
        if(msgHandle != null) {
            id = BluetoothMapUtils.getCpHandle(msgHandle);
            if(D)Log.d(TAG,"id: " + id);
        }
        if(id != -1) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
               where = " AND " + Sms._ID + " = " + id;
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where = " AND " + Mms._ID + " = " + id;
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                where = " AND " + BluetoothMapContract.MessageColumns._ID + " = " + id;
            }
        }
        return where;
    }

    private String setWhereFilterThreadId(BluetoothMapAppParams ap, FilterInfo fi) {
        String where = "";
        long id = -1;
        String msgHandle = ap.getFilterConvoIdString();
        if(msgHandle != null) {
            id = BluetoothMapUtils.getMsgHandleAsLong(msgHandle);
            if(D)Log.d(TAG,"id: " + id);
        }
        if(id > 0) {
            if (fi.mMsgType == FilterInfo.TYPE_SMS) {
               where = " AND " + Sms.THREAD_ID + " = " + id;
            } else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
                where = " AND " + Mms.THREAD_ID + " = " + id;
            } else if (fi.mMsgType == FilterInfo.TYPE_EMAIL ||
                       fi.mMsgType == FilterInfo.TYPE_IM) {
                where = " AND " + BluetoothMapContract.MessageColumns.THREAD_ID + " = " + id;
            }
        }

        return where;
    }

    private String setWhereFilter(BluetoothMapFolderElement folderElement,
            FilterInfo fi, BluetoothMapAppParams ap) {
        String where = "";
        where += setWhereFilterFolderType(folderElement, fi);

        String msgHandleWhere = setWhereFilterMessageHandle(ap, fi);
        /* if message handle filter is available, the other filters should be ignored */
        if(msgHandleWhere.isEmpty()) {
            where += setWhereFilterReadStatus(ap, fi);
            where += setWhereFilterPriority(ap,fi);
            where += setWhereFilterPeriod(ap, fi);
            if (fi.mMsgType == FilterInfo.TYPE_EMAIL) {
                where += setWhereFilterOriginatorEmail(ap);
                where += setWhereFilterRecipientEmail(ap);
            }
            if (fi.mMsgType == FilterInfo.TYPE_IM) {
                where += setWhereFilterOriginatorIM(ap);
                // TODO: set 'where' filer recipient?
            }
            where += setWhereFilterThreadId(ap, fi);
        } else {
            where += msgHandleWhere;
        }

        return where;
    }


    /* Used only for SMS/MMS */
    private void setConvoWhereFilterSmsMms(StringBuilder selection, ArrayList<String> selectionArgs,
            FilterInfo fi, BluetoothMapAppParams ap) {

        if (smsSelected(fi, ap) || mmsSelected(ap)) {

            // Filter Read Status
            if(ap.getFilterReadStatus() != BluetoothMapAppParams.INVALID_VALUE_PARAMETER) {
                if ((ap.getFilterReadStatus() & FILTER_READ_STATUS_UNREAD_ONLY) != 0) {
                    selection.append(" AND ").append(Threads.READ).append(" = 0");
                }
                if ((ap.getFilterReadStatus() & FILTER_READ_STATUS_READ_ONLY) != 0) {
                    selection.append(" AND ").append(Threads.READ).append(" = 1");
                }
            }

            // Filter time
            if ((ap.getFilterLastActivityBegin() != BluetoothMapAppParams.INVALID_VALUE_PARAMETER)){
                selection.append(" AND ").append(Threads.DATE).append(" >= ")
                .append(ap.getFilterLastActivityBegin());
            }
            if ((ap.getFilterLastActivityEnd() != BluetoothMapAppParams.INVALID_VALUE_PARAMETER)) {
                selection.append(" AND ").append(Threads.DATE).append(" <= ")
                .append(ap.getFilterLastActivityEnd());
            }

            // Filter ConvoId
            long convoId = -1;
            if(ap.getFilterConvoId() != null) {
                convoId = ap.getFilterConvoId().getLeastSignificantBits();
            }
            if(convoId > 0) {
                selection.append(" AND ").append(Threads._ID).append(" = ")
                .append(Long.toString(convoId));
            }
        }
    }



    /**
     * Determine from application parameter if sms should be included.
     * The filter mask is set for message types not selected
     * @param fi
     * @param ap
     * @return boolean true if sms is selected, false if not
     */
    private boolean smsSelected(FilterInfo fi, BluetoothMapAppParams ap) {
        int msgType = ap.getFilterMessageType();
        int phoneType = fi.mPhoneType;

        if (D) Log.d(TAG, "smsSelected msgType: " + msgType);

        if (msgType == BluetoothMapAppParams.INVALID_VALUE_PARAMETER)
            return true;

        if ((msgType & (BluetoothMapAppParams.FILTER_NO_SMS_CDMA
                |BluetoothMapAppParams.FILTER_NO_SMS_GSM)) == 0)
            return true;

        if (((msgType & BluetoothMapAppParams.FILTER_NO_SMS_GSM) == 0)
                && (phoneType == TelephonyManager.PHONE_TYPE_GSM))
            return true;

        if (((msgType & BluetoothMapAppParams.FILTER_NO_SMS_CDMA) == 0)
                && (phoneType == TelephonyManager.PHONE_TYPE_CDMA))
            return true;

        return false;
    }

    /**
     * Determine from application parameter if mms should be included.
     * The filter mask is set for message types not selected
     * @param fi
     * @param ap
     * @return boolean true if mms is selected, false if not
     */
    private boolean mmsSelected(BluetoothMapAppParams ap) {
        int msgType = ap.getFilterMessageType();

        if (D) Log.d(TAG, "mmsSelected msgType: " + msgType);

        if (msgType == BluetoothMapAppParams.INVALID_VALUE_PARAMETER)
            return true;

        if ((msgType & BluetoothMapAppParams.FILTER_NO_MMS) == 0)
            return true;

        return false;
    }

    /**
     * Determine from application parameter if email should be included.
     * The filter mask is set for message types not selected
     * @param fi
     * @param ap
     * @return boolean true if email is selected, false if not
     */
    private boolean emailSelected(BluetoothMapAppParams ap) {
        int msgType = ap.getFilterMessageType();

        if (D) Log.d(TAG, "emailSelected msgType: " + msgType);

        if (msgType == BluetoothMapAppParams.INVALID_VALUE_PARAMETER)
            return true;

        if ((msgType & BluetoothMapAppParams.FILTER_NO_EMAIL) == 0)
            return true;

        return false;
    }

    /**
     * Determine from application parameter if IM should be included.
     * The filter mask is set for message types not selected
     * @param fi
     * @param ap
     * @return boolean true if im is selected, false if not
     */
    private boolean imSelected(BluetoothMapAppParams ap) {
        int msgType = ap.getFilterMessageType();

        if (D) Log.d(TAG, "imSelected msgType: " + msgType);

        if (msgType == BluetoothMapAppParams.INVALID_VALUE_PARAMETER)
            return true;

        if ((msgType & BluetoothMapAppParams.FILTER_NO_IM) == 0)
            return true;

        return false;
    }

    private void setFilterInfo(FilterInfo fi) {
        TelephonyManager tm =
            (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            fi.mPhoneType = tm.getPhoneType();
            fi.mPhoneNum = tm.getLine1Number();
            fi.mPhoneAlphaTag = tm.getLine1AlphaTag();
            if (D) Log.d(TAG, "phone type = " + fi.mPhoneType +
                " phone num = " + fi.mPhoneNum +
                " phone alpha tag = " + fi.mPhoneAlphaTag);
        }
    }

    /**
     * Get a listing of message in folder after applying filter.
     * @param folder Must contain a valid folder string != null
     * @param ap Parameters specifying message content and filters
     * @return Listing object containing requested messages
     */
    public BluetoothMapMessageListing msgListing(BluetoothMapFolderElement folderElement,
            BluetoothMapAppParams ap) {
        if (D) Log.d(TAG, "msgListing: messageType = " + ap.getFilterMessageType() );

        BluetoothMapMessageListing bmList = new BluetoothMapMessageListing();

        /* We overwrite the parameter mask here if it is 0 or not present, as this
         * should cause all parameters to be included in the message list. */
        if(ap.getParameterMask() == BluetoothMapAppParams.INVALID_VALUE_PARAMETER ||
                ap.getParameterMask() == 0) {
            ap.setParameterMask(PARAMETER_MASK_ALL_ENABLED);
            if (V) Log.v(TAG, "msgListing(): appParameterMask is zero or not present, " +
                    "changing to All Enabled by default: " + ap.getParameterMask());
        }
        if (V) Log.v(TAG, "folderElement hasSmsMmsContent = " + folderElement.hasSmsMmsContent() +
                " folderElement.hasEmailContent = " + folderElement.hasEmailContent() +
                " folderElement.hasImContent = " + folderElement.hasImContent());

        /* Cache some info used throughout filtering */
        FilterInfo fi = new FilterInfo();
        setFilterInfo(fi);
        Cursor smsCursor = null;
        Cursor mmsCursor = null;
        Cursor emailCursor = null;
        Cursor imCursor = null;
        String limit = "";
        int countNum = ap.getMaxListCount();
        int offsetNum = ap.getStartOffset();
        if(ap.getMaxListCount()>0){
            limit=" LIMIT "+ (ap.getMaxListCount()+ap.getStartOffset());
        }
        try{
            if (smsSelected(fi, ap) && folderElement.hasSmsMmsContent()) {
                if(ap.getFilterMessageType() == (BluetoothMapAppParams.FILTER_NO_EMAIL|
                                                 BluetoothMapAppParams.FILTER_NO_MMS|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_GSM|
                                                 BluetoothMapAppParams.FILTER_NO_IM)||
                   ap.getFilterMessageType() == (BluetoothMapAppParams.FILTER_NO_EMAIL|
                                                 BluetoothMapAppParams.FILTER_NO_MMS|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_CDMA|
                                                 BluetoothMapAppParams.FILTER_NO_IM)){
                    //set real limit and offset if only this type is used
                    // (only if offset/limit is used)
                    limit = " LIMIT " + ap.getMaxListCount()+" OFFSET "+ ap.getStartOffset();
                    if(D) Log.d(TAG, "SMS Limit => "+limit);
                    offsetNum = 0;
                }
                fi.mMsgType = FilterInfo.TYPE_SMS;
                if(ap.getFilterPriority() != 1){ /*SMS cannot have high priority*/
                    String where = setWhereFilter(folderElement, fi, ap);
                    if (D) Log.d(TAG, "msgType: " + fi.mMsgType + " where: " + where);
                    smsCursor = mResolver.query(Sms.CONTENT_URI,
                            SMS_PROJECTION, where, null, Sms.DATE + " DESC" + limit);
                    if (smsCursor != null) {
                        BluetoothMapMessageListingElement e = null;
                        // store column index so we dont have to look them up anymore (optimization)
                        if(D) Log.d(TAG, "Found " + smsCursor.getCount() + " sms messages.");
                        fi.setSmsColumns(smsCursor);
                        while (smsCursor.moveToNext()) {
                            if (matchAddresses(smsCursor, fi, ap)) {
                                if(V) BluetoothMapUtils.printCursor(smsCursor);
                                e = element(smsCursor, fi, ap);
                                bmList.add(e);
                            }
                        }
                    }
                }
            }

            if (mmsSelected(ap) && folderElement.hasSmsMmsContent()) {
                if(ap.getFilterMessageType() == (BluetoothMapAppParams.FILTER_NO_EMAIL|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_CDMA|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_GSM|
                                                 BluetoothMapAppParams.FILTER_NO_IM)){
                    //set real limit and offset if only this type is used
                    //(only if offset/limit is used)
                    limit = " LIMIT " + ap.getMaxListCount()+" OFFSET "+ ap.getStartOffset();
                    if(D) Log.d(TAG, "MMS Limit => "+limit);
                    offsetNum = 0;
                }
                fi.mMsgType = FilterInfo.TYPE_MMS;
                String where = setWhereFilter(folderElement, fi, ap);
                if(!where.isEmpty()) {
                    if (D) Log.d(TAG, "msgType: " + fi.mMsgType + " where: " + where);
                    mmsCursor = mResolver.query(Mms.CONTENT_URI,
                            MMS_PROJECTION, where, null, Mms.DATE + " DESC" + limit);
                    if (mmsCursor != null) {
                        BluetoothMapMessageListingElement e = null;
                        // store column index so we dont have to look them up anymore (optimization)
                        fi.setMmsColumns(mmsCursor);
                        if(D) Log.d(TAG, "Found " + mmsCursor.getCount() + " mms messages.");
                        while (mmsCursor.moveToNext()) {
                            if (matchAddresses(mmsCursor, fi, ap)) {
                                if(V) BluetoothMapUtils.printCursor(mmsCursor);
                                e = element(mmsCursor, fi, ap);
                                bmList.add(e);
                            }
                        }
                    }
                }
            }

            if (emailSelected(ap) && folderElement.hasEmailContent()) {
                if(ap.getFilterMessageType() == (BluetoothMapAppParams.FILTER_NO_MMS|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_CDMA|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_GSM|
                                                 BluetoothMapAppParams.FILTER_NO_IM)){
                    //set real limit and offset if only this type is used
                    //(only if offset/limit is used)
                    limit = " LIMIT " + ap.getMaxListCount()+" OFFSET "+ ap.getStartOffset();
                    if(D) Log.d(TAG, "Email Limit => "+limit);
                    offsetNum = 0;
                }
                fi.mMsgType = FilterInfo.TYPE_EMAIL;
                String where = setWhereFilter(folderElement, fi, ap);

                if(!where.isEmpty()) {
                    if (D) Log.d(TAG, "msgType: " + fi.mMsgType + " where: " + where);
                    Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
                    emailCursor = mResolver.query(contentUri,
                            BluetoothMapContract.BT_MESSAGE_PROJECTION, where, null,
                            BluetoothMapContract.MessageColumns.DATE + " DESC" + limit);
                    if (emailCursor != null) {
                        BluetoothMapMessageListingElement e = null;
                        // store column index so we dont have to look them up anymore (optimization)
                        fi.setEmailMessageColumns(emailCursor);
                        int cnt = 0;
                        if(D) Log.d(TAG, "Found " + emailCursor.getCount() + " email messages.");
                        while (emailCursor.moveToNext()) {
                            if(V) BluetoothMapUtils.printCursor(emailCursor);
                            e = element(emailCursor, fi, ap);
                            bmList.add(e);
                        }
                    //   emailCursor.close();
                    }
                }
            }

            if (imSelected(ap) && folderElement.hasImContent()) {
                if(ap.getFilterMessageType() == (BluetoothMapAppParams.FILTER_NO_MMS|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_CDMA|
                                                 BluetoothMapAppParams.FILTER_NO_SMS_GSM|
                                                 BluetoothMapAppParams.FILTER_NO_EMAIL)){
                    //set real limit and offset if only this type is used
                    //(only if offset/limit is used)
                    limit = " LIMIT " + ap.getMaxListCount() + " OFFSET "+ ap.getStartOffset();
                    if(D) Log.d(TAG, "IM Limit => "+limit);
                    offsetNum = 0;
                }
                fi.mMsgType = FilterInfo.TYPE_IM;
                String where = setWhereFilter(folderElement, fi, ap);
                if (D) Log.d(TAG, "msgType: " + fi.mMsgType + " where: " + where);

                Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
                imCursor = mResolver.query(contentUri,
                        BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION,
                        where, null, BluetoothMapContract.MessageColumns.DATE + " DESC" + limit);
                if (imCursor != null) {
                    BluetoothMapMessageListingElement e = null;
                    // store column index so we dont have to look them up anymore (optimization)
                    fi.setImMessageColumns(imCursor);
                    if (D) Log.d(TAG, "Found " + imCursor.getCount() + " im messages.");
                    while (imCursor.moveToNext()) {
                        if (V) BluetoothMapUtils.printCursor(imCursor);
                        e = element(imCursor, fi, ap);
                        bmList.add(e);
                    }
                }
            }

            /* Enable this if post sorting and segmenting needed */
            bmList.sort();
            bmList.segment(ap.getMaxListCount(), offsetNum);
            List<BluetoothMapMessageListingElement> list = bmList.getList();
            int listSize = list.size();
            Cursor tmpCursor = null;
            for(int x=0;x<listSize;x++){
                BluetoothMapMessageListingElement ele = list.get(x);
                /* If OBEX "GET" request header includes "ParameterMask" with 'Type' NOT set,
                 * then ele.getType() returns "null" even for a valid cursor.
                 * Avoid NullPointerException in equals() check when 'mType' value is "null" */
                TYPE tmpType = ele.getType();
                if (smsCursor!= null &&
                        ((TYPE.SMS_GSM).equals(tmpType) || (TYPE.SMS_CDMA).equals(tmpType))) {
                    tmpCursor = smsCursor;
                    fi.mMsgType = FilterInfo.TYPE_SMS;
                } else if(mmsCursor != null && (TYPE.MMS).equals(tmpType)) {
                    tmpCursor = mmsCursor;
                    fi.mMsgType = FilterInfo.TYPE_MMS;
                } else if(emailCursor != null && ((TYPE.EMAIL).equals(tmpType))) {
                    tmpCursor = emailCursor;
                    fi.mMsgType = FilterInfo.TYPE_EMAIL;
                } else if(imCursor != null && ((TYPE.IM).equals(tmpType))) {
                    tmpCursor = imCursor;
                    fi.mMsgType = FilterInfo.TYPE_IM;
                }
                if(tmpCursor != null){
                    tmpCursor.moveToPosition(ele.getCursorIndex());
                    setSenderAddressing(ele, tmpCursor, fi, ap);
                    setSenderName(ele, tmpCursor, fi, ap);
                    setRecipientAddressing(ele, tmpCursor, fi, ap);
                    setRecipientName(ele, tmpCursor, fi, ap);
                    setSubject(ele, tmpCursor, fi, ap);
                    setSize(ele, tmpCursor, fi, ap);
                    setText(ele, tmpCursor, fi, ap);
                    setPriority(ele, tmpCursor, fi, ap);
                    setSent(ele, tmpCursor, fi, ap);
                    setProtected(ele, tmpCursor, fi, ap);
                    setReceptionStatus(ele, tmpCursor, fi, ap);
                    setAttachment(ele, tmpCursor, fi, ap);

                    if(mMsgListingVersion > BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V10 ){
                        setDeliveryStatus(ele, tmpCursor, fi, ap);
                        setThreadId(ele, tmpCursor, fi, ap);
                        setThreadName(ele, tmpCursor, fi, ap);
                        setFolderType(ele, tmpCursor, fi, ap);
                    }
                }
            }
        } finally {
            if(emailCursor != null)emailCursor.close();
            if(smsCursor != null)smsCursor.close();
            if(mmsCursor != null)mmsCursor.close();
            if(imCursor != null)imCursor.close();
        }


        if(D)Log.d(TAG, "messagelisting end");
        return bmList;
    }

    /**
     * Get the size of the message listing
     * @param folder Must contain a valid folder string != null
     * @param ap Parameters specifying message content and filters
     * @return Integer equal to message listing size
     */
    public int msgListingSize(BluetoothMapFolderElement folderElement,
            BluetoothMapAppParams ap) {
        if (D) Log.d(TAG, "msgListingSize: folder = " + folderElement.getName());
        int cnt = 0;

        /* Cache some info used throughout filtering */
        FilterInfo fi = new FilterInfo();
        setFilterInfo(fi);

        if (smsSelected(fi, ap) && folderElement.hasSmsMmsContent()) {
            fi.mMsgType = FilterInfo.TYPE_SMS;
            String where = setWhereFilter(folderElement, fi, ap);
            Cursor c = mResolver.query(Sms.CONTENT_URI,
                    SMS_PROJECTION, where, null, Sms.DATE + " DESC");
            try {
                if (c != null) {
                    cnt = c.getCount();
                }
            } finally {
                if (c != null) c.close();
            }
        }

        if (mmsSelected(ap)  && folderElement.hasSmsMmsContent()) {
            fi.mMsgType = FilterInfo.TYPE_MMS;
            String where = setWhereFilter(folderElement, fi, ap);
            Cursor c = mResolver.query(Mms.CONTENT_URI,
                    MMS_PROJECTION, where, null, Mms.DATE + " DESC");
            try {
                if (c != null) {
                    cnt += c.getCount();
                }
            } finally {
                if (c != null) c.close();
            }
        }

        if (emailSelected(ap) && folderElement.hasEmailContent()) {
            fi.mMsgType = FilterInfo.TYPE_EMAIL;
            String where = setWhereFilter(folderElement, fi, ap);
            if(!where.isEmpty()) {
                Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
                Cursor c = mResolver.query(contentUri, BluetoothMapContract.BT_MESSAGE_PROJECTION,
                        where, null, BluetoothMapContract.MessageColumns.DATE + " DESC");
                try {
                    if (c != null) {
                        cnt += c.getCount();
                    }
                } finally {
                    if (c != null) c.close();
                }
            }
        }

        if (imSelected(ap) && folderElement.hasImContent()) {
            fi.mMsgType = FilterInfo.TYPE_IM;
            String where = setWhereFilter(folderElement, fi, ap);
            if(!where.isEmpty()) {
                Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
                Cursor c = mResolver.query(contentUri,
                        BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION,
                        where, null, BluetoothMapContract.MessageColumns.DATE + " DESC");
                try {
                    if (c != null) {
                        cnt += c.getCount();
                    }
                } finally {
                    if (c != null) c.close();
                }
            }
        }

        if (D) Log.d(TAG, "msgListingSize: size = " + cnt);
        return cnt;
    }

    /**
     * Return true if there are unread messages in the requested list of messages
     * @param folder folder where the message listing should come from
     * @param ap application parameter object
     * @return true if unread messages are in the list, else false
     */
    public boolean msgListingHasUnread(BluetoothMapFolderElement folderElement,
            BluetoothMapAppParams ap) {
        if (D) Log.d(TAG, "msgListingHasUnread: folder = " + folderElement.getName());
        int cnt = 0;

        /* Cache some info used throughout filtering */
        FilterInfo fi = new FilterInfo();
        setFilterInfo(fi);

       if (smsSelected(fi, ap)  && folderElement.hasSmsMmsContent()) {
            fi.mMsgType = FilterInfo.TYPE_SMS;
            String where = setWhereFilterFolderType(folderElement, fi);
            where += " AND " + Sms.READ + "=0 ";
            where += setWhereFilterPeriod(ap, fi);
            Cursor c = mResolver.query(Sms.CONTENT_URI,
                SMS_PROJECTION, where, null, Sms.DATE + " DESC");
            try {
                if (c != null) {
                    cnt = c.getCount();
                }
            } finally {
                if (c != null) c.close();
            }
        }

        if (mmsSelected(ap)  && folderElement.hasSmsMmsContent()) {
            fi.mMsgType = FilterInfo.TYPE_MMS;
            String where = setWhereFilterFolderType(folderElement, fi);
            where += " AND " + Mms.READ + "=0 ";
            where += setWhereFilterPeriod(ap, fi);
            Cursor c = mResolver.query(Mms.CONTENT_URI,
                MMS_PROJECTION, where, null, Sms.DATE + " DESC");
            try {
                if (c != null) {
                    cnt += c.getCount();
                }
            } finally {
                if (c != null) c.close();
            }
        }


        if (emailSelected(ap) && folderElement.getFolderId() != -1) {
            fi.mMsgType = FilterInfo.TYPE_EMAIL;
            String where = setWhereFilterFolderType(folderElement, fi);
            if(!where.isEmpty()) {
                where += " AND " + BluetoothMapContract.MessageColumns.FLAG_READ + "=0 ";
                where += setWhereFilterPeriod(ap, fi);
                Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
                Cursor c = mResolver.query(contentUri, BluetoothMapContract.BT_MESSAGE_PROJECTION,
                        where, null, BluetoothMapContract.MessageColumns.DATE + " DESC");
                try {
                    if (c != null) {
                        cnt += c.getCount();
                    }
                } finally {
                    if (c != null) c.close();
                }
            }
        }

        if (imSelected(ap) && folderElement.hasImContent()) {
            fi.mMsgType = FilterInfo.TYPE_IM;
            String where = setWhereFilter(folderElement, fi, ap);
            if(!where.isEmpty()) {
                where += " AND " + BluetoothMapContract.MessageColumns.FLAG_READ + "=0 ";
                where += setWhereFilterPeriod(ap, fi);
                Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
                Cursor c = mResolver.query(contentUri,
                        BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION,
                        where, null, BluetoothMapContract.MessageColumns.DATE + " DESC");
                try {
                    if (c != null) {
                        cnt += c.getCount();
                    }
                } finally {
                    if (c != null) c.close();
                }
            }
        }

        if (D) Log.d(TAG, "msgListingHasUnread: numUnread = " + cnt);
        return (cnt>0)?true:false;
    }

    /**
     * Build the conversation listing.
     * @param ap The Application Parameters
     * @param sizeOnly TRUE: don't populate the list members, only build the list to get the size.
     * @return
     */
    public BluetoothMapConvoListing convoListing(BluetoothMapAppParams ap, boolean sizeOnly) {

        if (D) Log.d(TAG, "convoListing: " + " messageType = " + ap.getFilterMessageType() );
        BluetoothMapConvoListing convoList = new BluetoothMapConvoListing();

        /* We overwrite the parameter mask here if it is 0 or not present, as this
         * should cause all parameters to be included in the message list. */
        if(ap.getConvoParameterMask() == BluetoothMapAppParams.INVALID_VALUE_PARAMETER ||
                ap.getConvoParameterMask() == 0) {
            ap.setConvoParameterMask(CONVO_PARAMETER_MASK_DEFAULT);
            if (D) Log.v(TAG, "convoListing(): appParameterMask is zero or not present, " +
                    "changing to default: " + ap.getConvoParameterMask());
        }

        /* Possible filters:
         *  - Recipient name (contacts DB) or id (for SMS/MMS this is the thread-id contact-id)
         *  - Activity start/begin
         *  - Read status
         *  - Thread_id
         * The strategy for SMS/MMS
         *   With no filter on name - use limit and offset.
         *   With a filter on name - build the complete list of conversations and create a filter
         *                           mechanism
         *
         * The strategy for IM:
         *   Join the conversation table with the contacts table in a way that makes it possible to
         *   get the data needed in a single query.
         *   Manually handle limit/offset
         * */

        /* Cache some info used throughout filtering */
        FilterInfo fi = new FilterInfo();
        setFilterInfo(fi);
        Cursor smsMmsCursor = null;
        Cursor imEmailCursor = null;
        int offsetNum;
        if(sizeOnly) {
            offsetNum = 0;
        } else {
            offsetNum = ap.getStartOffset();
        }
        // Inverse meaning - hence a 1 is include.
        int msgTypesInclude = ((~ap.getFilterMessageType())
                & BluetoothMapAppParams.FILTER_MSG_TYPE_MASK);
        int maxThreads = ap.getMaxListCount()+ap.getStartOffset();


        try {
            if (smsSelected(fi, ap) || mmsSelected(ap)) {
                String limit = "";
                if((sizeOnly == false) && (ap.getMaxListCount()>0) &&
                        (ap.getFilterRecipient()==null)){
                    /* We can only use limit if we do not have a contacts filter */
                    limit=" LIMIT " + maxThreads;
                }
                StringBuilder sortOrder = new StringBuilder(Threads.DATE + " DESC");
                if((sizeOnly == false) &&
                        ((msgTypesInclude & ~(BluetoothMapAppParams.FILTER_NO_SMS_GSM |
                        BluetoothMapAppParams.FILTER_NO_SMS_CDMA) |
                        BluetoothMapAppParams.FILTER_NO_MMS) == 0)
                        && ap.getFilterRecipient() == null){
                    // SMS/MMS messages only and no recipient filter - use optimization.
                    limit = " LIMIT " + ap.getMaxListCount()+" OFFSET "+ ap.getStartOffset();
                    if(D) Log.d(TAG, "SMS Limit => "+limit);
                    offsetNum = 0;
                }
                StringBuilder selection = new StringBuilder(120); // This covers most cases
                ArrayList<String> selectionArgs = new ArrayList<String>(12); // Covers all cases
                selection.append("1=1 "); // just to simplify building the where-clause
                setConvoWhereFilterSmsMms(selection, selectionArgs, fi, ap);
                String[] args = null;
                if(selectionArgs.size() > 0) {
                    args = new String[selectionArgs.size()];
                    selectionArgs.toArray(args);
                }
                Uri uri = Threads.CONTENT_URI.buildUpon()
                        .appendQueryParameter("simple", "true").build();
                sortOrder.append(limit);
                if(D) Log.d(TAG, "Query using selection: " + selection.toString() +
                        " - sortOrder: " + sortOrder.toString());
                // TODO: Optimize: Reduce projection based on convo parameter mask
                smsMmsCursor = mResolver.query(uri, MMS_SMS_THREAD_PROJECTION, selection.toString(),
                        args, sortOrder.toString());
                if (smsMmsCursor != null) {
                    // store column index so we don't have to look them up anymore (optimization)
                    if(D) Log.d(TAG, "Found " + smsMmsCursor.getCount()
                            + " sms/mms conversations.");
                    BluetoothMapConvoListingElement convoElement = null;
                    smsMmsCursor.moveToPosition(-1);
                    if(ap.getFilterRecipient() == null) {
                        int count = 0;
                        // We have no Recipient filter, add contacts after the list is reduced
                        while (smsMmsCursor.moveToNext()) {
                            convoElement = createConvoElement(smsMmsCursor, fi, ap);
                            convoList.add(convoElement);
                            count++;
                            if(sizeOnly == false && count >= maxThreads) {
                                break;
                            }
                        }
                    } else {
                        // We must be able to filter on recipient, add contacts now
                        SmsMmsContacts contacts = new SmsMmsContacts();
                        while (smsMmsCursor.moveToNext()) {
                            int count = 0;
                            convoElement = createConvoElement(smsMmsCursor, fi, ap);
                            String idsStr =
                                    smsMmsCursor.getString(MMS_SMS_THREAD_COL_RECIPIENT_IDS);
                            // Add elements only if we do find a contact - if not we cannot apply
                            // the filter, hence the item is irrelevant
                            // TODO: Perhaps the spec. should be changes to be able to search on
                            //       phone number as well?
                            if(addSmsMmsContacts(convoElement, contacts, idsStr,
                                    ap.getFilterRecipient(), ap)) {
                                convoList.add(convoElement);
                                if(sizeOnly == false && count >= maxThreads) {
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (emailSelected(ap) || imSelected(ap)) {
                int count = 0;
                if(emailSelected(ap)) {
                    fi.mMsgType = FilterInfo.TYPE_EMAIL;
                } else if(imSelected(ap)) {
                    fi.mMsgType = FilterInfo.TYPE_IM;
                }
                if (D) Log.d(TAG, "msgType: " + fi.mMsgType);
                Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_CONVERSATION);

                contentUri = appendConvoListQueryParameters(ap, contentUri);
                if(V) Log.v(TAG, "URI with parameters: " + contentUri.toString());
                // TODO: Optimize: Reduce projection based on convo parameter mask
                imEmailCursor = mResolver.query(contentUri,
                        BluetoothMapContract.BT_CONVERSATION_PROJECTION,
                        null, null, BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY
                        + " DESC, " + BluetoothMapContract.ConversationColumns.THREAD_ID
                        + " ASC");
                if (imEmailCursor != null) {
                    BluetoothMapConvoListingElement e = null;
                    // store column index so we don't have to look them up anymore (optimization)
                    // Here we rely on only a single account-based message type for each MAS.
                    fi.setEmailImConvoColumns(imEmailCursor);
                    boolean isValid = imEmailCursor.moveToNext();
                    if(D) Log.d(TAG, "Found " + imEmailCursor.getCount()
                            + " EMAIL/IM conversations. isValid = " + isValid);
                    while (isValid && ((sizeOnly == true) || (count < maxThreads))) {
                        long threadId = imEmailCursor.getLong(fi.mConvoColConvoId);
                        long nextThreadId;
                        count ++;
                        e = createConvoElement(imEmailCursor, fi, ap);
                        convoList.add(e);

                        do {
                            nextThreadId = imEmailCursor.getLong(fi.mConvoColConvoId);
                            if(V) Log.i(TAG, "  threadId = " + threadId + " newThreadId = " +
                                    nextThreadId);
                            // TODO: This seems rather inefficient in the case where we do not need
                            //       to reduce the list.
                        } while ((nextThreadId == threadId) &&
                                (isValid = imEmailCursor.moveToNext() == true));
                    }
                }
            }

            if(D) Log.d(TAG, "Done adding conversations - list size:" +
                    convoList.getCount());

            // If sizeOnly - we are all done here - return the list as is - no need to populate the
            // list.
            if(sizeOnly) {
                return convoList;
            }

            /* Enable this if post sorting and segmenting needed */
            /* This is too early */
            convoList.sort();
            convoList.segment(ap.getMaxListCount(), offsetNum);
            List<BluetoothMapConvoListingElement> list = convoList.getList();
            int listSize = list.size();
            if(V) Log.i(TAG, "List Size:" + listSize);
            Cursor tmpCursor = null;
            SmsMmsContacts contacts = new SmsMmsContacts();
            for(int x=0;x<listSize;x++){
                BluetoothMapConvoListingElement ele = list.get(x);
                TYPE type = ele.getType();
                switch(type) {
                case SMS_CDMA:
                case SMS_GSM:
                case MMS: {
                    tmpCursor = null; // SMS/MMS needs special treatment
                    if(smsMmsCursor != null) {
                        populateSmsMmsConvoElement(ele, smsMmsCursor, ap, contacts);
                    }
                    if(D) fi.mMsgType = FilterInfo.TYPE_IM;
                    break;
                }
                case EMAIL:
                    tmpCursor = imEmailCursor;
                    fi.mMsgType = FilterInfo.TYPE_EMAIL;
                    break;
                case IM:
                    tmpCursor = imEmailCursor;
                    fi.mMsgType = FilterInfo.TYPE_IM;
                    break;
                default:
                    tmpCursor = null;
                    break;
                }

                if(D) Log.d(TAG, "Working on cursor of type " + fi.mMsgType);

                if(tmpCursor != null){
                    populateImEmailConvoElement(ele, tmpCursor, ap, fi);
                }else {
                    // No, it will be for SMS/MMS at the moment
                    if(D) Log.d(TAG, "tmpCursor is Null - something is wrong - or the message is" +
                            " of type SMS/MMS");
                }
            }
        } finally {
            if(imEmailCursor != null)imEmailCursor.close();
            if(smsMmsCursor != null)smsMmsCursor.close();
            if(D)Log.d(TAG, "conversation end");
        }
        return convoList;
    }


    /**
     * Refreshes the entire list of SMS/MMS conversation version counters. Use it to generate a
     * new ConvoListVersinoCounter in mSmsMmsConvoListVersion
     * @return
     */
    /* package */
    boolean refreshSmsMmsConvoVersions() {
        boolean listChangeDetected = false;
        Cursor cursor = null;
        Uri uri = Threads.CONTENT_URI.buildUpon()
                .appendQueryParameter("simple", "true").build();
        cursor = mResolver.query(uri, MMS_SMS_THREAD_PROJECTION, null,
                null, Threads.DATE + " DESC");
        try {
            if (cursor != null) {
                // store column index so we don't have to look them up anymore (optimization)
                if(D) Log.d(TAG, "Found " + cursor.getCount()
                        + " sms/mms conversations.");
                BluetoothMapConvoListingElement convoElement = null;
                cursor.moveToPosition(-1);
                synchronized (getSmsMmsConvoList()) {
                    int size = Math.max(getSmsMmsConvoList().size(), cursor.getCount());
                    HashMap<Long,BluetoothMapConvoListingElement> newList =
                            new HashMap<Long,BluetoothMapConvoListingElement>(size);
                    while (cursor.moveToNext()) {
                        // TODO: Extract to function, that can be called at listing, which returns
                        //       the versionCounter(existing or new).
                        boolean convoChanged = false;
                        Long id = cursor.getLong(MMS_SMS_THREAD_COL_ID);
                        convoElement = getSmsMmsConvoList().remove(id);
                        if(convoElement == null) {
                            // New conversation added
                            convoElement = new BluetoothMapConvoListingElement();
                            convoElement.setConvoId(BluetoothMapUtils.CONVO_ID_TYPE_SMS_MMS, id);
                            listChangeDetected = true;
                            convoElement.setVersionCounter(0);
                        }
                        // Currently we only need to compare name, last_activity and read_status, and
                        // name is not used for SMS/MMS.
                        // msg delete will be handled by update folderVersionCounter().
                        long last_activity = cursor.getLong(MMS_SMS_THREAD_COL_DATE);
                        boolean read = (cursor.getInt(MMS_SMS_THREAD_COL_READ) == 1) ?
                                true : false;

                        if(last_activity != convoElement.getLastActivity()) {
                            convoChanged = true;
                            convoElement.setLastActivity(last_activity);
                        }

                        if(read != convoElement.getReadBool()) {
                            convoChanged = true;
                            convoElement.setRead(read, false);
                        }

                        String idsStr = cursor.getString(MMS_SMS_THREAD_COL_RECIPIENT_IDS);
                        if(!idsStr.equals(convoElement.getSmsMmsContacts())) {
                            // This should not trigger a change in conversationVersionCounter only the
                            // ConvoListVersionCounter.
                            listChangeDetected = true;
                            convoElement.setSmsMmsContacts(idsStr);
                        }

                        if(convoChanged) {
                            listChangeDetected = true;
                            convoElement.incrementVersionCounter();
                        }
                        newList.put(id, convoElement);
                    }
                    // If we still have items on the old list, something was deleted
                    if(getSmsMmsConvoList().size() != 0) {
                        listChangeDetected = true;
                    }
                    setSmsMmsConvoList(newList);
                }

                if(listChangeDetected) {
                    mMasInstance.updateSmsMmsConvoListVersionCounter();
                }
            }
        } finally {
            if(cursor != null) {
                cursor.close();
            }
        }
        return listChangeDetected;
    }

    /**
     * Refreshes the entire list of SMS/MMS conversation version counters. Use it to generate a
     * new ConvoListVersinoCounter in mSmsMmsConvoListVersion
     * @return
     */
    /* package */
    boolean refreshImEmailConvoVersions() {
        boolean listChangeDetected = false;
        FilterInfo fi = new FilterInfo();

        Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_CONVERSATION);

        if(V) Log.v(TAG, "URI with parameters: " + contentUri.toString());
        Cursor imEmailCursor = mResolver.query(contentUri,
                CONVO_VERSION_PROJECTION,
                null, null, BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY
                + " DESC, " + BluetoothMapContract.ConversationColumns.THREAD_ID
                + " ASC");
        try {
            if (imEmailCursor != null) {
                BluetoothMapConvoListingElement convoElement = null;
                // store column index so we don't have to look them up anymore (optimization)
                // Here we rely on only a single account-based message type for each MAS.
                fi.setEmailImConvoColumns(imEmailCursor);
                boolean isValid = imEmailCursor.moveToNext();
                if(V) Log.d(TAG, "Found " + imEmailCursor.getCount()
                        + " EMAIL/IM conversations. isValid = " + isValid);
                synchronized (getImEmailConvoList()) {
                    int size = Math.max(getImEmailConvoList().size(), imEmailCursor.getCount());
                    boolean convoChanged = false;
                    HashMap<Long,BluetoothMapConvoListingElement> newList =
                            new HashMap<Long,BluetoothMapConvoListingElement>(size);
                    while (isValid) {
                        long id = imEmailCursor.getLong(fi.mConvoColConvoId);
                        long nextThreadId;
                        convoElement = getImEmailConvoList().remove(id);
                        if(convoElement == null) {
                            // New conversation added
                            convoElement = new BluetoothMapConvoListingElement();
                            convoElement.setConvoId(BluetoothMapUtils.CONVO_ID_TYPE_EMAIL_IM, id);
                            listChangeDetected = true;
                            convoElement.setVersionCounter(0);
                        }
                        String name = imEmailCursor.getString(fi.mConvoColName);
                        String summary = imEmailCursor.getString(fi.mConvoColSummary);
                        long last_activity = imEmailCursor.getLong(fi.mConvoColLastActivity);
                        boolean read = (imEmailCursor.getInt(fi.mConvoColRead) == 1) ?
                                true : false;

                        if(last_activity != convoElement.getLastActivity()) {
                            convoChanged = true;
                            convoElement.setLastActivity(last_activity);
                        }

                        if(read != convoElement.getReadBool()) {
                            convoChanged = true;
                            convoElement.setRead(read, false);
                        }

                        if(name != null && !name.equals(convoElement.getName())) {
                            convoChanged = true;
                            convoElement.setName(name);
                        }

                        if(summary != null && !summary.equals(convoElement.getFullSummary())) {
                            convoChanged = true;
                            convoElement.setSummary(summary);
                        }
                        /* If the query returned one row for each contact, skip all the dublicates */
                        do {
                            nextThreadId = imEmailCursor.getLong(fi.mConvoColConvoId);
                            if(V) Log.i(TAG, "  threadId = " + id + " newThreadId = " +
                                    nextThreadId);
                        } while ((nextThreadId == id) &&
                                (isValid = imEmailCursor.moveToNext() == true));

                        if(convoChanged) {
                            listChangeDetected = true;
                            convoElement.incrementVersionCounter();
                        }
                        newList.put(id, convoElement);
                    }
                    // If we still have items on the old list, something was deleted
                    if(getImEmailConvoList().size() != 0) {
                        listChangeDetected = true;
                    }
                    setImEmailConvoList(newList);
                }
            }
        } finally {
            if(imEmailCursor != null) {
                imEmailCursor.close();
            }
        }

        if(listChangeDetected) {
            mMasInstance.updateImEmailConvoListVersionCounter();
        }
        return listChangeDetected;
    }

    /**
     * Update the convoVersionCounter within the element passed as parameter.
     * This function has the side effect to update the ConvoListVersionCounter if needed.
     * This function ignores changes to contacts as this shall not change the convoVersionCounter,
     * only the convoListVersion counter, which will be updated upon request.
     * @param ele Element to update shall not be null.
     */
    private void updateSmsMmsConvoVersion(Cursor cursor, BluetoothMapConvoListingElement ele) {
        long id = ele.getCpConvoId();
        BluetoothMapConvoListingElement convoElement = getSmsMmsConvoList().get(id);
        boolean listChangeDetected = false;
        boolean convoChanged = false;
        if(convoElement == null) {
            // New conversation added
            convoElement = new BluetoothMapConvoListingElement();
            getSmsMmsConvoList().put(id, convoElement);
            convoElement.setConvoId(BluetoothMapUtils.CONVO_ID_TYPE_SMS_MMS, id);
            listChangeDetected = true;
            convoElement.setVersionCounter(0);
        }
        long last_activity = cursor.getLong(MMS_SMS_THREAD_COL_DATE);
        boolean read = (cursor.getInt(MMS_SMS_THREAD_COL_READ) == 1) ?
                true : false;

        if(last_activity != convoElement.getLastActivity()) {
            convoChanged = true;
            convoElement.setLastActivity(last_activity);
        }

        if(read != convoElement.getReadBool()) {
            convoChanged = true;
            convoElement.setRead(read, false);
        }

        if(convoChanged) {
            listChangeDetected = true;
            convoElement.incrementVersionCounter();
        }
        if(listChangeDetected) {
            mMasInstance.updateSmsMmsConvoListVersionCounter();
        }
        ele.setVersionCounter(convoElement.getVersionCounter());
    }

    /**
     * Update the convoVersionCounter within the element passed as parameter.
     * This function has the side effect to update the ConvoListVersionCounter if needed.
     * This function ignores changes to contacts as this shall not change the convoVersionCounter,
     * only the convoListVersion counter, which will be updated upon request.
     * @param ele Element to update shall not be null.
     */
    private void updateImEmailConvoVersion(Cursor cursor, FilterInfo fi,
            BluetoothMapConvoListingElement ele) {
        long id = ele.getCpConvoId();
        BluetoothMapConvoListingElement convoElement = getImEmailConvoList().get(id);
        boolean listChangeDetected = false;
        boolean convoChanged = false;
        if(convoElement == null) {
            // New conversation added
            if(V) Log.d(TAG, "Added new conversation with ID = " + id);
            convoElement = new BluetoothMapConvoListingElement();
            convoElement.setConvoId(BluetoothMapUtils.CONVO_ID_TYPE_EMAIL_IM, id);
            getImEmailConvoList().put(id, convoElement);
            listChangeDetected = true;
            convoElement.setVersionCounter(0);
        }
        String name = cursor.getString(fi.mConvoColName);
        long last_activity = cursor.getLong(fi.mConvoColLastActivity);
        boolean read = (cursor.getInt(fi.mConvoColRead) == 1) ?
                true : false;

        if(last_activity != convoElement.getLastActivity()) {
            convoChanged = true;
            convoElement.setLastActivity(last_activity);
        }

        if(read != convoElement.getReadBool()) {
            convoChanged = true;
            convoElement.setRead(read, false);
        }

        if(name != null && !name.equals(convoElement.getName())) {
            convoChanged = true;
            convoElement.setName(name);
        }

        if(convoChanged) {
            listChangeDetected = true;
            if(V) Log.d(TAG, "conversation with ID = " + id + " changed");
            convoElement.incrementVersionCounter();
        }
        if(listChangeDetected) {
            mMasInstance.updateImEmailConvoListVersionCounter();
        }
        ele.setVersionCounter(convoElement.getVersionCounter());
    }

    /**
     * @param ele
     * @param smsMmsCursor
     * @param ap
     * @param contacts
     */
    private void populateSmsMmsConvoElement(BluetoothMapConvoListingElement ele,
            Cursor smsMmsCursor, BluetoothMapAppParams ap,
            SmsMmsContacts contacts) {
        smsMmsCursor.moveToPosition(ele.getCursorIndex());
        // TODO: If we ever get beyond 31 bit, change to long
        int parameterMask = (int) ap.getConvoParameterMask(); // We always set a default value

        // TODO: How to determine whether the convo-IDs can be used across message
        //       types?
        ele.setConvoId(BluetoothMapUtils.CONVO_ID_TYPE_SMS_MMS,
                smsMmsCursor.getLong(MMS_SMS_THREAD_COL_ID));

        boolean read = (smsMmsCursor.getInt(MMS_SMS_THREAD_COL_READ) == 1) ?
                true : false;
        if((parameterMask & CONVO_PARAM_MASK_CONVO_READ_STATUS) != 0) {
            ele.setRead(read, true);
        } else {
            ele.setRead(read, false);
        }

        if((parameterMask & CONVO_PARAM_MASK_CONVO_LAST_ACTIVITY) != 0) {
            long timeStamp = smsMmsCursor.getLong(MMS_SMS_THREAD_COL_DATE);
            ele.setLastActivity(timeStamp);
        } else {
            // We need to delete the time stamp, if it was added for multi msg-type
            ele.setLastActivity(-1);
        }

        if((parameterMask & CONVO_PARAM_MASK_CONVO_VERSION_COUNTER) != 0) {
            updateSmsMmsConvoVersion(smsMmsCursor, ele);
        }

        if((parameterMask & CONVO_PARAM_MASK_CONVO_NAME) != 0) {
            ele.setName(""); // We never have a thread name for SMS/MMS
        }

        if((parameterMask & CONVO_PARAM_MASK_CONVO_SUMMARY) != 0) {
            String summary = smsMmsCursor.getString(MMS_SMS_THREAD_COL_SNIPPET);
            String cs = smsMmsCursor.getString(MMS_SMS_THREAD_COL_SNIPPET_CS);
            if(summary != null && cs != null && !cs.equals("UTF-8")) {
                try {
                    // TODO: Not sure this is how to convert to UTF-8
                    summary = new String(summary.getBytes(cs),"UTF-8");
                } catch (UnsupportedEncodingException e){/*Cannot happen*/}
            }
            ele.setSummary(summary);
        }

        if((parameterMask & CONVO_PARAM_MASK_PARTTICIPANTS) != 0) {
            if(ap.getFilterRecipient() == null) {
                // Add contacts only if not already added
                String idsStr =
                        smsMmsCursor.getString(MMS_SMS_THREAD_COL_RECIPIENT_IDS);
                addSmsMmsContacts(ele, contacts, idsStr, null, ap);
            }
        }
    }

    /**
     * @param ele
     * @param tmpCursor
     * @param fi
     */
    private void populateImEmailConvoElement( BluetoothMapConvoListingElement ele,
            Cursor tmpCursor, BluetoothMapAppParams ap, FilterInfo fi) {
        tmpCursor.moveToPosition(ele.getCursorIndex());
        // TODO: If we ever get beyond 31 bit, change to long
        int parameterMask = (int) ap.getConvoParameterMask(); // We always set a default value
        long threadId = tmpCursor.getLong(fi.mConvoColConvoId);

        // Mandatory field
        ele.setConvoId(BluetoothMapUtils.CONVO_ID_TYPE_EMAIL_IM, threadId);

        if((parameterMask & CONVO_PARAM_MASK_CONVO_NAME) != 0) {
            ele.setName(tmpCursor.getString(fi.mConvoColName));
        }

        boolean reportRead = false;
        if((parameterMask & CONVO_PARAM_MASK_CONVO_READ_STATUS) != 0) {
            reportRead = true;
        }
        ele.setRead(((1==tmpCursor.getInt(fi.mConvoColRead))?true:false), reportRead);

        long timestamp = tmpCursor.getLong(fi.mConvoColLastActivity);
        if((parameterMask & CONVO_PARAM_MASK_CONVO_LAST_ACTIVITY) != 0) {
            ele.setLastActivity(timestamp);
        } else {
            // We need to delete the time stamp, if it was added for multi msg-type
            ele.setLastActivity(-1);
        }


        if((parameterMask & CONVO_PARAM_MASK_CONVO_VERSION_COUNTER) != 0) {
            updateImEmailConvoVersion(tmpCursor, fi, ele);
        }
        if((parameterMask & CONVO_PARAM_MASK_CONVO_SUMMARY) != 0) {
            ele.setSummary(tmpCursor.getString(fi.mConvoColSummary));
        }
        // TODO: For optimization, we could avoid joining the contact and convo tables
        //       if we have no filter nor this bit is set.
        if((parameterMask & CONVO_PARAM_MASK_PARTTICIPANTS) != 0) {
            do {
                BluetoothMapConvoContactElement c = new BluetoothMapConvoContactElement();
                if((parameterMask & CONVO_PARAM_MASK_PART_X_BT_UID) != 0) {
                    c.setBtUid(new SignedLongLong(tmpCursor.getLong(fi.mContactColBtUid),0));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_CHAT_STATE) != 0) {
                    c.setChatState(tmpCursor.getInt(fi.mContactColChatState));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_PRESENCE) != 0) {
                    c.setPresenceAvailability(tmpCursor.getInt(fi.mContactColPresenceState));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_PRESENCE_TEXT) != 0) {
                    c.setPresenceStatus(tmpCursor.getString(fi.mContactColPresenceText));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_PRIORITY) != 0) {
                    c.setPriority(tmpCursor.getInt(fi.mContactColPriority));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_DISP_NAME) != 0) {
                    c.setDisplayName(tmpCursor.getString(fi.mContactColNickname));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_UCI) != 0) {
                    c.setContactId(tmpCursor.getString(fi.mContactColContactUci));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_LAST_ACTIVITY) != 0) {
                    c.setLastActivity(tmpCursor.getLong(fi.mContactColLastActive));
                }
                if((parameterMask & CONVO_PARAM_MASK_PART_NAME) != 0) {
                    c.setName(tmpCursor.getString(fi.mContactColName));
                }
                ele.addContact(c);
            } while (tmpCursor.moveToNext() == true
                    && tmpCursor.getLong(fi.mConvoColConvoId) == threadId);
        }
    }

    /**
     * Extract the ConvoList parameters from appParams and build the matching URI with
     * query parameters.
     * @param ap the appParams from the request
     * @param contentUri the URI to append parameters to
     * @return the new URI with the appended parameters (if any)
     */
    private Uri appendConvoListQueryParameters(BluetoothMapAppParams ap,
            Uri contentUri) {
        Builder newUri = contentUri.buildUpon();
        String str = ap.getFilterRecipient();
        if(str != null) {
            str = str.trim();
            str = str.replace("*", "%");
            newUri.appendQueryParameter(BluetoothMapContract.FILTER_ORIGINATOR_SUBSTRING, str);
        }
        long time = ap.getFilterLastActivityBegin();
        if(time > 0) {
            newUri.appendQueryParameter(BluetoothMapContract.FILTER_PERIOD_BEGIN,
                    Long.toString(time));
        }
        time = ap.getFilterLastActivityEnd();
        if(time > 0) {
            newUri.appendQueryParameter(BluetoothMapContract.FILTER_PERIOD_END,
                    Long.toString(time));
        }
        int readStatus = ap.getFilterReadStatus();
        if(readStatus > 0) {
            if(readStatus == 1) {
                // Conversations with Unread messages only
                newUri.appendQueryParameter(BluetoothMapContract.FILTER_READ_STATUS,
                        "false");
            }else if(readStatus == 2) {
                // Conversations with all read messages only
                newUri.appendQueryParameter(BluetoothMapContract.FILTER_READ_STATUS,
                        "true");
            }
            // if both are set it will be the same as requesting an empty list, but
            // as it makes no sense with such a structure in a bit mask, we treat
            // requesting both the same as no filtering.
        }
        long convoId = -1;
        if(ap.getFilterConvoId() != null) {
            convoId = ap.getFilterConvoId().getLeastSignificantBits();
        }
        if(convoId > 0) {
            newUri.appendQueryParameter(BluetoothMapContract.FILTER_THREAD_ID,
                    Long.toString(convoId));
        }
        return newUri.build();
    }

    /**
     * Procedure if we have a filter:
     *  - loop through all ids to examine if there is a match (this will build the cache)
     *  - If there is a match loop again to add all contacts.
     *
     * Procedure if we don't have a filter
     *  - Add all contacts
     *
     * @param convoElement
     * @param contacts
     * @param idsStr
     * @param recipientFilter
     * @return
     */
    private boolean addSmsMmsContacts( BluetoothMapConvoListingElement convoElement,
            SmsMmsContacts contacts, String idsStr, String recipientFilter,
            BluetoothMapAppParams ap) {
        BluetoothMapConvoContactElement contactElement;
        int parameterMask = (int) ap.getConvoParameterMask(); // We always set a default value
        boolean foundContact = false;
        String[] ids = idsStr.split(" ");
        long[] longIds = new long[ids.length];
        if(recipientFilter != null) {
            recipientFilter = recipientFilter.trim();
        }

        for (int i = 0; i < ids.length; i++) {
            long longId;
            try {
                longId = Long.parseLong(ids[i]);
                longIds[i] = longId;
                if(recipientFilter == null) {
                    // If there is not filter, all we need to do is to parse the ids
                    foundContact = true;
                    continue;
                }
                String addr = contacts.getPhoneNumber(mResolver, longId);
                if(addr == null) {
                    // This can only happen if all messages from a contact is deleted while
                    // performing the query.
                    continue;
                }
                MapContact contact =
                        contacts.getContactNameFromPhone(addr, mResolver, recipientFilter);
                if(D) {
                    Log.d(TAG, "  id " + longId + ": " + addr);
                    if(contact != null) {
                        Log.d(TAG,"  contact name: " + contact.getName() + "  X-BT-UID: "
                                + contact.getXBtUid());
                    }
                }
                if(contact == null) {
                    continue;
                }
                foundContact = true;
            } catch (NumberFormatException ex) {
                // skip this id
                continue;
            }
        }

        if(foundContact == true) {
            foundContact = false;
            for (long id : longIds) {
                String addr = contacts.getPhoneNumber(mResolver, id);
                if(addr == null) {
                    // This can only happen if all messages from a contact is deleted while
                    // performing the query.
                    continue;
                }
                foundContact = true;
                MapContact contact = contacts.getContactNameFromPhone(addr, mResolver);

                if(contact == null) {
                    // We do not have a contact, we need to manually add one
                    contactElement = new BluetoothMapConvoContactElement();
                    if((parameterMask & CONVO_PARAM_MASK_PART_NAME) != 0) {
                        contactElement.setName(addr); // Use the phone number as name
                    }
                    if((parameterMask & CONVO_PARAM_MASK_PART_UCI) != 0) {
                        contactElement.setContactId(addr);
                    }
                } else {
                    contactElement = BluetoothMapConvoContactElement
                            .createFromMapContact(contact, addr);
                    // Remove the parameters not to be reported
                    if((parameterMask & CONVO_PARAM_MASK_PART_UCI) == 0) {
                        contactElement.setContactId(null);
                    }
                    if((parameterMask & CONVO_PARAM_MASK_PART_X_BT_UID) == 0) {
                        contactElement.setBtUid(null);
                    }
                    if((parameterMask & CONVO_PARAM_MASK_PART_DISP_NAME) == 0) {
                        contactElement.setDisplayName(null);
                    }
                }
                convoElement.addContact(contactElement);
            }
        }
        return foundContact;
    }

    /**
     * Get the folder name of an SMS message or MMS message.
     * @param c the cursor pointing at the message
     * @return the folder name.
     */
    private String getFolderName(int type, int threadId) {

        if(threadId == -1)
            return BluetoothMapContract.FOLDER_NAME_DELETED;

        switch(type) {
        case 1:
            return BluetoothMapContract.FOLDER_NAME_INBOX;
        case 2:
            return BluetoothMapContract.FOLDER_NAME_SENT;
        case 3:
            return BluetoothMapContract.FOLDER_NAME_DRAFT;
        case 4: // Just name outbox, failed and queued "outbox"
        case 5:
        case 6:
            return BluetoothMapContract.FOLDER_NAME_OUTBOX;
        }
        return "";
    }

    public byte[] getMessage(String handle, BluetoothMapAppParams appParams,
            BluetoothMapFolderElement folderElement, String version)
            throws UnsupportedEncodingException{
        TYPE type = BluetoothMapUtils.getMsgTypeFromHandle(handle);
        mMessageVersion = version;
        long id = BluetoothMapUtils.getCpHandle(handle);
        if(appParams.getFractionRequest() == BluetoothMapAppParams.FRACTION_REQUEST_NEXT) {
            throw new IllegalArgumentException("FRACTION_REQUEST_NEXT does not make sence as" +
                                               " we always return the full message.");
        }
        switch(type) {
        case SMS_GSM:
        case SMS_CDMA:
            return getSmsMessage(id, appParams.getCharset());
        case MMS:
            return getMmsMessage(id, appParams);
        case EMAIL:
            return getEmailMessage(id, appParams, folderElement);
        case IM:
            return getIMMessage(id, appParams, folderElement);
        }
        throw new IllegalArgumentException("Invalid message handle.");
    }

    private String setVCardFromPhoneNumber(BluetoothMapbMessage message,
            String phone, boolean incoming) {
        String contactId = null, contactName = null;
        String[] phoneNumbers = new String[1];
        //Handle possible exception for empty phone address
        if (TextUtils.isEmpty(phone)) {
            return contactName;
        }
        //
        // Use only actual phone number, because the MCE cannot know which
        // number the message is from.
        //
        phoneNumbers[0] = phone;
        String[] emailAddresses = null;
        Cursor p;

        Uri uri = Uri
                .withAppendedPath(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI,
                Uri.encode(phone));

        String[] projection = {Contacts._ID, Contacts.DISPLAY_NAME};
        String selection = Contacts.IN_VISIBLE_GROUP + "=1";
        String orderBy = Contacts._ID + " ASC";

        // Get the contact _ID and name
        p = mResolver.query(uri, projection, selection, null, orderBy);
        try {
            if (p != null && p.moveToFirst()) {
                contactId = p.getString(p.getColumnIndex(Contacts._ID));
                contactName = p.getString(p.getColumnIndex(Contacts.DISPLAY_NAME));
            }
        } finally {
            close(p);
        }
        // Bail out if we are unable to find a contact, based on the phone number
        if (contactId != null) {
            Cursor q = null;
            // Fetch the contact e-mail addresses
            try {
                q = mResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{contactId},
                        null);
                if (q != null && q.moveToFirst()) {
                    int i = 0;
                    emailAddresses = new String[q.getCount()];
                    do {
                        String emailAddress = q.getString(q.getColumnIndex(
                                ContactsContract.CommonDataKinds.Email.ADDRESS));
                        emailAddresses[i++] = emailAddress;
                    } while (q != null && q.moveToNext());
                }
            } finally {
                close(q);
            }
        }

        if (incoming == true) {
            if(V) Log.d(TAG, "Adding originator for phone:" + phone);
            // Use version 3.0 as we only have a formatted name
            message.addOriginator(contactName, contactName, phoneNumbers, emailAddresses,null,null);
        } else {
            if(V) Log.d(TAG, "Adding recipient for phone:" + phone);
            // Use version 3.0 as we only have a formatted name
            message.addRecipient(contactName, contactName, phoneNumbers, emailAddresses,null,null);
        }
        return contactName;
    }

    public static final int MAP_MESSAGE_CHARSET_NATIVE = 0;
    public static final int MAP_MESSAGE_CHARSET_UTF8 = 1;

    public byte[] getSmsMessage(long id, int charset) throws UnsupportedEncodingException{
        int type, threadId;
        long time = -1;
        String msgBody;
        BluetoothMapbMessageSms message = new BluetoothMapbMessageSms();
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);

        Cursor c = mResolver.query(Sms.CONTENT_URI, SMS_PROJECTION, "_ID = " + id, null, null);
        if (c == null || !c.moveToFirst()) {
            throw new IllegalArgumentException("SMS handle not found");
        }

        try{
            if(c != null && c.moveToFirst())
            {
                if(V) Log.v(TAG,"c.count: " + c.getCount());

                if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
                    message.setType(TYPE.SMS_GSM);
                } else if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
                    message.setType(TYPE.SMS_CDMA);
                }
                message.setVersionString(mMessageVersion);
                String read = c.getString(c.getColumnIndex(Sms.READ));
                if (read.equalsIgnoreCase("1"))
                    message.setStatus(true);
                else
                    message.setStatus(false);

                type = c.getInt(c.getColumnIndex(Sms.TYPE));
                threadId = c.getInt(c.getColumnIndex(Sms.THREAD_ID));
                message.setFolder(getFolderName(type, threadId));

                msgBody = c.getString(c.getColumnIndex(Sms.BODY));

                String phone = c.getString(c.getColumnIndex(Sms.ADDRESS));
                if ((phone == null) && type == Sms.MESSAGE_TYPE_DRAFT) {
                    //Fetch address for Drafts folder from "canonical_address" table
                    phone  = getCanonicalAddressSms(mResolver, threadId);
                }
                time = c.getLong(c.getColumnIndex(Sms.DATE));
                if(type == 1) // Inbox message needs to set the vCard as originator
                    setVCardFromPhoneNumber(message, phone, true);
                else          // Other messages sets the vCard as the recipient
                    setVCardFromPhoneNumber(message, phone, false);

                if(charset == MAP_MESSAGE_CHARSET_NATIVE) {
                    if(type == 1) //Inbox
                        message.setSmsBodyPdus(BluetoothMapSmsPdu.getDeliverPdus(msgBody,
                                    phone, time));
                    else
                        message.setSmsBodyPdus(BluetoothMapSmsPdu.getSubmitPdus(msgBody, phone));
                } else /*if (charset == MAP_MESSAGE_CHARSET_UTF8)*/ {
                    message.setSmsBody(msgBody);
                }
                return message.encode();
            }
        } finally {
            if (c != null) c.close();
        }

        return message.encode();
    }

    private void extractMmsAddresses(long id, BluetoothMapbMessageMime message) {
        final String[] projection = null;
        String selection = new String(Mms.Addr.MSG_ID + "=" + id);
        String uriStr = new String(Mms.CONTENT_URI + "/" + id + "/addr");
        Uri uriAddress = Uri.parse(uriStr);
        String contactName = null;

        Cursor c = mResolver.query( uriAddress, projection, selection, null, null);
        try {
            if (c.moveToFirst()) {
                do {
                    String address = c.getString(c.getColumnIndex(Mms.Addr.ADDRESS));
                    if(address.equals(INSERT_ADDRES_TOKEN))
                        continue;
                    Integer type = c.getInt(c.getColumnIndex(Mms.Addr.TYPE));
                    switch(type) {
                    case MMS_FROM:
                        contactName = setVCardFromPhoneNumber(message, address, true);
                        message.addFrom(contactName, address);
                        break;
                    case MMS_TO:
                        contactName = setVCardFromPhoneNumber(message, address, false);
                        message.addTo(contactName, address);
                        break;
                    case MMS_CC:
                        contactName = setVCardFromPhoneNumber(message, address, false);
                        message.addCc(contactName, address);
                        break;
                    case MMS_BCC:
                        contactName = setVCardFromPhoneNumber(message, address, false);
                        message.addBcc(contactName, address);
                        break;
                    default:
                        break;
                    }
                } while(c.moveToNext());
            }
        } finally {
            if (c != null) c.close();
        }
    }


    /**
     * Read out a mime data part and return the data in a byte array.
     * @param contentPartUri TODO
     * @param partid the content provider id of the Mime Part.
     * @return
     */
    private byte[] readRawDataPart(Uri contentPartUri, long partid) {
        String uriStr = new String(contentPartUri+"/"+ partid);
        Uri uriAddress = Uri.parse(uriStr);
        InputStream is = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int bufferSize = 8192;
        byte[] buffer = new byte[bufferSize];
        byte[] retVal = null;

        try {
            is = mResolver.openInputStream(uriAddress);
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
              os.write(buffer, 0, len); // We need to specify the len, as it can be != bufferSize
            }
            retVal = os.toByteArray();
        } catch (IOException e) {
            // do nothing for now
            Log.w(TAG,"Error reading part data",e);
        } finally {
            close(os);
            close(is);
        }
        return retVal;
    }

    /**
     * Read out the mms parts and update the bMessage object provided i {@linkplain message}
     * @param id the content provider ID of the message
     * @param message the bMessage object to add the information to
     */
    private void extractMmsParts(long id, BluetoothMapbMessageMime message)
    {
        /* Handling of filtering out non-text parts for exclude
         * attachments is handled within the bMessage object. */
        final String[] projection = null;
        String selection = new String(Mms.Part.MSG_ID + "=" + id);
        String uriStr = new String(Mms.CONTENT_URI + "/"+ id + "/part");
        Uri uriAddress = Uri.parse(uriStr);
        BluetoothMapbMessageMime.MimePart part;
        Cursor c = mResolver.query(uriAddress, projection, selection, null, null);
        try {
            if (c.moveToFirst()) {
                do {
                    Long partId = c.getLong(c.getColumnIndex(BaseColumns._ID));
                    String contentType = c.getString(c.getColumnIndex(Mms.Part.CONTENT_TYPE));
                    String name = c.getString(c.getColumnIndex(Mms.Part.NAME));
                    String charset = c.getString(c.getColumnIndex(Mms.Part.CHARSET));
                    String filename = c.getString(c.getColumnIndex(Mms.Part.FILENAME));
                    String text = c.getString(c.getColumnIndex(Mms.Part.TEXT));
                    Integer fd = c.getInt(c.getColumnIndex(Mms.Part._DATA));
                    String cid = c.getString(c.getColumnIndex(Mms.Part.CONTENT_ID));
                    String cl = c.getString(c.getColumnIndex(Mms.Part.CONTENT_LOCATION));
                    String cdisp = c.getString(c.getColumnIndex(Mms.Part.CONTENT_DISPOSITION));

                    if(V) Log.d(TAG, "     _id : " + partId +
                            "\n     ct : " + contentType +
                            "\n     partname : " + name +
                            "\n     charset : " + charset +
                            "\n     filename : " + filename +
                            "\n     text : " + text +
                            "\n     fd : " + fd +
                            "\n     cid : " + cid +
                            "\n     cl : " + cl +
                            "\n     cdisp : " + cdisp);

                    part = message.addMimePart();
                    part.mContentType = contentType;
                    part.mPartName = name;
                    part.mContentId = cid;
                    part.mContentLocation = cl;
                    part.mContentDisposition = cdisp;

                    try {
                        if(text != null) {
                            part.mData = text.getBytes("UTF-8");
                            part.mCharsetName = "utf-8";
                        } else {
                            part.mData =
                                    readRawDataPart(Uri.parse(Mms.CONTENT_URI+"/part"), partId);
                            if(charset != null) {
                                part.mCharsetName =
                                        CharacterSets.getMimeName(Integer.parseInt(charset));
                            }
                        }
                    } catch (NumberFormatException e) {
                        Log.d(TAG,"extractMmsParts",e);
                        part.mData = null;
                        part.mCharsetName = null;
                    } catch (UnsupportedEncodingException e) {
                        Log.d(TAG,"extractMmsParts",e);
                        part.mData = null;
                        part.mCharsetName = null;
                    } finally {
                    }
                    part.mFileName = filename;
                } while(c.moveToNext());
                message.updateCharset();
            }

        } finally {
            if(c != null) c.close();
        }
    }
    /**
     * Read out the mms parts and update the bMessage object provided i {@linkplain message}
     * @param id the content provider ID of the message
     * @param message the bMessage object to add the information to
     */
    private void extractIMParts(long id, BluetoothMapbMessageMime message)
    {
        /* Handling of filtering out non-text parts for exclude
         * attachments is handled within the bMessage object. */
        final String[] projection = null;
        String selection = new String(BluetoothMapContract.MessageColumns._ID + "=" + id);
        String uriStr = new String(mBaseUri
                                         + BluetoothMapContract.TABLE_MESSAGE + "/"+ id + "/part");
        Uri uriAddress = Uri.parse(uriStr);
        BluetoothMapbMessageMime.MimePart part;
        Cursor c = mResolver.query(uriAddress, projection, selection, null, null);
        try{
            if (c.moveToFirst()) {
                do {
                    Long partId = c.getLong(
                                  c.getColumnIndex(BluetoothMapContract.MessagePartColumns._ID));
                    String charset = c.getString(
                           c.getColumnIndex(BluetoothMapContract.MessagePartColumns.CHARSET));
                    String filename = c.getString(
                           c.getColumnIndex(BluetoothMapContract.MessagePartColumns.FILENAME));
                    String text = c.getString(
                           c.getColumnIndex(BluetoothMapContract.MessagePartColumns.TEXT));
                    String body = c.getString(
                           c.getColumnIndex(BluetoothMapContract.MessagePartColumns.RAW_DATA));
                    String cid = c.getString(
                           c.getColumnIndex(BluetoothMapContract.MessagePartColumns.CONTENT_ID));

                    if(V) Log.d(TAG, "     _id : " + partId +
                            "\n     charset : " + charset +
                            "\n     filename : " + filename +
                            "\n     text : " + text +
                            "\n     cid : " + cid);

                    part = message.addMimePart();
                    part.mContentId = cid;
                    try {
                        if(text.equalsIgnoreCase("yes")) {
                            part.mData = body.getBytes("UTF-8");
                            part.mCharsetName = "utf-8";
                        } else {
                            part.mData = readRawDataPart(Uri.parse(mBaseUri
                                             + BluetoothMapContract.TABLE_MESSAGE_PART) , partId);
                            if(charset != null)
                                part.mCharsetName = CharacterSets.getMimeName(
                                                                        Integer.parseInt(charset));
                        }
                    } catch (NumberFormatException e) {
                        Log.d(TAG,"extractIMParts",e);
                        part.mData = null;
                        part.mCharsetName = null;
                    } catch (UnsupportedEncodingException e) {
                        Log.d(TAG,"extractIMParts",e);
                        part.mData = null;
                        part.mCharsetName = null;
                    } finally {
                    }
                    part.mFileName = filename;
                } while(c.moveToNext());
            }
        } finally {
            if(c != null) c.close();
        }

        message.updateCharset();
    }

    /**
     *
     * @param id the content provider id for the message to fetch.
     * @param appParams The application parameter object received from the client.
     * @return a byte[] containing the utf-8 encoded bMessage to send to the client.
     * @throws UnsupportedEncodingException if UTF-8 is not supported,
     * which is guaranteed to be supported on an android device
     */
    public byte[] getMmsMessage(long id,BluetoothMapAppParams appParams)
                                                        throws UnsupportedEncodingException {
        int msgBox, threadId;
        if (appParams.getCharset() == MAP_MESSAGE_CHARSET_NATIVE)
            throw new IllegalArgumentException("MMS charset native not allowed for MMS"
                                                                            +" - must be utf-8");

        BluetoothMapbMessageMime message = new BluetoothMapbMessageMime();
        Cursor c = mResolver.query(Mms.CONTENT_URI, MMS_PROJECTION, "_ID = " + id, null, null);
        try {
            if(c != null && c.moveToFirst())
            {
                message.setType(TYPE.MMS);
                message.setVersionString(mMessageVersion);

                // The MMS info:
                String read = c.getString(c.getColumnIndex(Mms.READ));
                if (read.equalsIgnoreCase("1"))
                    message.setStatus(true);
                else
                    message.setStatus(false);

                msgBox = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX));
                threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID));
                message.setFolder(getFolderName(msgBox, threadId));
                message.setSubject(c.getString(c.getColumnIndex(Mms.SUBJECT)));
                message.setMessageId(c.getString(c.getColumnIndex(Mms.MESSAGE_ID)));
                message.setContentType(c.getString(c.getColumnIndex(Mms.CONTENT_TYPE)));
                message.setDate(c.getLong(c.getColumnIndex(Mms.DATE)) * 1000L);
                message.setTextOnly(c.getInt(c.getColumnIndex(Mms.TEXT_ONLY)) == 0 ? false : true);
                message.setIncludeAttachments(appParams.getAttachment() == 0 ? false : true);
                // c.getLong(c.getColumnIndex(Mms.DATE_SENT)); - this is never used
                // c.getInt(c.getColumnIndex(Mms.STATUS)); - don't know what this is

                // The parts
                extractMmsParts(id, message);

                // The addresses
                extractMmsAddresses(id, message);


                return message.encode();
            }
        } finally {
            if (c != null) c.close();
        }

        return message.encode();
    }

    /**
    *
    * @param id the content provider id for the message to fetch.
    * @param appParams The application parameter object received from the client.
    * @return a byte[] containing the utf-8 encoded bMessage to send to the client.
    * @throws UnsupportedEncodingException if UTF-8 is not supported,
    * which is guaranteed to be supported on an android device
    */
   public byte[] getEmailMessage(long id, BluetoothMapAppParams appParams,
           BluetoothMapFolderElement currentFolder) throws UnsupportedEncodingException {
       // Log print out of application parameters set
       if(D && appParams != null) {
           Log.d(TAG,"TYPE_MESSAGE (GET): Attachment = " + appParams.getAttachment() +
                   ", Charset = " + appParams.getCharset() +
                   ", FractionRequest = " + appParams.getFractionRequest());
       }

       // Throw exception if requester NATIVE charset for Email
       // Exception is caught by MapObexServer sendGetMessageResp
       if (appParams.getCharset() == MAP_MESSAGE_CHARSET_NATIVE)
           throw new IllegalArgumentException("EMAIL charset not UTF-8");

       BluetoothMapbMessageEmail message = new BluetoothMapbMessageEmail();
       Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
       Cursor c = mResolver.query(contentUri, BluetoothMapContract.BT_MESSAGE_PROJECTION, "_ID = "
               + id, null, null);
       try {
           if(c != null && c.moveToFirst())
           {
               BluetoothMapFolderElement folderElement;
               FileInputStream is = null;
               ParcelFileDescriptor fd = null;
               try {
                   // Handle fraction requests
                   int fractionRequest = appParams.getFractionRequest();
                   if (fractionRequest != BluetoothMapAppParams.INVALID_VALUE_PARAMETER) {
                       // Fraction requested
                       if(V) {
                           String fractionStr = (fractionRequest == 0) ? "FIRST" : "NEXT";
                           Log.v(TAG, "getEmailMessage - FractionRequest " + fractionStr
                                   +  " - send compete message" );
                       }
                       // Check if message is complete and if not - request message from server
                       if (c.getString(c.getColumnIndex(
                               BluetoothMapContract.MessageColumns.RECEPTION_STATE)).equalsIgnoreCase(
                                       BluetoothMapContract.RECEPTION_STATE_COMPLETE) == false)  {
                           // TODO: request message from server
                           Log.w(TAG, "getEmailMessage - receptionState not COMPLETE -  Not Implemented!" );
                       }
                   }
                   // Set read status:
                   String read = c.getString(
                                        c.getColumnIndex(BluetoothMapContract.MessageColumns.FLAG_READ));
                   if (read != null && read.equalsIgnoreCase("1"))
                       message.setStatus(true);
                   else
                       message.setStatus(false);

                   // Set message type:
                   message.setType(TYPE.EMAIL);
                   message.setVersionString(mMessageVersion);
                   // Set folder:
                   long folderId = c.getLong(
                                       c.getColumnIndex(BluetoothMapContract.MessageColumns.FOLDER_ID));
                   folderElement = currentFolder.getFolderById(folderId);
                   message.setCompleteFolder(folderElement.getFullPath());

                   // Set recipient:
                   String nameEmail = c.getString(
                                       c.getColumnIndex(BluetoothMapContract.MessageColumns.TO_LIST));
                   Rfc822Token tokens[] = Rfc822Tokenizer.tokenize(nameEmail);
                   if (tokens.length != 0) {
                       if(D) Log.d(TAG, "Recipient count= " + tokens.length);
                       int i = 0;
                       while (i < tokens.length) {
                           if(V) Log.d(TAG, "Recipient = " + tokens[i].toString());
                           String[] emails = new String[1];
                           emails[0] = tokens[i].getAddress();
                           String name = tokens[i].getName();
                           message.addRecipient(name, name, null, emails, null, null);
                           i++;
                       }
                   }

                   // Set originator:
                   nameEmail = c.getString(c.getColumnIndex(BluetoothMapContract.MessageColumns.FROM_LIST));
                   tokens = Rfc822Tokenizer.tokenize(nameEmail);
                   if (tokens.length != 0) {
                       if(D) Log.d(TAG, "Originator count= " + tokens.length);
                       int i = 0;
                       while (i < tokens.length) {
                           if(V) Log.d(TAG, "Originator = " + tokens[i].toString());
                           String[] emails = new String[1];
                           emails[0] = tokens[i].getAddress();
                           String name = tokens[i].getName();
                           message.addOriginator(name, name, null, emails, null, null);
                           i++;
                       }
                   }
               } finally {
                   if(c != null) c.close();
               }
               // Find out if we get attachments
               String attStr = (appParams.getAttachment() == 0) ?
                                           "/" +  BluetoothMapContract.FILE_MSG_NO_ATTACHMENTS : "";
               Uri uri = Uri.parse(contentUri + "/" + id + attStr);

               // Get email message body content
               int count = 0;
               try {
                   fd = mResolver.openFileDescriptor(uri, "r");
                   is = new FileInputStream(fd.getFileDescriptor());
                   StringBuilder email = new StringBuilder("");
                   byte[] buffer = new byte[1024];
                   while((count = is.read(buffer)) != -1) {
                       // TODO: Handle breaks within a UTF8 character
                       email.append(new String(buffer,0,count));
                       if(V) Log.d(TAG, "Email part = "
                                         + new String(buffer,0,count)
                                         + " count=" + count);
                   }
                   // Set email message body:
                   message.setEmailBody(email.toString());
               } catch (FileNotFoundException e) {
                   Log.w(TAG, e);
               } catch (NullPointerException e) {
                   Log.w(TAG, e);
               } catch (IOException e) {
                   Log.w(TAG, e);
               } finally {
                   try {
                       if(is != null) is.close();
                   } catch (IOException e) {}
                   try {
                       if(fd != null) fd.close();
                   } catch (IOException e) {}
               }
               return message.encode();
           }
       } finally {
           if (c != null) c.close();
       }
       throw new IllegalArgumentException("EMAIL handle not found");
   }
   /**
   *
   * @param id the content provider id for the message to fetch.
   * @param appParams The application parameter object received from the client.
   * @return a byte[] containing the UTF-8 encoded bMessage to send to the client.
   * @throws UnsupportedEncodingException if UTF-8 is not supported,
   * which is guaranteed to be supported on an android device
   */

   /**
   *
   * @param id the content provider id for the message to fetch.
   * @param appParams The application parameter object received from the client.
   * @return a byte[] containing the utf-8 encoded bMessage to send to the client.
   * @throws UnsupportedEncodingException if UTF-8 is not supported,
   * which is guaranteed to be supported on an android device
   */
   public byte[] getIMMessage(long id,
           BluetoothMapAppParams appParams,
           BluetoothMapFolderElement folderElement)
                   throws UnsupportedEncodingException {
       long threadId, folderId;

       if (appParams.getCharset() == MAP_MESSAGE_CHARSET_NATIVE)
           throw new IllegalArgumentException(
                   "IM charset native not allowed for IM - must be utf-8");

       BluetoothMapbMessageMime message = new BluetoothMapbMessageMime();
       Uri contentUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_MESSAGE);
       Cursor c = mResolver.query(contentUri,
               BluetoothMapContract.BT_MESSAGE_PROJECTION, "_ID = " + id, null, null);
       Cursor contacts = null;
       try {
           if(c != null && c.moveToFirst()) {
               message.setType(TYPE.IM);
               message.setVersionString(mMessageVersion);

               // The IM message info:
               int read =
                       c.getInt(c.getColumnIndex(BluetoothMapContract.MessageColumns.FLAG_READ));
               if (read == 1)
                   message.setStatus(true);
               else
                   message.setStatus(false);

               threadId =
                       c.getInt(c.getColumnIndex(BluetoothMapContract.MessageColumns.THREAD_ID));
               folderId =
                       c.getLong(c.getColumnIndex(BluetoothMapContract.MessageColumns.FOLDER_ID));
               folderElement = folderElement.getFolderById(folderId);
               message.setCompleteFolder(folderElement.getFullPath());
               message.setSubject(c.getString(
                       c.getColumnIndex(BluetoothMapContract.MessageColumns.SUBJECT)));
               message.setMessageId(c.getString(
                       c.getColumnIndex(BluetoothMapContract.MessageColumns._ID)));
               message.setDate(c.getLong(
                       c.getColumnIndex(BluetoothMapContract.MessageColumns.DATE)));
               message.setTextOnly(c.getInt(c.getColumnIndex(
                       BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE)) != 0 ? false : true);

               message.setIncludeAttachments(appParams.getAttachment() == 0 ? false : true);

               // c.getLong(c.getColumnIndex(Mms.DATE_SENT)); - this is never used
               // c.getInt(c.getColumnIndex(Mms.STATUS)); - don't know what this is

               // The parts

               //FIXME use the parts when ready - until then use the body column for text-only
               //  extractIMParts(id, message);
               //FIXME next few lines are temporary code
               MimePart part = message.addMimePart();
               part.mData = c.getString((c.getColumnIndex(
                       BluetoothMapContract.MessageColumns.BODY))).getBytes("UTF-8");
               part.mCharsetName = "utf-8";
               part.mContentId = "0";
               part.mContentType = "text/plain";
               message.updateCharset();
               // FIXME end temp code

               Uri contactsUri = Uri.parse(mBaseUri + BluetoothMapContract.TABLE_CONVOCONTACT);
               contacts = mResolver.query(contactsUri,
                       BluetoothMapContract.BT_CONTACT_PROJECTION,
                       BluetoothMapContract.ConvoContactColumns.CONVO_ID
                       + " = " + threadId, null, null);
               // TODO this will not work for group-chats
               if(contacts != null && contacts.moveToFirst()){
                   String name = contacts.getString(contacts.getColumnIndex(
                           BluetoothMapContract.ConvoContactColumns.NAME));
                   String btUid[] = new String[1];
                   btUid[0]= contacts.getString(contacts.getColumnIndex(
                           BluetoothMapContract.ConvoContactColumns.X_BT_UID));
                   String nickname = contacts.getString(contacts.getColumnIndex(
                           BluetoothMapContract.ConvoContactColumns.NICKNAME));
                   String btUci[] = new String[1];
                   String btOwnUci[] = new String[1];
                   btOwnUci[0] = mAccount.getUciFull();
                   btUci[0] = contacts.getString(contacts.getColumnIndex(
                           BluetoothMapContract.ConvoContactColumns.UCI));
                   if(folderId == BluetoothMapContract.FOLDER_ID_SENT
                           || folderId == BluetoothMapContract.FOLDER_ID_OUTBOX) {
                       message.addRecipient(nickname,name,null, null, btUid, btUci);
                       message.addOriginator(null, btOwnUci);

                   }else {
                       message.addOriginator(nickname,name,null, null, btUid, btUci);
                       message.addRecipient(null, btOwnUci);

                   }
               }
               return message.encode();
           }
       } finally {
           if(c != null) c.close();
           if(contacts != null) contacts.close();
       }

       throw new IllegalArgumentException("IM handle not found");
   }

   public void setRemoteFeatureMask(int featureMask){
       this.mRemoteFeatureMask = featureMask;
       if(V) Log.d(TAG, "setRemoteFeatureMask");
       if((this.mRemoteFeatureMask & BluetoothMapUtils.MAP_FEATURE_MESSAGE_LISTING_FORMAT_V11_BIT)
               == BluetoothMapUtils.MAP_FEATURE_MESSAGE_LISTING_FORMAT_V11_BIT) {
           if(V) Log.d(TAG, "setRemoteFeatureMask MAP_MESSAGE_LISTING_FORMAT_V11");
           this.mMsgListingVersion = BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11;
       }
   }

   public int getRemoteFeatureMask(){
       return this.mRemoteFeatureMask;
   }

    HashMap<Long,BluetoothMapConvoListingElement> getSmsMmsConvoList() {
        return mMasInstance.getSmsMmsConvoList();
    }

    void setSmsMmsConvoList(HashMap<Long,BluetoothMapConvoListingElement> smsMmsConvoList) {
        mMasInstance.setSmsMmsConvoList(smsMmsConvoList);
    }

    HashMap<Long,BluetoothMapConvoListingElement> getImEmailConvoList() {
        return mMasInstance.getImEmailConvoList();
    }

    void setImEmailConvoList(HashMap<Long,BluetoothMapConvoListingElement> imEmailConvoList) {
        mMasInstance.setImEmailConvoList(imEmailConvoList);
    }
}