summaryrefslogtreecommitdiffstats
path: root/src/com/android/bluetooth/map/BluetoothMapContentObserver.java
blob: 92899c23aeb31f82f722a113e239452479770edc (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
/*
 * 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.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteException;
import android.provider.Telephony;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.Sms;
import android.provider.Telephony.Sms.Inbox;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.EventLog;
import android.util.Log;
import android.util.Xml;
import android.text.TextUtils;

import org.xmlpull.v1.XmlSerializer;

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.MessageColumns;
import com.google.android.mms.pdu.PduHeaders;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.obex.ResponseCodes;

@TargetApi(19)
public class BluetoothMapContentObserver {
    private static final String TAG = "BluetoothMapContentObserver";

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

    private static final String EVENT_TYPE_NEW              = "NewMessage";
    private static final String EVENT_TYPE_DELETE           = "MessageDeleted";
    private static final String EVENT_TYPE_REMOVED          = "MessageRemoved";
    private static final String EVENT_TYPE_SHIFT            = "MessageShift";
    private static final String EVENT_TYPE_DELEVERY_SUCCESS = "DeliverySuccess";
    private static final String EVENT_TYPE_SENDING_SUCCESS  = "SendingSuccess";
    private static final String EVENT_TYPE_SENDING_FAILURE  = "SendingFailure";
    private static final String EVENT_TYPE_DELIVERY_FAILURE = "DeliveryFailure";
    private static final String EVENT_TYPE_READ_STATUS      = "ReadStatusChanged";
    private static final String EVENT_TYPE_CONVERSATION     = "ConversationChanged";
    private static final String EVENT_TYPE_PRESENCE         = "ParticipantPresenceChanged";
    private static final String EVENT_TYPE_CHAT_STATE       = "ParticipantChatStateChanged";

    private static final long EVENT_FILTER_NEW_MESSAGE                  = 1L;
    private static final long EVENT_FILTER_MESSAGE_DELETED              = 1L<<1;
    private static final long EVENT_FILTER_MESSAGE_SHIFT                = 1L<<2;
    private static final long EVENT_FILTER_SENDING_SUCCESS              = 1L<<3;
    private static final long EVENT_FILTER_SENDING_FAILED               = 1L<<4;
    private static final long EVENT_FILTER_DELIVERY_SUCCESS             = 1L<<5;
    private static final long EVENT_FILTER_DELIVERY_FAILED              = 1L<<6;
    private static final long EVENT_FILTER_MEMORY_FULL                  = 1L<<7; // Unused
    private static final long EVENT_FILTER_MEMORY_AVAILABLE             = 1L<<8; // Unused
    private static final long EVENT_FILTER_READ_STATUS_CHANGED          = 1L<<9;
    private static final long EVENT_FILTER_CONVERSATION_CHANGED         = 1L<<10;
    private static final long EVENT_FILTER_PARTICIPANT_PRESENCE_CHANGED = 1L<<11;
    private static final long EVENT_FILTER_PARTICIPANT_CHATSTATE_CHANGED= 1L<<12;
    private static final long EVENT_FILTER_MESSAGE_REMOVED              = 1L<<13;

    // TODO: If we are requesting a large message from the network, on a slow connection
    //       20 seconds might not be enough... But then again 20 seconds is long for other
    //       cases.
    private static final long PROVIDER_ANR_TIMEOUT = 20 * DateUtils.SECOND_IN_MILLIS;

    private Context mContext;
    private ContentResolver mResolver;
    private ContentProviderClient mProviderClient = null;
    private BluetoothMnsObexClient mMnsClient;
    private BluetoothMapMasInstance mMasInstance = null;
    private int mMasId;
    private boolean mEnableSmsMms = false;
    private boolean mObserverRegistered = false;
    private BluetoothMapAccountItem mAccount;
    private String mAuthority = null;

    // Default supported feature bit mask is 0x1f
    private int mMapSupportedFeatures = BluetoothMapUtils.MAP_FEATURE_DEFAULT_BITMASK;
    // Default event report version is 1.0
    private int mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V10;

    private BluetoothMapFolderElement mFolders =
            new BluetoothMapFolderElement("DUMMY", null); // Will be set by the MAS when generated.
    private Uri mMessageUri = null;
    private Uri mContactUri = null;

    private boolean mTransmitEvents = true;

    /* To make the filter update atomic, we declare it volatile.
     * To avoid a penalty when using it, copy the value to a local
     * non-volatile variable when used more than once.
     * Actually we only ever use the lower 4 bytes of this variable,
     * hence we could manage without the volatile keyword, but as
     * we tend to copy ways of doing things, we better do it right:-) */
    private volatile long mEventFilter = 0xFFFFFFFFL;

    public static final int DELETED_THREAD_ID = -1;

    // X-Mms-Message-Type field types. These are from PduHeaders.java
    public static final int MESSAGE_TYPE_RETRIEVE_CONF = 0x84;

    // Text only MMS converted to SMS if sms parts less than or equal to defined count
    private static final int CONVERT_MMS_TO_SMS_PART_COUNT = 10;

    private TYPE mSmsType;

    private static final String ACTION_MESSAGE_DELIVERY =
            "com.android.bluetooth.BluetoothMapContentObserver.action.MESSAGE_DELIVERY";
    /*package*/ static final String ACTION_MESSAGE_SENT =
        "com.android.bluetooth.BluetoothMapContentObserver.action.MESSAGE_SENT";

    public static final String EXTRA_MESSAGE_SENT_HANDLE = "HANDLE";
    public static final String EXTRA_MESSAGE_SENT_RESULT = "result";
    public static final String EXTRA_MESSAGE_SENT_MSG_TYPE = "type";
    public static final String EXTRA_MESSAGE_SENT_URI = "uri";
    public static final String EXTRA_MESSAGE_SENT_RETRY = "retry";
    public static final String EXTRA_MESSAGE_SENT_TRANSPARENT = "transparent";
    public static final String EXTRA_MESSAGE_SENT_TIMESTAMP = "timestamp";

    private SmsBroadcastReceiver mSmsBroadcastReceiver = new SmsBroadcastReceiver();

    private boolean mInitialized = false;


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

    static final String[] SMS_PROJECTION_SHORT = new String[] {
        Sms._ID,
        Sms.THREAD_ID,
        Sms.TYPE,
        Sms.READ
    };

    static final String[] SMS_PROJECTION_SHORT_EXT = new String[] {
        Sms._ID,
        Sms.THREAD_ID,
        Sms.ADDRESS,
        Sms.BODY,
        Sms.DATE,
        Sms.READ,
        Sms.TYPE,
    };

    static final String[] MMS_PROJECTION_SHORT = new String[] {
        Mms._ID,
        Mms.THREAD_ID,
        Mms.MESSAGE_TYPE,
        Mms.MESSAGE_BOX,
        Mms.READ
    };

    static final String[] MMS_PROJECTION_SHORT_EXT = new String[] {
        Mms._ID,
        Mms.THREAD_ID,
        Mms.MESSAGE_TYPE,
        Mms.MESSAGE_BOX,
        Mms.READ,
        Mms.DATE,
        Mms.SUBJECT,
        Mms.PRIORITY
    };

    static final String[] MSG_PROJECTION_SHORT = new String[] {
        BluetoothMapContract.MessageColumns._ID,
        BluetoothMapContract.MessageColumns.FOLDER_ID,
        BluetoothMapContract.MessageColumns.FLAG_READ
    };

    static final String[] MSG_PROJECTION_SHORT_EXT = new String[] {
        BluetoothMapContract.MessageColumns._ID,
        BluetoothMapContract.MessageColumns.FOLDER_ID,
        BluetoothMapContract.MessageColumns.FLAG_READ,
        BluetoothMapContract.MessageColumns.DATE,
        BluetoothMapContract.MessageColumns.SUBJECT,
        BluetoothMapContract.MessageColumns.FROM_LIST,
        BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY
    };

    static final String[] MSG_PROJECTION_SHORT_EXT2 = new String[] {
        BluetoothMapContract.MessageColumns._ID,
        BluetoothMapContract.MessageColumns.FOLDER_ID,
        BluetoothMapContract.MessageColumns.FLAG_READ,
        BluetoothMapContract.MessageColumns.DATE,
        BluetoothMapContract.MessageColumns.SUBJECT,
        BluetoothMapContract.MessageColumns.FROM_LIST,
        BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY,
        BluetoothMapContract.MessageColumns.THREAD_ID,
        BluetoothMapContract.MessageColumns.THREAD_NAME
    };

    public BluetoothMapContentObserver(final Context context,
            BluetoothMnsObexClient mnsClient,
            BluetoothMapMasInstance masInstance,
            BluetoothMapAccountItem account,
            boolean enableSmsMms) throws RemoteException {
        mContext = context;
        mResolver = mContext.getContentResolver();
        mAccount = account;
        mMasInstance = masInstance;
        mMasId = mMasInstance.getMasId();

        mMapSupportedFeatures = mMasInstance.getRemoteFeatureMask();
        if (D) Log.d(TAG, "BluetoothMapContentObserver: Supported features " +
                Integer.toHexString(mMapSupportedFeatures) ) ;

        if((BluetoothMapUtils.MAP_FEATURE_EXTENDED_EVENT_REPORT_11_BIT
                & mMapSupportedFeatures) != 0){
            mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11;
        }
        // Make sure support for all formats result in latest version returned
        if((BluetoothMapUtils.MAP_FEATURE_EVENT_REPORT_V12_BIT
                & mMapSupportedFeatures) != 0){
            mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12;
        }

        if(account != null) {
            mAuthority = Uri.parse(account.mBase_uri).getAuthority();
            mMessageUri = Uri.parse(account.mBase_uri + "/" + BluetoothMapContract.TABLE_MESSAGE);
            if (mAccount.getType() == TYPE.IM) {
                mContactUri = Uri.parse(account.mBase_uri + "/"
                        + BluetoothMapContract.TABLE_CONVOCONTACT);
            }
            // TODO: We need to release this again!
            mProviderClient = mResolver.acquireUnstableContentProviderClient(mAuthority);
            if (mProviderClient == null) {
                throw new RemoteException("Failed to acquire provider for " + mAuthority);
            }
            mProviderClient.setDetectNotResponding(PROVIDER_ANR_TIMEOUT);
            mContactList = mMasInstance.getContactList();
            if(mContactList == null) {
                setContactList(new HashMap<String, BluetoothMapConvoContactElement>(), false);
                initContactsList();
            }
        }
        mEnableSmsMms = enableSmsMms;
        mSmsType = getSmsType();
        mMnsClient = mnsClient;
        /* Get the cached list - if any, else create */
        mMsgListSms = mMasInstance.getMsgListSms();
        boolean doInit = false;
        if(mEnableSmsMms) {
            if(mMsgListSms == null) {
                setMsgListSms(new HashMap<Long, Msg>(), false);
                doInit = true;
            }
            mMsgListMms = mMasInstance.getMsgListMms();
            if(mMsgListMms == null) {
                setMsgListMms(new HashMap<Long, Msg>(), false);
                doInit = true;
            }
        }
        if(mAccount != null) {
            mMsgListMsg = mMasInstance.getMsgListMsg();
            if(mMsgListMsg == null) {
                setMsgListMsg(new HashMap<Long, Msg>(), false);
                doInit = true;
            }
        }
        if(doInit) {
            initMsgList();
        }
    }

    public int getObserverRemoteFeatureMask() {
        if (V) Log.v(TAG, "getObserverRemoteFeatureMask : " + mMapEventReportVersion
            + " mMapSupportedFeatures: " + mMapSupportedFeatures);
        return mMapSupportedFeatures;
    }

    public void setObserverRemoteFeatureMask( int remoteSupportedFeatures) {
        mMapSupportedFeatures = remoteSupportedFeatures;
        if ((BluetoothMapUtils.MAP_FEATURE_EXTENDED_EVENT_REPORT_11_BIT
                & mMapSupportedFeatures) != 0) {
            mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11;
        }
        // Make sure support for all formats result in latest version returned
        if ((BluetoothMapUtils.MAP_FEATURE_EVENT_REPORT_V12_BIT
                & mMapSupportedFeatures) != 0) {
            mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12;
        }
        if (V) Log.d(TAG, "setObserverRemoteFeatureMask : " + mMapEventReportVersion
            + " mMapSupportedFeatures : " + mMapSupportedFeatures);
    }

    private Map<Long, Msg> getMsgListSms() {
        return mMsgListSms;
    }

    private void setMsgListSms(Map<Long, Msg> msgListSms, boolean changesDetected) {
        mMsgListSms = msgListSms;
        if(changesDetected) {
            mMasInstance.updateFolderVersionCounter();
        }
        mMasInstance.setMsgListSms(msgListSms);
    }


    private Map<Long, Msg> getMsgListMms() {
        return mMsgListMms;
    }


    private void setMsgListMms(Map<Long, Msg> msgListMms, boolean changesDetected) {
        mMsgListMms = msgListMms;
        if(changesDetected) {
            mMasInstance.updateFolderVersionCounter();
        }
        mMasInstance.setMsgListMms(msgListMms);
    }


    private Map<Long, Msg> getMsgListMsg() {
        return mMsgListMsg;
    }


    private void setMsgListMsg(Map<Long, Msg> msgListMsg, boolean changesDetected) {
        mMsgListMsg = msgListMsg;
        if(changesDetected) {
            mMasInstance.updateFolderVersionCounter();
        }
        mMasInstance.setMsgListMsg(msgListMsg);
    }

    private Map<String, BluetoothMapConvoContactElement> getContactList() {
        return mContactList;
    }


    /**
     * Currently we only have data for IM / email contacts
     * @param contactList
     * @param changesDetected that is not chat state changed nor presence state changed.
     */
    private void setContactList(Map<String, BluetoothMapConvoContactElement> contactList,
            boolean changesDetected) {
        mContactList = contactList;
        if(changesDetected) {
            mMasInstance.updateImEmailConvoListVersionCounter();
        }
        mMasInstance.setContactList(contactList);
    }

    private static boolean sendEventNewMessage(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_NEW_MESSAGE) > 0);
    }

    private static boolean sendEventMessageDeleted(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_MESSAGE_DELETED) > 0);
    }

    private static boolean sendEventMessageShift(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_MESSAGE_SHIFT) > 0);
    }

    private static boolean sendEventSendingSuccess(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_SENDING_SUCCESS) > 0);
    }

    private static boolean sendEventSendingFailed(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_SENDING_FAILED) > 0);
    }

    private static boolean sendEventDeliverySuccess(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_DELIVERY_SUCCESS) > 0);
    }

    private static boolean sendEventDeliveryFailed(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_DELIVERY_FAILED) > 0);
    }

    private static boolean sendEventReadStatusChanged(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_READ_STATUS_CHANGED) > 0);
    }

    private static boolean sendEventConversationChanged(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_CONVERSATION_CHANGED) > 0);
    }

    private static boolean sendEventParticipantPresenceChanged(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_PARTICIPANT_PRESENCE_CHANGED) > 0);
    }

    private static boolean sendEventParticipantChatstateChanged(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_PARTICIPANT_CHATSTATE_CHANGED) > 0);
    }

    private static boolean sendEventMessageRemoved(long eventFilter) {
        return ((eventFilter & EVENT_FILTER_MESSAGE_REMOVED) > 0);
    }

    private TYPE getSmsType() {
        TYPE smsType = null;
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);

        if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
            smsType = TYPE.SMS_CDMA;
        } else {
            smsType = TYPE.SMS_GSM;
        }

        return smsType;
    }

    private final ContentObserver mObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            if(uri == null) {
                Log.w(TAG, "onChange() with URI == null - not handled.");
                return;
            }
            if (V) Log.d(TAG, "onChange on thread: " + Thread.currentThread().getId()
                    + " Uri: " + uri.toString() + " selfchange: " + selfChange);

            if(uri.toString().contains(BluetoothMapContract.TABLE_CONVOCONTACT))
                handleContactListChanges(uri);
            else
                handleMsgListChanges(uri);
        }
    };

    private static final HashMap<Integer, String> FOLDER_SMS_MAP;
    static {
        FOLDER_SMS_MAP = new HashMap<Integer, String>();
        FOLDER_SMS_MAP.put(Sms.MESSAGE_TYPE_INBOX,  BluetoothMapContract.FOLDER_NAME_INBOX);
        FOLDER_SMS_MAP.put(Sms.MESSAGE_TYPE_SENT,  BluetoothMapContract.FOLDER_NAME_SENT);
        FOLDER_SMS_MAP.put(Sms.MESSAGE_TYPE_DRAFT,  BluetoothMapContract.FOLDER_NAME_DRAFT);
        FOLDER_SMS_MAP.put(Sms.MESSAGE_TYPE_OUTBOX,  BluetoothMapContract.FOLDER_NAME_OUTBOX);
        FOLDER_SMS_MAP.put(Sms.MESSAGE_TYPE_FAILED,  BluetoothMapContract.FOLDER_NAME_OUTBOX);
        FOLDER_SMS_MAP.put(Sms.MESSAGE_TYPE_QUEUED,  BluetoothMapContract.FOLDER_NAME_OUTBOX);
    }

    private static String getSmsFolderName(int type) {
        String name = FOLDER_SMS_MAP.get(type);
        if(name != null) {
            return name;
        }
        Log.e(TAG, "New SMS mailbox types have been introduced, without an update in BT...");
        return "Unknown";
    }


    private static final HashMap<Integer, String> FOLDER_MMS_MAP;
    static {
        FOLDER_MMS_MAP = new HashMap<Integer, String>();
        FOLDER_MMS_MAP.put(Mms.MESSAGE_BOX_INBOX,  BluetoothMapContract.FOLDER_NAME_INBOX);
        FOLDER_MMS_MAP.put(Mms.MESSAGE_BOX_SENT,   BluetoothMapContract.FOLDER_NAME_SENT);
        FOLDER_MMS_MAP.put(Mms.MESSAGE_BOX_DRAFTS, BluetoothMapContract.FOLDER_NAME_DRAFT);
        FOLDER_MMS_MAP.put(Mms.MESSAGE_BOX_OUTBOX, BluetoothMapContract.FOLDER_NAME_OUTBOX);
    }

    private static String getMmsFolderName(int mailbox) {
        String name = FOLDER_MMS_MAP.get(mailbox);
        if(name != null) {
            return name;
        }
        Log.e(TAG, "New MMS mailboxes have been introduced, without an update in BT...");
        return "Unknown";
    }

    /**
     * Set the folder structure to be used for this instance.
     * @param folderStructure
     */
    public void setFolderStructure(BluetoothMapFolderElement folderStructure) {
        this.mFolders = folderStructure;
    }

    private class ConvoContactInfo {
        public int mConvoColConvoId         = -1;
        public int mConvoColLastActivity    = -1;
        public int mConvoColName            = -1;
        //        public int mConvoColRead            = -1;
        //        public int mConvoColVersionCounter  = -1;
        public int mContactColUci           = -1;
        public int mContactColConvoId       = -1;
        public int mContactColName          = -1;
        public int mContactColNickname      = -1;
        public int mContactColBtUid         = -1;
        public int mContactColChatState     = -1;
        public int mContactColContactId     = -1;
        public int mContactColLastActive    = -1;
        public int mContactColPresenceState = -1;
        public int mContactColPresenceText  = -1;
        public int mContactColPriority      = -1;
        public int mContactColLastOnline    = -1;

        public void setConvoColunms(Cursor c) {
            //            mConvoColConvoId         = c.getColumnIndex(
            //                    BluetoothMapContract.ConversationColumns.THREAD_ID);
            //            mConvoColLastActivity    = c.getColumnIndex(
            //                    BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY);
            //            mConvoColName            = c.getColumnIndex(
            //                    BluetoothMapContract.ConversationColumns.THREAD_NAME);
            mContactColConvoId       = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.CONVO_ID);
            mContactColName          = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.NAME);
            mContactColNickname      = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.NICKNAME);
            mContactColBtUid         = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.X_BT_UID);
            mContactColChatState     = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.CHAT_STATE);
            mContactColUci           = 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);
            mContactColLastOnline    = c.getColumnIndex(
                    BluetoothMapContract.ConvoContactColumns.LAST_ONLINE);
        }
    }

    class Event {
        String eventType;
        long handle;
        String folder = null;
        String oldFolder = null;
        TYPE msgType;
        /* Extended event parameters in MAP Event version 1.1 */
        String datetime = null; // OBEX time "YYYYMMDDTHHMMSS"
        String uci = null;
        String subject = null;
        String senderName = null;
        String priority = null;
        /* Event parameters in MAP Event version 1.2 */
        String conversationName = null;
        long conversationID = -1;
        int presenceState = BluetoothMapContract.PresenceState.UNKNOWN;
        String presenceStatus = null;
        int chatState = BluetoothMapContract.ChatState.UNKNOWN;

        final static String PATH = "telecom/msg/";

        private void setFolderPath(String name, TYPE type) {
            if (name != null) {
                if(type == TYPE.EMAIL || type == TYPE.IM) {
                    this.folder = name;
                } else {
                    this.folder = PATH + name;
                }
            } else {
                this.folder = null;
            }
        }

        public Event(String eventType, long handle, String folder,
                String oldFolder, TYPE msgType) {
            this.eventType = eventType;
            this.handle = handle;
            setFolderPath(folder, msgType);
            if (oldFolder != null) {
                if(msgType == TYPE.EMAIL || msgType == TYPE.IM) {
                    this.oldFolder = oldFolder;
                } else {
                    this.oldFolder = PATH + oldFolder;
                }
            } else {
                this.oldFolder = null;
            }
            this.msgType = msgType;
        }

        public Event(String eventType, long handle, String folder, TYPE msgType) {
            this.eventType = eventType;
            this.handle = handle;
            setFolderPath(folder, msgType);
            this.msgType = msgType;
        }

        /* extended event type 1.1 */
        public Event(String eventType, long handle, String folder, TYPE msgType,
                String datetime, String subject, String senderName, String priority) {
            this.eventType = eventType;
            this.handle = handle;
            setFolderPath(folder, msgType);
            this.msgType = msgType;
            this.datetime = datetime;
            if (subject != null) {
                this.subject = BluetoothMapUtils.stripInvalidChars(subject);
            }
            if (senderName != null) {
                this.senderName = BluetoothMapUtils.stripInvalidChars(senderName);
            }
            this.priority = priority;
        }

        /* extended event type 1.2 message events */
        public Event(String eventType, long handle, String folder, TYPE msgType,
                String datetime, String subject, String senderName, String priority,
                long conversationID, String conversationName) {
            this.eventType = eventType;
            this.handle = handle;
            setFolderPath(folder, msgType);
            this.msgType = msgType;
            this.datetime = datetime;
            if (subject != null) {
                this.subject = BluetoothMapUtils.stripInvalidChars(subject);
            }
            if (senderName != null) {
                this.senderName = BluetoothMapUtils.stripInvalidChars(senderName);
            }
            if (conversationID != 0) {
                this.conversationID = conversationID;
            }
            if (conversationName != null) {
                this.conversationName = BluetoothMapUtils.stripInvalidChars(conversationName);
            }
            this.priority = priority;
        }

        /* extended event type 1.2 for conversation, presence or chat state changed events */
        public Event(String eventType, String uci, TYPE msgType, String name, String priority,
                String lastActivity, long conversationID, String conversationName,
                int presenceState, String presenceStatus, int chatState) {
            this.eventType = eventType;
            this.uci = uci;
            this.msgType = msgType;
            if (name != null) {
                this.senderName = BluetoothMapUtils.stripInvalidChars(name);
            }
            this.priority = priority;
            this.datetime = lastActivity;
            if (conversationID != 0) {
                this.conversationID = conversationID;
            }
            if (conversationName != null) {
                this.conversationName = BluetoothMapUtils.stripInvalidChars(conversationName);
            }
            if (presenceState != BluetoothMapContract.PresenceState.UNKNOWN) {
                this.presenceState = presenceState;
            }
            if (presenceStatus != null) {
                this.presenceStatus = BluetoothMapUtils.stripInvalidChars(presenceStatus);
            }
            if (chatState != BluetoothMapContract.ChatState.UNKNOWN) {
                this.chatState = chatState;
            }
        }

        public byte[] encode() throws UnsupportedEncodingException {
            StringWriter sw = new StringWriter();
            XmlSerializer xmlEvtReport = Xml.newSerializer();

            try {
                xmlEvtReport.setOutput(sw);
                xmlEvtReport.startDocument("UTF-8", true);
                xmlEvtReport.text("\r\n");
                xmlEvtReport.startTag("", "MAP-event-report");
                if (mMapEventReportVersion == BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                    xmlEvtReport.attribute("", "version", BluetoothMapUtils.MAP_V10_STR);
                } else if (mMapEventReportVersion == BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
                    xmlEvtReport.attribute("", "version", BluetoothMapUtils.MAP_V11_STR);
                } else {
                    xmlEvtReport.attribute("", "version", BluetoothMapUtils.MAP_V12_STR);
                }
                xmlEvtReport.startTag("", "event");
                xmlEvtReport.attribute("", "type", eventType);
                if (eventType.equals(EVENT_TYPE_CONVERSATION) ||
                        eventType.equals(EVENT_TYPE_PRESENCE) ||
                        eventType.equals(EVENT_TYPE_CHAT_STATE)) {
                    xmlEvtReport.attribute("", "participant_uci", uci);
                } else {
                    xmlEvtReport.attribute("", "handle",
                            BluetoothMapUtils.getMapHandle(handle, msgType));
                }

                if (folder != null) {
                    xmlEvtReport.attribute("", "folder", folder);
                }
                if (oldFolder != null) {
                    xmlEvtReport.attribute("", "old_folder", oldFolder);
                }
                /* Avoid possible NPE for "msgType" "null" value. "msgType"
                 * is a implied attribute and will be set "null" for events
                 * like "memory full" or "memory available" */
                if (msgType != null) {
                    xmlEvtReport.attribute("", "msg_type", msgType.name());
                }
                /* If MAP event report version is above 1.0 send
                 * extended event report parameters */
                if (datetime != null) {
                    xmlEvtReport.attribute("", "datetime", datetime);
                }
                if (subject != null) {
                    xmlEvtReport.attribute("", "subject",
                            subject.substring(0,subject.length() < 256 ? subject.length() : 256));
                }
                if (senderName != null) {
                    xmlEvtReport.attribute("", "senderName", senderName);
                }
                if (priority != null) {
                    xmlEvtReport.attribute("", "priority", priority);
                }

                //}
                /* Include conversation information from event version 1.2 */
                if (mMapEventReportVersion > BluetoothMapUtils.MAP_EVENT_REPORT_V11 ) {
                    if (conversationName != null) {
                        xmlEvtReport.attribute("", "conversation_name", conversationName);
                    }
                    if (conversationID != -1) {
                        // Convert provider conversation handle to string incl type
                        xmlEvtReport.attribute("", "conversation_id",
                                BluetoothMapUtils.getMapConvoHandle(conversationID, msgType));
                    }
                    if (eventType.equals(EVENT_TYPE_PRESENCE)) {
                        if (presenceState != 0) {
                            // Convert provider conversation handle to string incl type
                            xmlEvtReport.attribute("", "presence_availability",
                                    String.valueOf(presenceState));
                        }
                        if (presenceStatus != null) {
                            // Convert provider conversation handle to string incl type
                            xmlEvtReport.attribute("", "presence_status",
                                    presenceStatus.substring(
                                            0,presenceStatus.length() < 256 ? subject.length() : 256));
                        }
                    }
                    if (eventType.equals(EVENT_TYPE_PRESENCE)) {
                        if (chatState != 0) {
                            // Convert provider conversation handle to string incl type
                            xmlEvtReport.attribute("", "chat_state", String.valueOf(chatState));
                        }
                    }

                }
                xmlEvtReport.endTag("", "event");
                xmlEvtReport.endTag("", "MAP-event-report");
                xmlEvtReport.endDocument();
            } catch (IllegalArgumentException e) {
                if(D) Log.w(TAG,e);
            } catch (IllegalStateException e) {
                if(D) Log.w(TAG,e);
            } catch (IOException e) {
                if(D) Log.w(TAG,e);
            }

            if (V) Log.d(TAG, sw.toString());

            return sw.toString().getBytes("UTF-8");
        }
    }

    /*package*/ class Msg {
        long id;
        int type;               // Used as folder for SMS/MMS
        int threadId;           // Used for SMS/MMS at delete
        long folderId = -1;     // Email folder ID
        long oldFolderId = -1;  // Used for email undelete
        boolean localInitiatedSend = false; // Used for MMS to filter out events
        boolean localInitiatedReadStatus = false; // Used for SetMsgStatusRead to filter out event
        boolean localInitiatedShift = false; // Used for SetMsgStatusDelete to filter out events
        boolean transparent = false; // Used for EMAIL to delete message sent with transparency
        int flagRead = -1;      // Message status read/unread

        public Msg(long id, int type, int threadId, int readFlag) {
            this.id = id;
            this.type = type;
            this.threadId = threadId;
            this.flagRead = readFlag;
        }
        public Msg(long id, long folderId, int readFlag) {
            this.id = id;
            this.folderId = folderId;
            this.flagRead = readFlag;
        }

        /* Eclipse generated hashCode() and equals() to make
         * hashMap lookup work independent of whether the obj
         * is used for email or SMS/MMS and whether or not the
         * oldFolder is set. */
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (int) (id ^ (id >>> 32));
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Msg other = (Msg) obj;
            if (id != other.id)
                return false;
            return true;
        }
    }

    private Map<Long, Msg> mMsgListSms = null;

    private Map<Long, Msg> mMsgListMms = null;

    private Map<Long, Msg> mMsgListMsg = null;

    private Map<String, BluetoothMapConvoContactElement> mContactList = null;

    public int setNotificationRegistration(int notificationStatus) throws RemoteException {
        // Forward the request to the MNS thread as a message - including the MAS instance ID.
        if(D) Log.d(TAG,"setNotificationRegistration() enter");
        if (mMnsClient == null ) {
            return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
        }
        Handler mns = mMnsClient.getMessageHandler();
        if (mns != null) {
            Message msg = mns.obtainMessage();
            if (mMnsClient.isValidMnsRecord()) {
                msg.what = BluetoothMnsObexClient.MSG_MNS_NOTIFICATION_REGISTRATION;
            } else {
                //Trigger SDP Search and notificaiton registration , if SDP record not found.
                msg.what = BluetoothMnsObexClient.MSG_MNS_SDP_SEARCH_REGISTRATION;
                if (mMnsClient.mMnsLstRegRqst != null &&
                        (mMnsClient.mMnsLstRegRqst.getIsSearchProgress())) {
                        /*  1. Disallow next Notification ON Request :
                         *     - Respond "Service Unavailable" as SDP Search and last notification
                         *       registration ON request is already InProgress.
                         *     - Next notification ON Request will be allowed ONLY after search
                         *       and connect for last saved request [Replied with OK ] is processed.
                         */
                     if (notificationStatus == BluetoothMapAppParams.NOTIFICATION_STATUS_YES) {
                         return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
                     } else {
                         /*  2. Allow next Notification OFF Request:
                          *    - Keep the SDP search still in progress.
                          *    - Disconnect and Deregister the contentObserver.
                          */
                          msg.what = BluetoothMnsObexClient.MSG_MNS_NOTIFICATION_REGISTRATION;
                    }
                }
            }
            msg.arg1 = mMasId;
            msg.arg2 = notificationStatus;
            mns.sendMessageDelayed(msg, 10); // Send message without forcing a context switch
            /* Some devices - e.g. PTS needs to get the unregister confirm before we actually
             * disconnect the MNS. */
            if(D) Log.d(TAG,"setNotificationRegistration() send : " + msg.what + " to MNS ");
            return ResponseCodes.OBEX_HTTP_OK;
        } else {
            // This should not happen except at shutdown.
            if(D) Log.d(TAG,"setNotificationRegistration() Unable to send registration request");
            return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
        }
    }

    boolean eventMaskContainsContacts(long mask) {
        return sendEventParticipantPresenceChanged(mask);
    }

    boolean eventMaskContainsCovo(long mask) {
        return (sendEventConversationChanged(mask)
                || sendEventParticipantChatstateChanged(mask));
    }

    /* Overwrite the existing notification filter. Will register/deregister observers for
     * the Contacts and Conversation table as needed. We keep the message observer
     * at all times. */
    /*package*/ synchronized void setNotificationFilter(long newFilter) {
        long oldFilter = mEventFilter;
        mEventFilter = newFilter;
        /* Contacts */
        if(!eventMaskContainsContacts(oldFilter) &&
                eventMaskContainsContacts(newFilter)) {
            // TODO:
            // Enable the observer
            // Reset the contacts list
        }
        /* Conversations */
        if(!eventMaskContainsCovo(oldFilter) &&
                eventMaskContainsCovo(newFilter)) {
            // TODO:
            // Enable the observer
            // Reset the conversations list
        }
    }

    public void registerObserver() throws RemoteException{
        if (V) Log.d(TAG, "registerObserver");

        if (mObserverRegistered)
            return;

        if(mAccount != null) {

            mProviderClient = mResolver.acquireUnstableContentProviderClient(mAuthority);
            if (mProviderClient == null) {
                throw new RemoteException("Failed to acquire provider for " + mAuthority);
            }
            mProviderClient.setDetectNotResponding(PROVIDER_ANR_TIMEOUT);

            // If there is a change in the database before we init the lists we will be sending
            // loads of events - hence init before register.
            if(mAccount.getType() == TYPE.IM) {
                // Further add contact list tracking
                initContactsList();
            }
        }
        // If there is a change in the database before we init the lists we will be sending
        // loads of events - hence init before register.
        initMsgList();

        /* Use MmsSms Uri since the Sms Uri is not notified on deletes */
        if(mEnableSmsMms){
            //this is sms/mms
            mResolver.registerContentObserver(MmsSms.CONTENT_URI, false, mObserver);
            mObserverRegistered = true;
        }

        if(mAccount != null) {
            /* For URI's without account ID */
            Uri uri = Uri.parse(mAccount.mBase_uri_no_account + "/"
                    + BluetoothMapContract.TABLE_MESSAGE);
            if(D) Log.d(TAG, "Registering observer for: " + uri);
            mResolver.registerContentObserver(uri, true, mObserver);

            /* For URI's with account ID - is handled the same way as without ID, but is
             * only triggered for MAS instances with matching account ID. */
            uri = Uri.parse(mAccount.mBase_uri + "/" + BluetoothMapContract.TABLE_MESSAGE);
            if(D) Log.d(TAG, "Registering observer for: " + uri);
            mResolver.registerContentObserver(uri, true, mObserver);

            if(mAccount.getType() == TYPE.IM) {

                uri = Uri.parse(mAccount.mBase_uri_no_account + "/"
                        + BluetoothMapContract.TABLE_CONVOCONTACT);
                if(D) Log.d(TAG, "Registering observer for: " + uri);
                mResolver.registerContentObserver(uri, true, mObserver);

                /* For URI's with account ID - is handled the same way as without ID, but is
                 * only triggered for MAS instances with matching account ID. */
                uri = Uri.parse(mAccount.mBase_uri + "/" + BluetoothMapContract.TABLE_CONVOCONTACT);
                if(D) Log.d(TAG, "Registering observer for: " + uri);
                mResolver.registerContentObserver(uri, true, mObserver);
            }

            mObserverRegistered = true;
        }
    }

    public void unregisterObserver() {
        if (V) Log.d(TAG, "unregisterObserver");
        mResolver.unregisterContentObserver(mObserver);
        mObserverRegistered = false;
        if(mProviderClient != null){
            mProviderClient.release();
            mProviderClient = null;
        }
    }

    /**
     * Per design it is only possible to call the refreshXxxx functions sequentially, hence it
     * is safe to modify mTransmitEvents without synchronization.
     */
    /* package */ void refreshFolderVersionCounter() {
        if (mObserverRegistered) {
            // As we have observers, we already keep the counter up-to-date.
            return;
        }
        /* We need to perform the same functionality, as when we receive a notification change,
           hence we:
            - disable the event transmission
            - triggers the code for updates
            - enable the event transmission */
        mTransmitEvents = false;
        try {
            if(mEnableSmsMms) {
                handleMsgListChangesSms();
                handleMsgListChangesMms();
            }
            if(mAccount != null) {
                try {
                    handleMsgListChangesMsg(mMessageUri);
                } catch (RemoteException e) {
                    Log.e(TAG, "Unable to update FolderVersionCounter. - Not fatal, but can cause" +
                            " undesirable user experience!", e);
                }
            }
        } finally {
            // Ensure we always enable events again
            mTransmitEvents = true;
        }
    }

    /* package */ void refreshConvoListVersionCounter() {
        if (mObserverRegistered) {
            // As we have observers, we already keep the counter up-to-date.
            return;
        }
        /* We need to perform the same functionality, as when we receive a notification change,
        hence we:
         - disable event transmission
         - triggers the code for updates
         - enable event transmission */
        mTransmitEvents = false;
        try {
            if((mAccount != null) && (mContactUri != null)) {
                handleContactListChanges(mContactUri);
            }
        } finally {
            // Ensure we always enable events again
            mTransmitEvents = true;
        }
    }

    private void sendEvent(Event evt) {

        if(mTransmitEvents == false) {
            if(V) Log.v(TAG, "mTransmitEvents == false - don't send event.");
            return;
        }

        if(D)Log.d(TAG, "sendEvent: " + evt.eventType + " " + evt.handle + " " + evt.folder + " "
                + evt.oldFolder + " " + evt.msgType.name() + " " + evt.datetime + " "
                + evt.subject + " " + evt.senderName + " " + evt.priority );

        if (mMnsClient == null || mMnsClient.isConnected() == false) {
            Log.d(TAG, "sendEvent: No MNS client registered or connected- don't send event");
            return;
        }

        /* Enable use of the cache for checking the filter */
        long eventFilter = mEventFilter;

        /* This should have been a switch on the string, but it is not allowed in Java 1.6 */
        /* WARNING: Here we do pointer compare for the string to speed up things, that is.
         * HENCE: always use the EVENT_TYPE_"defines" */
        if(evt.eventType == EVENT_TYPE_NEW) {
            if(!sendEventNewMessage(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_DELETE) {
            if(!sendEventMessageDeleted(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_REMOVED) {
            if(!sendEventMessageRemoved(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_SHIFT) {
            if(!sendEventMessageShift(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_DELEVERY_SUCCESS) {
            if(!sendEventDeliverySuccess(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_SENDING_SUCCESS) {
            if(!sendEventSendingSuccess(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_SENDING_FAILURE) {
            if(!sendEventSendingFailed(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_DELIVERY_FAILURE) {
            if(!sendEventDeliveryFailed(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_READ_STATUS) {
            if(!sendEventReadStatusChanged(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_CONVERSATION) {
            if(!sendEventConversationChanged(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_PRESENCE) {
            if(!sendEventParticipantPresenceChanged(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        } else if(evt.eventType == EVENT_TYPE_CHAT_STATE) {
            if(!sendEventParticipantChatstateChanged(eventFilter)) {
                if(D)Log.d(TAG, "Skip sending event of type: " + evt.eventType);
                return;
            }
        }

        try {
            mMnsClient.sendEvent(evt.encode(), mMasId);
        } catch (UnsupportedEncodingException ex) {
            /* do nothing */
            if (D) Log.e(TAG, "Exception - should not happen: ",ex);
        }
    }

    private void initMsgList() throws RemoteException {
        if (V) Log.d(TAG, "initMsgList");

        if(mEnableSmsMms) {

            HashMap<Long, Msg> msgListSms = new HashMap<Long, Msg>();

            Cursor c = mResolver.query(Sms.CONTENT_URI,
                    SMS_PROJECTION_SHORT, null, null, null);
            try {
                if (c != null && c.moveToFirst()) {
                    do {
                        long id = c.getLong(c.getColumnIndex(Sms._ID));
                        int type = c.getInt(c.getColumnIndex(Sms.TYPE));
                        int threadId = c.getInt(c.getColumnIndex(Sms.THREAD_ID));
                        int read = c.getInt(c.getColumnIndex(Sms.READ));

                        Msg msg = new Msg(id, type, threadId, read);
                        msgListSms.put(id, msg);
                    } while (c.moveToNext());
                }
            } finally {
                if (c != null) c.close();
            }

            synchronized(getMsgListSms()) {
                getMsgListSms().clear();
                setMsgListSms(msgListSms, true); // Set initial folder version counter
            }

            HashMap<Long, Msg> msgListMms = new HashMap<Long, Msg>();

            c = mResolver.query(Mms.CONTENT_URI, MMS_PROJECTION_SHORT, null, null, null);
            try {
                if (c != null && c.moveToFirst()) {
                    do {
                        long id = c.getLong(c.getColumnIndex(Mms._ID));
                        int type = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX));
                        int threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID));
                        int read = c.getInt(c.getColumnIndex(Mms.READ));

                        Msg msg = new Msg(id, type, threadId, read);
                        msgListMms.put(id, msg);
                    } while (c.moveToNext());
                }
            } finally {
                if (c != null) c.close();
            }

            synchronized(getMsgListMms()) {
                getMsgListMms().clear();
                setMsgListMms(msgListMms, true); // Set initial folder version counter
            }
        }

        if(mAccount != null) {
            HashMap<Long, Msg> msgList = new HashMap<Long, Msg>();
            Uri uri = mMessageUri;
            Cursor c = mProviderClient.query(uri, MSG_PROJECTION_SHORT, null, null, null);

            try {
                if (c != null && c.moveToFirst()) {
                    do {
                        long id = c.getLong(c.getColumnIndex(MessageColumns._ID));
                        long folderId = c.getInt(c.getColumnIndex(
                                BluetoothMapContract.MessageColumns.FOLDER_ID));
                        int readFlag = c.getInt(c.getColumnIndex(
                                BluetoothMapContract.MessageColumns.FLAG_READ));
                        Msg msg = new Msg(id, folderId, readFlag);
                        msgList.put(id, msg);
                    } while (c.moveToNext());
                }
            } finally {
                if (c != null) c.close();
            }

            synchronized(getMsgListMsg()) {
                getMsgListMsg().clear();
                setMsgListMsg(msgList, true);
            }
        }
    }

    private void initContactsList() throws RemoteException {
        if (V) Log.d(TAG, "initContactsList");
        if(mContactUri == null) {
            if (D) Log.d(TAG, "initContactsList() no mContactUri - nothing to init");
            return;
        }
        Uri uri = mContactUri;
        Cursor c = mProviderClient.query(uri,
                BluetoothMapContract.BT_CONTACT_CHATSTATE_PRESENCE_PROJECTION,
                null, null, null);
        Map<String, BluetoothMapConvoContactElement> contactList =
                new HashMap<String, BluetoothMapConvoContactElement>();
        try {
            if (c != null && c.moveToFirst()) {
                ConvoContactInfo cInfo = new ConvoContactInfo();
                cInfo.setConvoColunms(c);
                do {
                    long convoId = c.getLong(cInfo.mContactColConvoId);
                    if (convoId == 0)
                        continue;
                    if (V) BluetoothMapUtils.printCursor(c);
                    String uci = c.getString(cInfo.mContactColUci);
                    String name = c.getString(cInfo.mContactColName);
                    String displayName = c.getString(cInfo.mContactColNickname);
                    String presenceStatus = c.getString(cInfo.mContactColPresenceText);
                    int presenceState = c.getInt(cInfo.mContactColPresenceState);
                    long lastActivity = c.getLong(cInfo.mContactColLastActive);
                    int chatState = c.getInt(cInfo.mContactColChatState);
                    int priority = c.getInt(cInfo.mContactColPriority);
                    String btUid = c.getString(cInfo.mContactColBtUid);
                    BluetoothMapConvoContactElement contact =
                            new BluetoothMapConvoContactElement(uci, name, displayName,
                                    presenceStatus, presenceState, lastActivity, chatState,
                                    priority, btUid);
                    contactList.put(uci, contact);
                } while (c.moveToNext());
            }
        } finally {
            if (c != null) c.close();
        }
        synchronized(getContactList()) {
            getContactList().clear();
            setContactList(contactList, true);
        }
    }

    private void handleMsgListChangesSms() {
        if (V) Log.d(TAG, "handleMsgListChangesSms");

        HashMap<Long, Msg> msgListSms = new HashMap<Long, Msg>();
        boolean listChanged = false;

        Cursor c;
        synchronized(getMsgListSms()) {
            if (mMapEventReportVersion == BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                c = mResolver.query(Sms.CONTENT_URI,
                        SMS_PROJECTION_SHORT, null, null, null);
            } else {
                c = mResolver.query(Sms.CONTENT_URI,
                        SMS_PROJECTION_SHORT_EXT, null, null, null);
            }
            try {
                if (c != null && c.moveToFirst()) {
                    do {
                        long id = c.getLong(c.getColumnIndex(Sms._ID));
                        int type = c.getInt(c.getColumnIndex(Sms.TYPE));
                        int threadId = c.getInt(c.getColumnIndex(Sms.THREAD_ID));
                        int read = c.getInt(c.getColumnIndex(Sms.READ));

                        Msg msg = getMsgListSms().remove(id);

                        /* We must filter out any actions made by the MCE, hence do not send e.g.
                         * a message deleted and/or MessageShift for messages deleted by the MCE. */

                        if (msg == null) {
                            /* New message */
                            msg = new Msg(id, type, threadId, read);
                            msgListSms.put(id, msg);
                            listChanged = true;
                            Event evt;
                            if (mTransmitEvents == true && // extract contact details only if needed
                                    mMapEventReportVersion >
                            BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                                String date = BluetoothMapUtils.getDateTimeString(
                                        c.getLong(c.getColumnIndex(Sms.DATE)));
                                String subject = c.getString(c.getColumnIndex(Sms.BODY));
                                String name = "";
                                String phone = "";
                                if (type == 1) { //inbox
                                    phone = c.getString(c.getColumnIndex(Sms.ADDRESS));
                                    if (phone != null && !phone.isEmpty()) {
                                        name = BluetoothMapContent.getContactNameFromPhone(phone,
                                                mResolver);
                                        if(name == null || name.isEmpty()){
                                            name = phone;
                                        }
                                    }else{
                                        name = phone;
                                    }
                                } else {
                                    TelephonyManager tm =
                                            (TelephonyManager)mContext.getSystemService(
                                            Context.TELEPHONY_SERVICE);
                                    if (tm != null) {
                                        phone = tm.getLine1Number();
                                        name = tm.getLine1AlphaTag();
                                        if(name == null || name.isEmpty()){
                                            name = phone;
                                        }
                                    }
                                }
                                String priority = "no";// no priority for sms
                                /* Incoming message from the network */
                                if (mMapEventReportVersion ==
                                        BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
                                    evt = new Event(EVENT_TYPE_NEW, id, getSmsFolderName(type),
                                            mSmsType, date, subject, name, priority);
                                } else {
                                    evt = new Event(EVENT_TYPE_NEW, id, getSmsFolderName(type),
                                            mSmsType, date, subject, name, priority,
                                            (long)threadId, null);
                                }
                            } else {
                                /* Incoming message from the network */
                                evt = new Event(EVENT_TYPE_NEW, id, getSmsFolderName(type),
                                        null, mSmsType);
                            }
                            sendEvent(evt);
                        } else {
                            /* Existing message */
                            if (type != msg.type) {
                                listChanged = true;
                                Log.d(TAG, "new type: " + type + " old type: " + msg.type);
                                String oldFolder = getSmsFolderName(msg.type);
                                String newFolder = getSmsFolderName(type);
                                // Filter out the intermediate outbox steps
                                if(!oldFolder.equalsIgnoreCase(newFolder)) {
                                    Event evt = new Event(EVENT_TYPE_SHIFT, id,
                                            getSmsFolderName(type), oldFolder, mSmsType);
                                    sendEvent(evt);
                                }
                                msg.type = type;
                            } else if(threadId != msg.threadId) {
                                listChanged = true;
                                Log.d(TAG, "Message delete change: type: " + type
                                        + " old type: " + msg.type
                                        + "\n    threadId: " + threadId
                                        + " old threadId: " + msg.threadId);
                                if(threadId == DELETED_THREAD_ID) { // Message deleted
                                    // TODO:
                                    // We shall only use the folder attribute, but can't remember
                                    // wether to set it to "deleted" or the name of the folder
                                    // from which the message have been deleted.
                                    // "old_folder" used only for MessageShift event
                                    Event evt = new Event(EVENT_TYPE_DELETE, id,
                                            getSmsFolderName(msg.type), null, mSmsType);
                                    sendEvent(evt);
                                    msg.threadId = threadId;
                                } else { // Undelete
                                    Event evt = new Event(EVENT_TYPE_SHIFT, id,
                                            getSmsFolderName(msg.type),
                                            BluetoothMapContract.FOLDER_NAME_DELETED, mSmsType);
                                    sendEvent(evt);
                                    msg.threadId = threadId;
                                }
                            }
                            if(read != msg.flagRead) {
                                listChanged = true;
                                msg.flagRead = read;
                                if (mMapEventReportVersion >
                                        BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                                    Event evt = new Event(EVENT_TYPE_READ_STATUS, id,
                                            getSmsFolderName(msg.type), mSmsType);
                                    sendEvent(evt);
                                }
                            }
                            msgListSms.put(id, msg);
                        }
                    } while (c.moveToNext());
                }
            } finally {
                if (c != null) c.close();
            }

            for (Msg msg : getMsgListSms().values()) {
                // "old_folder" used only for MessageShift event
                Event evt = new Event(EVENT_TYPE_DELETE, msg.id,
                        getSmsFolderName(msg.type), null, mSmsType);
                sendEvent(evt);
                listChanged = true;
            }

            setMsgListSms(msgListSms, listChanged);
        }
    }

    private void handleMsgListChangesMms() {
        if (V) Log.d(TAG, "handleMsgListChangesMms");

        HashMap<Long, Msg> msgListMms = new HashMap<Long, Msg>();
        boolean listChanged = false;
        Cursor c;
        synchronized(getMsgListMms()) {
            if (mMapEventReportVersion == BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                c = mResolver.query(Mms.CONTENT_URI,
                        MMS_PROJECTION_SHORT, null, null, null);
            } else {
                c = mResolver.query(Mms.CONTENT_URI,
                        MMS_PROJECTION_SHORT_EXT, null, null, null);
            }

            try{
                if (c != null && c.moveToFirst()) {
                    do {
                        long id = c.getLong(c.getColumnIndex(Mms._ID));
                        int type = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX));
                        int mtype = c.getInt(c.getColumnIndex(Mms.MESSAGE_TYPE));
                        int threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID));
                        // TODO: Go through code to see if we have an issue with mismatch in types
                        //       for threadId. Seems to be a long in DB??
                        int read = c.getInt(c.getColumnIndex(Mms.READ));

                        Msg msg = getMsgListMms().remove(id);

                        /* We must filter out any actions made by the MCE, hence do not send
                         * e.g. a message deleted and/or MessageShift for messages deleted by the
                         * MCE.*/

                        if (msg == null) {
                            /* New message - only notify on retrieve conf */
                            listChanged = true;
                            if (getMmsFolderName(type).equalsIgnoreCase(
                                    BluetoothMapContract.FOLDER_NAME_INBOX) &&
                                    mtype != MESSAGE_TYPE_RETRIEVE_CONF) {
                                continue;
                            }
                            msg = new Msg(id, type, threadId, read);
                            msgListMms.put(id, msg);
                            Event evt;
                            if (mTransmitEvents == true && // extract contact details only if needed
                                    mMapEventReportVersion !=
                                    BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                                String date = BluetoothMapUtils.getDateTimeString(
                                        c.getLong(c.getColumnIndex(Mms.DATE)));
                                String subject = c.getString(c.getColumnIndex(Mms.SUBJECT));
                                if (subject == null || subject.length() == 0) {
                                    /* Get subject from mms text body parts - if any exists */
                                    subject = BluetoothMapContent.getTextPartsMms(mResolver, id);
                                }
                                int tmpPri = c.getInt(c.getColumnIndex(Mms.PRIORITY));
                                Log.d(TAG, "TEMP handleMsgListChangesMms, " +
                                        "newMessage 'read' state: " + read +
                                        "priority: " + tmpPri);

                                String address = BluetoothMapContent.getAddressMms(
                                        mResolver,id,BluetoothMapContent.MMS_FROM);
                                String priority = "no";
                                if(tmpPri == PduHeaders.PRIORITY_HIGH)
                                    priority = "yes";

                                /* Incoming message from the network */
                                if (mMapEventReportVersion ==
                                        BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
                                    evt = new Event(EVENT_TYPE_NEW, id, getMmsFolderName(type),
                                            TYPE.MMS, date, subject, address, priority);
                                } else {
                                    evt = new Event(EVENT_TYPE_NEW, id, getMmsFolderName(type),
                                            TYPE.MMS, date, subject, address, priority,
                                            (long)threadId, null);
                                }

                            } else {
                                /* Incoming message from the network */
                                evt = new Event(EVENT_TYPE_NEW, id, getMmsFolderName(type),
                                        null, TYPE.MMS);
                            }

                            sendEvent(evt);
                        } else {
                            /* Existing message */
                            if (type != msg.type) {
                                Log.d(TAG, "new type: " + type + " old type: " + msg.type);
                                Event evt;
                                listChanged = true;
                                if(msg.localInitiatedSend == false) {
                                    // Only send events about local initiated changes
                                    evt = new Event(EVENT_TYPE_SHIFT, id, getMmsFolderName(type),
                                            getMmsFolderName(msg.type), TYPE.MMS);
                                    sendEvent(evt);
                                }
                                msg.type = type;

                                if (getMmsFolderName(type).equalsIgnoreCase(
                                        BluetoothMapContract.FOLDER_NAME_SENT)
                                        && msg.localInitiatedSend == true) {
                                    // Stop tracking changes for this message
                                    msg.localInitiatedSend = false;
                                    evt = new Event(EVENT_TYPE_SENDING_SUCCESS, id,
                                            getMmsFolderName(type), null, TYPE.MMS);
                                    sendEvent(evt);
                                }
                            } else if(threadId != msg.threadId) {
                                Log.d(TAG, "Message delete change: type: " + type + " old type: "
                                        + msg.type
                                        + "\n    threadId: " + threadId + " old threadId: "
                                        + msg.threadId);
                                listChanged = true;
                                if(threadId == DELETED_THREAD_ID) { // Message deleted
                                    // "old_folder" used only for MessageShift event
                                    Event evt = new Event(EVENT_TYPE_DELETE, id,
                                            getMmsFolderName(msg.type), null, TYPE.MMS);
                                    sendEvent(evt);
                                    msg.threadId = threadId;
                                } else { // Undelete
                                    Event evt = new Event(EVENT_TYPE_SHIFT, id,
                                            getMmsFolderName(msg.type),
                                            BluetoothMapContract.FOLDER_NAME_DELETED, TYPE.MMS);
                                    sendEvent(evt);
                                    msg.threadId = threadId;
                                }
                            }
                            if(read != msg.flagRead) {
                                listChanged = true;
                                msg.flagRead = read;
                                if (mMapEventReportVersion >
                                        BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                                    Event evt = new Event(EVENT_TYPE_READ_STATUS, id,
                                            getMmsFolderName(msg.type), TYPE.MMS);
                                    sendEvent(evt);
                                }
                            }
                            msgListMms.put(id, msg);
                        }
                    } while (c.moveToNext());

                }
            } finally {
                if (c != null) c.close();
            }
            for (Msg msg : getMsgListMms().values()) {
                // "old_folder" used only for MessageShift event
                Event evt = new Event(EVENT_TYPE_DELETE, msg.id,
                        getMmsFolderName(msg.type), null, TYPE.MMS);
                sendEvent(evt);
                listChanged = true;
            }
            setMsgListMms(msgListMms, listChanged);
        }
    }

    private void handleMsgListChangesMsg(Uri uri)  throws RemoteException{
        if (V) Log.v(TAG, "handleMsgListChangesMsg uri: " + uri.toString());

        // TODO: Change observer to handle accountId and message ID if present

        HashMap<Long, Msg> msgList = new HashMap<Long, Msg>();
        Cursor c;
        boolean listChanged = false;
        if (mMapEventReportVersion == BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
            c = mProviderClient.query(mMessageUri, MSG_PROJECTION_SHORT, null, null, null);
        } else if (mMapEventReportVersion == BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
            c = mProviderClient.query(mMessageUri, MSG_PROJECTION_SHORT_EXT, null, null, null);
        } else {
            c = mProviderClient.query(mMessageUri, MSG_PROJECTION_SHORT_EXT2, null, null, null);
        }
        synchronized(getMsgListMsg()) {
            try {
                if (c != null && c.moveToFirst()) {
                    do {
                        long id = c.getLong(c.getColumnIndex(
                                BluetoothMapContract.MessageColumns._ID));
                        int folderId = c.getInt(c.getColumnIndex(
                                BluetoothMapContract.MessageColumns.FOLDER_ID));
                        int readFlag = c.getInt(c.getColumnIndex(
                                BluetoothMapContract.MessageColumns.FLAG_READ));
                        Msg msg = getMsgListMsg().remove(id);
                        BluetoothMapFolderElement folderElement = mFolders.getFolderById(folderId);
                        String newFolder;
                        if(folderElement != null) {
                            newFolder = folderElement.getFullPath();
                        } else {
                            // This can happen if a new folder is created while connected
                            newFolder = "unknown";
                        }
                        /* We must filter out any actions made by the MCE, hence do not send e.g.
                         * a message deleted and/or MessageShift for messages deleted by the MCE. */
                        if (msg == null) {
                            listChanged = true;
                            /* New message - created with message unread */
                            msg = new Msg(id, folderId, 0, readFlag);
                            msgList.put(id, msg);
                            Event evt;
                            /* Incoming message from the network */
                            if (mMapEventReportVersion != BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                                String date = BluetoothMapUtils.getDateTimeString(
                                        c.getLong(c.getColumnIndex(
                                                BluetoothMapContract.MessageColumns.DATE)));
                                String subject = c.getString(c.getColumnIndex(
                                        BluetoothMapContract.MessageColumns.SUBJECT));
                                String address = c.getString(c.getColumnIndex(
                                        BluetoothMapContract.MessageColumns.FROM_LIST));
                                String priority = "no";
                                if(c.getInt(c.getColumnIndex(
                                        BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY))
                                        == 1)
                                    priority = "yes";
                                if (mMapEventReportVersion ==
                                        BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
                                    evt = new Event(EVENT_TYPE_NEW, id, newFolder,
                                            mAccount.getType(), date, subject, address, priority);
                                } else {
                                    long thread_id = c.getLong(c.getColumnIndex(
                                            BluetoothMapContract.MessageColumns.THREAD_ID));
                                    String thread_name = c.getString(c.getColumnIndex(
                                            BluetoothMapContract.MessageColumns.THREAD_NAME));
                                    evt = new Event(EVENT_TYPE_NEW, id, newFolder,
                                            mAccount.getType(), date, subject, address, priority,
                                            thread_id, thread_name);
                                }
                            } else {
                                evt = new Event(EVENT_TYPE_NEW, id, newFolder, null, TYPE.EMAIL);
                            }
                            sendEvent(evt);
                        } else {
                            /* Existing message */
                            if (folderId != msg.folderId && msg.folderId != -1) {
                                if (D) Log.d(TAG, "new folderId: " + folderId + " old folderId: "
                                        + msg.folderId);
                                BluetoothMapFolderElement oldFolderElement =
                                        mFolders.getFolderById(msg.folderId);
                                String oldFolder;
                                listChanged = true;
                                if(oldFolderElement != null) {
                                    oldFolder = oldFolderElement.getFullPath();
                                } else {
                                    // This can happen if a new folder is created while connected
                                    oldFolder = "unknown";
                                }
                                BluetoothMapFolderElement deletedFolder =
                                        mFolders.getFolderByName(
                                                BluetoothMapContract.FOLDER_NAME_DELETED);
                                BluetoothMapFolderElement sentFolder =
                                        mFolders.getFolderByName(
                                                BluetoothMapContract.FOLDER_NAME_SENT);
                                /*
                                 *  If the folder is now 'deleted', send a deleted-event in stead of
                                 *  a shift or if message is sent initiated by MAP Client, then send
                                 *  sending-success otherwise send folderShift
                                 */
                                if(deletedFolder != null && deletedFolder.getFolderId()
                                        == folderId) {
                                    // "old_folder" used only for MessageShift event
                                    Event evt = new Event(EVENT_TYPE_DELETE, msg.id, oldFolder,
                                            null, mAccount.getType());
                                    sendEvent(evt);
                                } else if(sentFolder != null
                                        && sentFolder.getFolderId() == folderId
                                        && msg.localInitiatedSend == true) {
                                    if(msg.transparent) {
                                        mResolver.delete(
                                                ContentUris.withAppendedId(mMessageUri, id),
                                                null, null);
                                    } else {
                                        msg.localInitiatedSend = false;
                                        Event evt = new Event(EVENT_TYPE_SENDING_SUCCESS, msg.id,
                                                oldFolder, null, mAccount.getType());
                                        sendEvent(evt);
                                    }
                                } else {
                                    if (!oldFolder.equalsIgnoreCase("root")) {
                                        Event evt = new Event(EVENT_TYPE_SHIFT, id, newFolder,
                                                oldFolder, mAccount.getType());
                                        sendEvent(evt);
                                    }
                                }
                                msg.folderId = folderId;
                            }
                            if(readFlag != msg.flagRead) {
                                listChanged = true;

                                if (mMapEventReportVersion >
                                BluetoothMapUtils.MAP_EVENT_REPORT_V10) {
                                    Event evt = new Event(EVENT_TYPE_READ_STATUS, id, newFolder,
                                            mAccount.getType());
                                    sendEvent(evt);
                                    msg.flagRead = readFlag;
                                }
                            }

                            msgList.put(id, msg);
                        }
                    } while (c.moveToNext());
                }
            } finally {
                if (c != null) c.close();
            }
            // For all messages no longer in the database send a delete notification
            for (Msg msg : getMsgListMsg().values()) {
                BluetoothMapFolderElement oldFolderElement = mFolders.getFolderById(msg.folderId);
                String oldFolder;
                listChanged = true;
                if(oldFolderElement != null) {
                    oldFolder = oldFolderElement.getFullPath();
                } else {
                    oldFolder = "unknown";
                }
                /* Some e-mail clients delete the message after sending, and creates a
                 * new message in sent. We cannot track the message anymore, hence send both a
                 * send success and delete message.
                 */
                if(msg.localInitiatedSend == true) {
                    msg.localInitiatedSend = false;
                    // If message is send with transparency don't set folder as message is deleted
                    if (msg.transparent)
                        oldFolder = null;
                    Event evt = new Event(EVENT_TYPE_SENDING_SUCCESS, msg.id, oldFolder, null,
                            mAccount.getType());
                    sendEvent(evt);
                }
                /* As this message deleted is only send on a real delete - don't set folder.
                 *  - only send delete event if message is not sent with transparency
                 */
                if (!msg.transparent) {

                    // "old_folder" used only for MessageShift event
                    Event evt = new Event(EVENT_TYPE_DELETE, msg.id, oldFolder,
                            null, mAccount.getType());
                    sendEvent(evt);
                }
            }
            setMsgListMsg(msgList, listChanged);
        }
    }

    private void handleMsgListChanges(Uri uri) {
        if(uri.getAuthority().equals(mAuthority)) {
            try {
                if(D) Log.d(TAG, "handleMsgListChanges: account type = "
                        + mAccount.getType().toString());
                handleMsgListChangesMsg(uri);
            } catch(RemoteException e) {
                mMasInstance.restartObexServerSession();
                Log.w(TAG, "Problems contacting the ContentProvider in mas Instance "
                        + mMasId + " restaring ObexServerSession");
            }

        }
        // TODO: check to see if there could be problem with IM and SMS in one instance
        if (mEnableSmsMms) {
            handleMsgListChangesSms();
            handleMsgListChangesMms();
        }
    }

    private void handleContactListChanges(Uri uri) {
        if (uri.getAuthority().equals(mAuthority)) {
            try {
                if (V) Log.v(TAG,"handleContactListChanges uri: " + uri.toString());
                Cursor c = null;
                boolean listChanged = false;
                try {
                    ConvoContactInfo cInfo = new ConvoContactInfo();

                    if (mMapEventReportVersion != BluetoothMapUtils.MAP_EVENT_REPORT_V10
                            && mMapEventReportVersion != BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
                        c = mProviderClient
                                .query(mContactUri,
                                        BluetoothMapContract.
                                        BT_CONTACT_CHATSTATE_PRESENCE_PROJECTION,
                                        null, null, null);
                        cInfo.setConvoColunms(c);
                    } else {
                        if (V) Log.v(TAG,"handleContactListChanges MAP version does not" +
                                "support convocontact notifications");
                        return;
                    }

                    HashMap<String, BluetoothMapConvoContactElement> contactList =
                            new HashMap<String,
                            BluetoothMapConvoContactElement>(getContactList().size());

                    synchronized (getContactList()) {
                        if (c != null && c.moveToFirst()) {
                            do {
                                String uci = c.getString(cInfo.mContactColUci);
                                long convoId = c.getLong(cInfo.mContactColConvoId);
                                if (convoId == 0)
                                    continue;

                                if (V) BluetoothMapUtils.printCursor(c);

                                BluetoothMapConvoContactElement contact =
                                        getContactList().remove(uci);

                                /*
                                 * We must filter out any actions made by the
                                 * MCE, hence do not send e.g. a message deleted
                                 * and/or MessageShift for messages deleted by
                                 * the MCE.
                                 */
                                if (contact == null) {
                                    listChanged = true;
                                    /*
                                     * New contact - added to conversation and
                                     * tracked here
                                     */
                                    if (mMapEventReportVersion
                                            != BluetoothMapUtils.MAP_EVENT_REPORT_V10
                                            && mMapEventReportVersion
                                            != BluetoothMapUtils.MAP_EVENT_REPORT_V11) {
                                        Event evt;
                                        String name = c
                                                .getString(cInfo.mContactColName);
                                        String displayName = c
                                                .getString(cInfo.mContactColNickname);
                                        String presenceStatus = c
                                                .getString(cInfo.mContactColPresenceText);
                                        int presenceState = c
                                                .getInt(cInfo.mContactColPresenceState);
                                        long lastActivity = c
                                                .getLong(cInfo.mContactColLastActive);
                                        int chatState = c
                                                .getInt(cInfo.mContactColChatState);
                                        int priority = c
                                                .getInt(cInfo.mContactColPriority);
                                        String btUid = c
                                                .getString(cInfo.mContactColBtUid);

                                        // Get Conversation information for
                                        // event
//                                        Uri convoUri = Uri
//                                                .parse(mAccount.mBase_uri
//                                                        + "/"
//                                                        + BluetoothMapContract.TABLE_CONVERSATION);
//                                        String whereClause = "contacts._id = "
//                                                + convoId;
//                                        Cursor cConvo = mProviderClient
//                                                .query(convoUri,
//                                                       BluetoothMapContract.BT_CONVERSATION_PROJECTION,
//                                                       whereClause, null, null);
                                        // TODO: will move out of the loop when merged with CB's
                                        // changes make sure to look up col index out side loop
                                        String convoName = null;
//                                        if (cConvo != null
//                                                && cConvo.moveToFirst()) {
//                                            convoName = cConvo
//                                                    .getString(cConvo
//                                                            .getColumnIndex(BluetoothMapContract.ConvoContactColumns.NAME));
//                                        }

                                        contact = new BluetoothMapConvoContactElement(
                                                uci, name, displayName,
                                                presenceStatus, presenceState,
                                                lastActivity, chatState,
                                                priority, btUid);

                                        contactList.put(uci, contact);

                                        evt = new Event(
                                                EVENT_TYPE_CONVERSATION,
                                                uci,
                                                mAccount.getType(),
                                                name,
                                                String.valueOf(priority),
                                                BluetoothMapUtils
                                                .getDateTimeString(lastActivity),
                                                convoId, convoName,
                                                presenceState, presenceStatus,
                                                chatState);

                                        sendEvent(evt);
                                    }

                                } else {
                                    // Not new - compare updated content
//                                    Uri convoUri = Uri
//                                            .parse(mAccount.mBase_uri
//                                                    + "/"
//                                                    + BluetoothMapContract.TABLE_CONVERSATION);
                                    // TODO: Should be changed to own provider interface name
//                                    String whereClause = "contacts._id = "
//                                            + convoId;
//                                    Cursor cConvo = mProviderClient
//                                            .query(convoUri,
//                                                    BluetoothMapContract.BT_CONVERSATION_PROJECTION,
//                                                    whereClause, null, null);
//                                    // TODO: will move out of the loop when merged with CB's
//                                    // changes make sure to look up col index out side loop
                                    String convoName = null;
//                                    if (cConvo != null && cConvo.moveToFirst()) {
//                                        convoName = cConvo
//                                                .getString(cConvo
//                                                        .getColumnIndex(BluetoothMapContract.ConvoContactColumns.NAME));
//                                    }

                                    // Check if presence is updated
                                    int presenceState = c.getInt(cInfo.mContactColPresenceState);
                                    String presenceStatus = c.getString(
                                            cInfo.mContactColPresenceText);
                                    String currentPresenceStatus = contact
                                            .getPresenceStatus();
                                    if (contact.getPresenceAvailability() != presenceState
                                            || currentPresenceStatus != presenceStatus) {
                                        long lastOnline = c
                                                .getLong(cInfo.mContactColLastOnline);
                                        contact.setPresenceAvailability(presenceState);
                                        contact.setLastActivity(lastOnline);
                                        if (currentPresenceStatus != null
                                                && !currentPresenceStatus
                                                .equals(presenceStatus)) {
                                            contact.setPresenceStatus(presenceStatus);
                                        }
                                        Event evt = new Event(
                                                EVENT_TYPE_PRESENCE,
                                                uci,
                                                mAccount.getType(),
                                                contact.getName(),
                                                String.valueOf(contact
                                                        .getPriority()),
                                                        BluetoothMapUtils
                                                        .getDateTimeString(lastOnline),
                                                        convoId, convoName,
                                                        presenceState, presenceStatus,
                                                        0);
                                        sendEvent(evt);
                                    }

                                    // Check if chat state is updated
                                    int chatState = c.getInt(cInfo.mContactColChatState);
                                    if (contact.getChatState() != chatState) {
                                        // Get DB timestamp
                                        long lastActivity = c.getLong(cInfo.mContactColLastActive);
                                        contact.setLastActivity(lastActivity);
                                        contact.setChatState(chatState);
                                        Event evt = new Event(
                                                EVENT_TYPE_CHAT_STATE,
                                                uci,
                                                mAccount.getType(),
                                                contact.getName(),
                                                String.valueOf(contact
                                                        .getPriority()),
                                                        BluetoothMapUtils
                                                        .getDateTimeString(lastActivity),
                                                        convoId, convoName, 0, null,
                                                        chatState);
                                        sendEvent(evt);
                                    }
                                    contactList.put(uci, contact);
                                }
                            } while (c.moveToNext());
                        }
                        if(getContactList().size() > 0) {
                            // one or more contacts were deleted, hence the conversation listing
                            // version counter should change.
                            listChanged = true;
                        }
                        setContactList(contactList, listChanged);
                    } // end synchronized
                } finally {
                    if (c != null) c.close();
                }
            } catch (RemoteException e) {
                mMasInstance.restartObexServerSession();
                Log.w(TAG,
                        "Problems contacting the ContentProvider in mas Instance "
                                + mMasId + " restaring ObexServerSession");
            }

        }
        // TODO: conversation contact updates if IM and SMS(MMS in one instance
    }

    private boolean setEmailMessageStatusDelete(BluetoothMapFolderElement mCurrentFolder,
            String uriStr, long handle, int status) {
        boolean res = false;
        Uri uri = Uri.parse(uriStr + BluetoothMapContract.TABLE_MESSAGE);

        int updateCount = 0;
        ContentValues contentValues = new ContentValues();
        BluetoothMapFolderElement deleteFolder = mFolders.
                getFolderByName(BluetoothMapContract.FOLDER_NAME_DELETED);
        contentValues.put(BluetoothMapContract.MessageColumns._ID, handle);
        synchronized(getMsgListMsg()) {
            Msg msg = getMsgListMsg().get(handle);
            if (status == BluetoothMapAppParams.STATUS_VALUE_YES) {
                /* Set deleted folder id */
                long folderId = -1;
                if(deleteFolder != null) {
                    folderId = deleteFolder.getFolderId();
                }
                contentValues.put(BluetoothMapContract.MessageColumns.FOLDER_ID,folderId);
                updateCount = mResolver.update(uri, contentValues, null, null);
                /* The race between updating the value in our cached values and the database
                 * is handled by the synchronized statement. */
                if(updateCount > 0) {
                    res = true;
                    if (msg != null) {
                        msg.oldFolderId = msg.folderId;
                        /* Update the folder ID to avoid triggering an event for MCE
                         * initiated actions. */
                        msg.folderId = folderId;
                    }
                    if(D) Log.d(TAG, "Deleted MSG: " + handle + " from folderId: " + folderId);
                } else {
                    Log.w(TAG, "Msg: " + handle + " - Set delete status " + status
                            + " failed for folderId " + folderId);
                }
            } else if (status == BluetoothMapAppParams.STATUS_VALUE_NO) {
                /* Undelete message. move to old folder if we know it,
                 * else move to inbox - as dictated by the spec. */
                if(msg != null && deleteFolder != null &&
                        msg.folderId == deleteFolder.getFolderId()) {
                    /* Only modify messages in the 'Deleted' folder */
                    long folderId = -1;
                    BluetoothMapFolderElement inboxFolder = mCurrentFolder.
                            getFolderByName(BluetoothMapContract.FOLDER_NAME_INBOX);
                    if (msg != null && msg.oldFolderId != -1) {
                        folderId = msg.oldFolderId;
                    } else {
                        if(inboxFolder != null) {
                            folderId = inboxFolder.getFolderId();
                        }
                        if(D)Log.d(TAG,"We did not delete the message, hence the old folder " +
                                "is unknown. Moving to inbox.");
                    }
                    contentValues.put(BluetoothMapContract.MessageColumns.FOLDER_ID, folderId);
                    updateCount = mResolver.update(uri, contentValues, null, null);
                    if(updateCount > 0) {
                        res = true;
                        /* Update the folder ID to avoid triggering an event for MCE
                         * initiated actions. */
                        /* UPDATE: Actually the BT-Spec. states that an undelete is a move of the
                         * message to INBOX - clearified in errata 5591.
                         * Therefore we update the cache to INBOX-folderId - to trigger a message
                         * shift event to the old-folder. */
                        if(inboxFolder != null) {
                            msg.folderId = inboxFolder.getFolderId();
                        } else {
                            msg.folderId = folderId;
                        }
                    } else {
                        if(D)Log.d(TAG,"We did not delete the message, hence the old folder " +
                                "is unknown. Moving to inbox.");
                    }
                }
            }
            if(V) {
                BluetoothMapFolderElement folderElement;
                String folderName = "unknown";
                if (msg != null) {
                    folderElement = mCurrentFolder.getFolderById(msg.folderId);
                    if(folderElement != null) {
                        folderName = folderElement.getName();
                    }
                }
                Log.d(TAG,"setEmailMessageStatusDelete: " + handle + " from " + folderName
                        + " status: " + status);
            }
        }
        if(res == false) {
            Log.w(TAG, "Set delete status " + status + " failed.");
        }
        return res;
    }

    private void updateThreadId(Uri uri, String valueString, long threadId) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(valueString, threadId);
        mResolver.update(uri, contentValues, null, null);
    }

    private boolean deleteMessageMms(long handle) {
        boolean res = false;
        Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI, handle);
        Cursor c = mResolver.query(uri, null, null, null, null);
        try {
            if (c != null && c.moveToFirst()) {
                /* Move to deleted folder, or delete if already in deleted folder */
                int threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID));
                if (threadId != DELETED_THREAD_ID) {
                    /* Set deleted thread id */
                    synchronized(getMsgListMms()) {
                        Msg msg = getMsgListMms().get(handle);
                        if(msg != null) { // This will always be the case
                            msg.threadId = DELETED_THREAD_ID;
                        }
                    }
                    updateThreadId(uri, Mms.THREAD_ID, DELETED_THREAD_ID);
                } else {
                    /* Delete from observer message list to avoid delete notifications */
                    synchronized(getMsgListMms()) {
                        getMsgListMms().remove(handle);
                    }
                    /* Delete message */
                    mResolver.delete(uri, null, null);
                }
                res = true;
            }
        } finally {
            if (c != null) c.close();
        }

        return res;
    }

    private boolean unDeleteMessageMms(long handle) {
        boolean res = false;
        Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI, handle);
        Cursor c = mResolver.query(uri, null, null, null, null);
        try {
            if (c != null && c.moveToFirst()) {
                int threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID));
                if (threadId == DELETED_THREAD_ID) {
                    /* Restore thread id from address, or if no thread for address
                     * create new thread by insert and remove of fake message */
                    String address;
                    long id = c.getLong(c.getColumnIndex(Mms._ID));
                    int msgBox = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX));
                    if (msgBox == Mms.MESSAGE_BOX_INBOX) {
                        address = BluetoothMapContent.getAddressMms(mResolver, id,
                                BluetoothMapContent.MMS_FROM);
                    } else {
                        address = BluetoothMapContent.getAddressMms(mResolver, id,
                                BluetoothMapContent.MMS_TO);
                    }
                    Set<String> recipients = new HashSet<String>();
                    recipients.addAll(Arrays.asList(address));
                    Long oldThreadId = Telephony.Threads.getOrCreateThreadId(mContext, recipients);
                    synchronized(getMsgListMms()) {
                        Msg msg = getMsgListMms().get(handle);
                        if(msg != null) { // This will always be the case
                            msg.threadId = oldThreadId.intValue();
                            // Spec. states that undelete shall shift the message to Inbox.
                            // Hence we need to trigger a message shift from INBOX to old-folder
                            // after undelete.
                            // We do this by changing the cached folder value to being inbox - hence
                            // the event handler will se the update as the message have been shifted
                            // from INBOX to old-folder. (Errata 5591 clearifies this)
                            msg.type = Mms.MESSAGE_BOX_INBOX;
                        }
                    }
                    updateThreadId(uri, Mms.THREAD_ID, oldThreadId);
                } else {
                    Log.d(TAG, "Message not in deleted folder: handle " + handle
                            + " threadId " + threadId);
                }
                res = true;
            }
        } finally {
            if (c != null) c.close();
        }
        return res;
    }

    private boolean deleteMessageSms(long handle) {
        boolean res = false;
        Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, handle);
        Cursor c = mResolver.query(uri, null, null, null, null);
        try {
            if (c != null && c.moveToFirst()) {
                /* Move to deleted folder, or delete if already in deleted folder */
                int threadId = c.getInt(c.getColumnIndex(Sms.THREAD_ID));
                if (threadId != DELETED_THREAD_ID) {
                    synchronized(getMsgListSms()) {
                        Msg msg = getMsgListSms().get(handle);
                        if(msg != null) { // This will always be the case
                            msg.threadId = DELETED_THREAD_ID;
                        }
                    }
                    /* Set deleted thread id */
                    updateThreadId(uri, Sms.THREAD_ID, DELETED_THREAD_ID);
                } else {
                    /* Delete from observer message list to avoid delete notifications */
                    synchronized(getMsgListSms()) {
                        getMsgListSms().remove(handle);
                    }
                    /* Delete message */
                    mResolver.delete(uri, null, null);
                }
                res = true;
            }
        } finally {
            if (c != null) c.close();
        }
        return res;
    }

    private boolean unDeleteMessageSms(long handle) {
        boolean res = false;
        Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, handle);
        Cursor c = mResolver.query(uri, null, null, null, null);
        try {
            if (c != null && c.moveToFirst()) {
                int threadId = c.getInt(c.getColumnIndex(Sms.THREAD_ID));
                if (threadId == DELETED_THREAD_ID) {
                    String address = c.getString(c.getColumnIndex(Sms.ADDRESS));
                    Set<String> recipients = new HashSet<String>();
                    recipients.addAll(Arrays.asList(address));
                    Long oldThreadId = Telephony.Threads.getOrCreateThreadId(mContext, recipients);
                    synchronized(getMsgListSms()) {
                        Msg msg = getMsgListSms().get(handle);
                        if(msg != null) {
                            msg.threadId = oldThreadId.intValue();
                            /* This will always be the case
                             * The threadId is specified as an int, so it is safe to truncate
                             * TODO: Test that this will trigger a message-shift from Inbox
                             * to old-folder
                             **/
                            /* Spec. states that undelete shall shift the message to Inbox.
                             * Hence we need to trigger a message shift from INBOX to old-folder
                             * after undelete.
                             * We do this by changing the cached folder value to being inbox - hence
                             * the event handler will se the update as the message have been shifted
                             * from INBOX to old-folder. (Errata 5591 clearifies this)
                             * */
                            msg.type = Sms.MESSAGE_TYPE_INBOX;
                        }
                    }
                    updateThreadId(uri, Sms.THREAD_ID, oldThreadId);
                } else {
                    Log.d(TAG, "Message not in deleted folder: handle " + handle
                            + " threadId " + threadId);
                }
                res = true;
            }
        } finally {
            if (c != null) c.close();
        }
        return res;
    }

    /**
     *
     * @param handle
     * @param type
     * @param mCurrentFolder
     * @param uriStr
     * @param statusValue
     * @return true is success
     */
    public boolean setMessageStatusDeleted(long handle, TYPE type,
            BluetoothMapFolderElement mCurrentFolder, String uriStr, int statusValue) {
        boolean res = false;
        if (D) Log.d(TAG, "setMessageStatusDeleted: handle " + handle
                + " type " + type + " value " + statusValue);

        if (type == TYPE.EMAIL) {
            res = setEmailMessageStatusDelete(mCurrentFolder, uriStr, handle, statusValue);
        } else if (type == TYPE.IM) {
            // TODO: to do when deleting IM message
            if (D) Log.d(TAG, "setMessageStatusDeleted: IM not handled" );
        } else {
            if (statusValue == BluetoothMapAppParams.STATUS_VALUE_YES) {
                if (type == TYPE.SMS_GSM || type == TYPE.SMS_CDMA) {
                    res = deleteMessageSms(handle);
                } else if (type == TYPE.MMS) {
                    res = deleteMessageMms(handle);
                }
            } else if (statusValue == BluetoothMapAppParams.STATUS_VALUE_NO) {
                if (type == TYPE.SMS_GSM || type == TYPE.SMS_CDMA) {
                    res = unDeleteMessageSms(handle);
                } else if (type == TYPE.MMS) {
                    res = unDeleteMessageMms(handle);
                }
            }
        }
        return res;
    }

    /**
     *
     * @param handle
     * @param type
     * @param uriStr
     * @param statusValue
     * @return true at success
     */
    public boolean setMessageStatusRead(long handle, TYPE type, String uriStr, int statusValue)
            throws RemoteException{
        int count = 0;

        if (D) Log.d(TAG, "setMessageStatusRead: handle " + handle
                + " type " + type + " value " + statusValue);

        /* Approved MAP spec errata 3445 states that read status initiated
         * by the MCE shall change the MSE read status. */
        if (type == TYPE.SMS_GSM || type == TYPE.SMS_CDMA) {
            Uri uri = Sms.Inbox.CONTENT_URI;
            ContentValues contentValues = new ContentValues();
            contentValues.put(Sms.READ, statusValue);
            contentValues.put(Sms.SEEN, statusValue);
            String where = Sms._ID+"="+handle;
            String values = contentValues.toString();
            if (D) Log.d(TAG, " -> SMS Uri: " + uri.toString() +
                    " Where " + where + " values " + values);
            synchronized(getMsgListSms()) {
                Msg msg = getMsgListSms().get(handle);
                if(msg != null) { // This will always be the case
                    msg.flagRead = statusValue;
                }
            }
            count = mResolver.update(uri, contentValues, where, null);
            if (D) Log.d(TAG, " -> "+count +" rows updated!");

        } else if (type == TYPE.MMS) {
            Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI, handle);
            if (D) Log.d(TAG, " -> MMS Uri: " + uri.toString());
            ContentValues contentValues = new ContentValues();
            contentValues.put(Mms.READ, statusValue);
            synchronized(getMsgListMms()) {
                Msg msg = getMsgListMms().get(handle);
                if(msg != null) { // This will always be the case
                    msg.flagRead = statusValue;
                }
            }
            count = mResolver.update(uri, contentValues, null, null);
            if (D) Log.d(TAG, " -> "+count +" rows updated!");
        } else if (type == TYPE.EMAIL ||
                type == TYPE.IM) {
            Uri uri = mMessageUri;
            ContentValues contentValues = new ContentValues();
            contentValues.put(BluetoothMapContract.MessageColumns.FLAG_READ, statusValue);
            contentValues.put(BluetoothMapContract.MessageColumns._ID, handle);
            synchronized(getMsgListMsg()) {
                Msg msg = getMsgListMsg().get(handle);
                if(msg != null) { // This will always be the case
                    msg.flagRead = statusValue;
                }
            }
            count = mProviderClient.update(uri, contentValues, null, null);
        }

        return (count > 0);
    }

    private class PushMsgInfo {
        long id;
        int transparent;
        int retry;
        String phone;
        Uri uri;
        long timestamp;
        int parts;
        int partsSent;
        int partsDelivered;
        boolean resend;
        boolean sendInProgress;
        boolean failedSent; // Set to true if a single part sent fail is received.
        int statusDelivered; // Set to != 0 if a single part deliver fail is received.

        public PushMsgInfo(long id, int transparent,
                int retry, String phone, Uri uri) {
            this.id = id;
            this.transparent = transparent;
            this.retry = retry;
            this.phone = phone;
            this.uri = uri;
            this.resend = false;
            this.sendInProgress = false;
            this.failedSent = false;
            this.statusDelivered = 0; /* Assume success */
            this.timestamp = 0;
        };
    }

    private Map<Long, PushMsgInfo> mPushMsgList =
            Collections.synchronizedMap(new HashMap<Long, PushMsgInfo>());

    public long pushMessage(BluetoothMapbMessage msg, BluetoothMapFolderElement folderElement,
            BluetoothMapAppParams ap, String emailBaseUri)
                    throws IllegalArgumentException, RemoteException, IOException {
        if (D) Log.d(TAG, "pushMessage");
        ArrayList<BluetoothMapbMessage.vCard> recipientList = msg.getRecipients();
        int transparent = (ap.getTransparent() == BluetoothMapAppParams.INVALID_VALUE_PARAMETER) ?
                0 : ap.getTransparent();
        int retry = ap.getRetry();
        int charset = ap.getCharset();
        long handle = -1;
        long folderId = -1;

        if (recipientList == null) {
            if (D) Log.d(TAG, "empty recipient list");
            return -1;
        }

        if ( msg.getType().equals(TYPE.EMAIL) ) {
            /* Write the message to the database */
            String msgBody = ((BluetoothMapbMessageEmail) msg).getEmailBody();
            if (V) {
                int length = msgBody.length();
                Log.v(TAG, "pushMessage: message string length = " + length);
                String messages[] = msgBody.split("\r\n");
                Log.v(TAG, "pushMessage: messages count=" + messages.length);
                for(int i = 0; i < messages.length; i++) {
                    Log.v(TAG, "part " + i + ":" + messages[i]);
                }
            }
            FileOutputStream os = null;
            ParcelFileDescriptor fdOut = null;
            Uri uriInsert = Uri.parse(emailBaseUri + BluetoothMapContract.TABLE_MESSAGE);
            if (D) Log.d(TAG, "pushMessage - uriInsert= " + uriInsert.toString() +
                    ", intoFolder id=" + folderElement.getFolderId());

            synchronized(getMsgListMsg()) {
                // Now insert the empty message into folder
                ContentValues values = new ContentValues();
                folderId = folderElement.getFolderId();
                values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, folderId);
                Uri uriNew = mProviderClient.insert(uriInsert, values);
                if (D) Log.d(TAG, "pushMessage - uriNew= " + uriNew.toString());
                handle =  Long.parseLong(uriNew.getLastPathSegment());

                try {
                    fdOut = mProviderClient.openFile(uriNew, "w");
                    os = new FileOutputStream(fdOut.getFileDescriptor());
                    // Write Email to DB
                    os.write(msgBody.getBytes(), 0, msgBody.getBytes().length);
                } catch (FileNotFoundException e) {
                    Log.w(TAG, e);
                    throw(new IOException("Unable to open file stream"));
                } catch (NullPointerException e) {
                    Log.w(TAG, e);
                    throw(new IllegalArgumentException("Unable to parse message."));
                } finally {
                    try {
                        if(os != null)
                            os.close();
                    } catch (IOException e) {Log.w(TAG, e);}
                    try {
                        if(fdOut != null)
                            fdOut.close();
                    } catch (IOException e) {Log.w(TAG, e);}
                }

                /* Extract the data for the inserted message, and store in local mirror, to
                 * avoid sending a NewMessage Event. */
                /*TODO: We need to add the new 1.1 parameter as well:-) e.g. read*/
                Msg newMsg = new Msg(handle, folderId, 1); // TODO: Create define for read-state
                newMsg.transparent = (transparent == 1) ? true : false;
                if ( folderId == folderElement.getFolderByName(
                        BluetoothMapContract.FOLDER_NAME_OUTBOX).getFolderId() ) {
                    newMsg.localInitiatedSend = true;
                }
                getMsgListMsg().put(handle, newMsg);
            }
        } else { // type SMS_* of MMS
            for (BluetoothMapbMessage.vCard recipient : recipientList) {
                // Only send the message to the top level recipient
                if(recipient.getEnvLevel() == 0)
                {
                    /* Only send to first address */
                    String phone = recipient.getFirstPhoneNumber();
                    String email = recipient.getFirstEmail();
                    String folder = folderElement.getName();
                    boolean read = false;
                    boolean deliveryReport = true;
                    String msgBody = null;

                    /* If MMS contains text only and the size is less than ten SMS's
                     * then convert the MMS to type SMS and then proceed
                     */
                    if (msg.getType().equals(TYPE.MMS) &&
                            (((BluetoothMapbMessageMime) msg).getTextOnly() == true)) {
                        msgBody = ((BluetoothMapbMessageMime) msg).getMessageAsText();
                        SmsManager smsMng = SmsManager.getDefault();
                        ArrayList<String> parts = smsMng.divideMessage(msgBody);
                        int smsParts = parts.size();
                        if (smsParts  <= CONVERT_MMS_TO_SMS_PART_COUNT ) {
                            if (D) Log.d(TAG, "pushMessage - converting MMS to SMS, sms parts="
                                    + smsParts );
                            msg.setType(mSmsType);
                        } else {
                            if (D) Log.d(TAG, "pushMessage - MMS text only but to big to " +
                                    "convert to SMS");
                            msgBody = null;
                        }

                    }

                    if (msg.getType().equals(TYPE.MMS)) {
                        /* Send message if folder is outbox else just store in draft*/
                        handle = sendMmsMessage(folder, phone, (BluetoothMapbMessageMime)msg,
                                transparent, retry);
                    } else if (msg.getType().equals(TYPE.SMS_GSM) ||
                            msg.getType().equals(TYPE.SMS_CDMA) ) {
                        /* Add the message to the database */
                        if(msgBody == null)
                            msgBody = ((BluetoothMapbMessageSms) msg).getSmsBody();

                        if (TextUtils.isEmpty(msgBody)) {
                            Log.d(TAG, "PushMsg: Empty msgBody ");
                            /* not allowed to push empty message */
                            throw new IllegalArgumentException("push EMPTY message: Invalid Body");
                        }
                        /* We need to lock the SMS list while updating the database,
                         * to avoid sending events on MCE initiated operation. */
                        Uri contentUri = Uri.parse(Sms.CONTENT_URI+ "/" + folder);
                        Uri uri;
                        synchronized(getMsgListSms()) {
                            uri = Sms.addMessageToUri(mResolver, contentUri, phone, msgBody,
                                    "", System.currentTimeMillis(), read, deliveryReport);

                            if(V) Log.v(TAG, "Sms.addMessageToUri() returned: " + uri);
                            if (uri == null) {
                                if (D) Log.d(TAG, "pushMessage - failure on add to uri "
                                        + contentUri);
                                return -1;
                            }
                            Cursor c = mResolver.query(uri, SMS_PROJECTION_SHORT, null, null, null);

                            /* Extract the data for the inserted message, and store in local mirror,
                             * to avoid sending a NewMessage Event. */
                            try {
                                if (c != null && c.moveToFirst()) {
                                    long id = c.getLong(c.getColumnIndex(Sms._ID));
                                    int type = c.getInt(c.getColumnIndex(Sms.TYPE));
                                    int threadId = c.getInt(c.getColumnIndex(Sms.THREAD_ID));
                                    int readFlag = c.getInt(c.getColumnIndex(Sms.READ));
                                    if(V) Log.v(TAG, "add message with id=" + id +
                                            " type=" + type + " threadId=" + threadId +
                                            " readFlag=" + readFlag + "to mMsgListSms");
                                    Msg newMsg = new Msg(id, type, threadId, readFlag);
                                    getMsgListSms().put(id, newMsg);
                                    c.close();
                                } else {
                                    Log.w(TAG,"Message: " + uri + " no longer exist!");
                                    /* This can only happen, if the message is deleted
                                     * just as it is added */
                                    return -1;
                                }
                            } finally {
                                if (c != null) c.close();
                            }

                            handle = Long.parseLong(uri.getLastPathSegment());

                            /* Send message if folder is outbox */
                            if (folder.equalsIgnoreCase(BluetoothMapContract.FOLDER_NAME_OUTBOX)) {
                                PushMsgInfo msgInfo = new PushMsgInfo(handle, transparent,
                                        retry, phone, uri);
                                mPushMsgList.put(handle, msgInfo);
                                sendMessage(msgInfo, msgBody);
                                if(V) Log.v(TAG, "sendMessage returned...");
                            } /* else just added to draft */

                            /* sendMessage causes the message to be deleted and reinserted,
                             * hence we need to lock the list while this is happening. */
                        }
                    } else {
                        if (D) Log.d(TAG, "pushMessage - failure on type " );
                        return -1;
                    }
                }
            }
        }

        /* If multiple recipients return handle of last */
        return handle;
    }

    public long sendMmsMessage(String folder, String to_address, BluetoothMapbMessageMime msg,
            int transparent, int retry) {
        /*
         *strategy:
         *1) parse message into parts
         *if folder is outbox/drafts:
         *2) push message to draft
         *if folder is outbox:
         *3) move message to outbox (to trigger the mms app to add msg to pending_messages list)
         *4) send intent to mms app in order to wake it up.
         *else if folder !outbox:
         *1) push message to folder
         * */
        if (folder != null && (folder.equalsIgnoreCase(BluetoothMapContract.FOLDER_NAME_OUTBOX)
                ||  folder.equalsIgnoreCase(BluetoothMapContract.FOLDER_NAME_DRAFT))) {
            long handle = pushMmsToFolder(Mms.MESSAGE_BOX_DRAFTS, to_address, msg);
            /* if invalid handle (-1) then just return the handle
             * - else continue sending (if folder is outbox) */
            if (BluetoothMapAppParams.INVALID_VALUE_PARAMETER != handle &&
                    folder.equalsIgnoreCase(BluetoothMapContract.FOLDER_NAME_OUTBOX)) {
                Uri btMmsUri = MmsFileProvider.CONTENT_URI.buildUpon()
                        .appendPath(Long.toString(handle)).build();
                Intent sentIntent = new Intent(ACTION_MESSAGE_SENT);
                // TODO: update the mmsMsgList <- done in pushMmsToFolder() but check
                sentIntent.setType("message/" + Long.toString(handle));
                sentIntent.putExtra(EXTRA_MESSAGE_SENT_MSG_TYPE, TYPE.MMS.ordinal());
                sentIntent.putExtra(EXTRA_MESSAGE_SENT_HANDLE, handle); // needed for notification
                sentIntent.putExtra(EXTRA_MESSAGE_SENT_TRANSPARENT, transparent);
                sentIntent.putExtra(EXTRA_MESSAGE_SENT_RETRY, retry);
                //sentIntent.setDataAndNormalize(btMmsUri);
                PendingIntent pendingSendIntent = PendingIntent.getBroadcast(mContext, 0,
                        sentIntent, 0);
                SmsManager.getDefault().sendMultimediaMessage(mContext,
                        btMmsUri, null/*locationUrl*/, null/*configOverrides*/,
                        pendingSendIntent);
            }
            return handle;
        } else {
            /* not allowed to push mms to anything but outbox/draft */
            throw  new IllegalArgumentException("Cannot push message to other " +
                    "folders than outbox/draft");
        }
    }

    private void moveDraftToOutbox(long handle) {
        moveMmsToFolder(handle, mResolver, Mms.MESSAGE_BOX_OUTBOX);
    }

    /**
     * Move a MMS to another folder.
     * @param handle the CP handle of the message to move
     * @param resolver the ContentResolver to use
     * @param folder the destination folder - use Mms.MESSAGE_BOX_xxx
     */
    private static void moveMmsToFolder(long handle, ContentResolver resolver, int folder) {
        /*Move message by changing the msg_box value in the content provider database */
        if (handle != -1) {
            String whereClause = " _id= " + handle;
            Uri uri = Mms.CONTENT_URI;
            Cursor queryResult = resolver.query(uri, null, whereClause, null, null);
            try {
                if (queryResult != null) {
                    if (queryResult.getCount() > 0) {
                        queryResult.moveToFirst();
                        ContentValues data = new ContentValues();
                        /* set folder to be outbox */
                        data.put(Mms.MESSAGE_BOX, folder);
                        resolver.update(uri, data, whereClause, null);
                        if (D) Log.d(TAG, "moved MMS message to " + getMmsFolderName(folder));
                    }
                } else {
                    Log.w(TAG, "Could not move MMS message to " + getMmsFolderName(folder));
                }
            } finally {
                if (queryResult != null) queryResult.close();
            }
        }
    }
    private long pushMmsToFolder(int folder, String to_address, BluetoothMapbMessageMime msg) {
        /**
         * strategy:
         * 1) parse msg into parts + header
         * 2) create thread id (abuse the ease of adding an SMS to get id for thread)
         * 3) push parts into content://mms/parts/ table
         * 3)
         */

        ContentValues values = new ContentValues();
        values.put(Mms.MESSAGE_BOX, folder);
        values.put(Mms.READ, 0);
        values.put(Mms.SEEN, 0);
        if(msg.getSubject() != null) {
            values.put(Mms.SUBJECT, msg.getSubject());
        } else {
            values.put(Mms.SUBJECT, "");
        }

        if(msg.getSubject() != null && msg.getSubject().length() > 0) {
            values.put(Mms.SUBJECT_CHARSET, 106);
        }
        values.put(Mms.CONTENT_TYPE, "application/vnd.wap.multipart.related");
        values.put(Mms.EXPIRY, 604800);
        values.put(Mms.MESSAGE_CLASS, PduHeaders.MESSAGE_CLASS_PERSONAL_STR);
        values.put(Mms.MESSAGE_TYPE, PduHeaders.MESSAGE_TYPE_SEND_REQ);
        values.put(Mms.MMS_VERSION, PduHeaders.CURRENT_MMS_VERSION);
        values.put(Mms.PRIORITY, PduHeaders.PRIORITY_NORMAL);
        values.put(Mms.READ_REPORT, PduHeaders.VALUE_NO);
        values.put(Mms.TRANSACTION_ID, "T"+ Long.toHexString(System.currentTimeMillis()));
        values.put(Mms.DELIVERY_REPORT, PduHeaders.VALUE_NO);
        values.put(Mms.LOCKED, 0);
        if(msg.getTextOnly() == true)
            values.put(Mms.TEXT_ONLY, true);
        values.put(Mms.MESSAGE_SIZE, msg.getSize());

        // Get thread id
        Set<String> recipients = new HashSet<String>();
        recipients.addAll(Arrays.asList(to_address));
        values.put(Mms.THREAD_ID, Telephony.Threads.getOrCreateThreadId(mContext, recipients));
        Uri uri = Mms.CONTENT_URI;

        synchronized (getMsgListMms()) {

            uri = mResolver.insert(uri, values);

            if (uri == null) {
                // unable to insert MMS
                Log.e(TAG, "Unabled to insert MMS " + values + "Uri: " + uri);
                return -1;
            }
            /* As we already have all the values we need, we could skip the query, but
               doing the query ensures we get any changes made by the content provider
               at insert. */
            Cursor c = mResolver.query(uri, MMS_PROJECTION_SHORT, null, null, null);
            try {
                if (c != null && c.moveToFirst()) {
                    long id = c.getLong(c.getColumnIndex(Mms._ID));
                    int type = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX));
                    int threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID));
                    int readStatus = c.getInt(c.getColumnIndex(Mms.READ));

                    /* We must filter out any actions made by the MCE. Add the new message to
                     * the list of known messages. */

                    Msg newMsg = new Msg(id, type, threadId, readStatus);
                    newMsg.localInitiatedSend = true;
                    getMsgListMms().put(id, newMsg);
                    c.close();
                }
            } finally {
                if (c != null) c.close();
            }
        } // Done adding changes, unlock access to mMsgListMms to allow sending MMS events again

        long handle = Long.parseLong(uri.getLastPathSegment());
        if (V) Log.v(TAG, " NEW URI " + uri.toString());

        try {
            if(msg.getMimeParts() == null) {
                /* Perhaps this message have been deleted, and no longer have any content,
                 * but only headers */
                Log.w(TAG, "No MMS parts present...");
            } else {
                if(V) Log.v(TAG, "Adding " + msg.getMimeParts().size()
                        + " parts to the data base.");
                for(MimePart part : msg.getMimeParts()) {
                    int count = 0;
                    count++;
                    values.clear();
                    if(part.mContentType != null &&
                            part.mContentType.toUpperCase().contains("TEXT")) {
                        values.put(Mms.Part.CONTENT_TYPE, "text/plain");
                        values.put(Mms.Part.CHARSET, 106);
                        if(part.mPartName != null) {
                            values.put(Mms.Part.FILENAME, part.mPartName);
                            values.put(Mms.Part.NAME, part.mPartName);
                        } else {
                            values.put(Mms.Part.FILENAME, "text_" + count +".txt");
                            values.put(Mms.Part.NAME, "text_" + count +".txt");
                        }
                        // Ensure we have "ci" set
                        if(part.mContentId != null) {
                            values.put(Mms.Part.CONTENT_ID, part.mContentId);
                        } else {
                            if(part.mPartName != null) {
                                values.put(Mms.Part.CONTENT_ID, "<" + part.mPartName + ">");
                            } else {
                                values.put(Mms.Part.CONTENT_ID, "<text_" + count + ">");
                            }
                        }
                        // Ensure we have "cl" set
                        if(part.mContentLocation != null) {
                            values.put(Mms.Part.CONTENT_LOCATION, part.mContentLocation);
                        } else {
                            if(part.mPartName != null) {
                                values.put(Mms.Part.CONTENT_LOCATION, part.mPartName + ".txt");
                            } else {
                                values.put(Mms.Part.CONTENT_LOCATION, "text_" + count + ".txt");
                            }
                        }

                        if(part.mContentDisposition != null) {
                            values.put(Mms.Part.CONTENT_DISPOSITION, part.mContentDisposition);
                        }
                        values.put(Mms.Part.TEXT, part.getDataAsString());
                        uri = Uri.parse(Mms.CONTENT_URI + "/" + handle + "/part");
                        uri = mResolver.insert(uri, values);
                        if(V) Log.v(TAG, "Added TEXT part");

                    } else if (part.mContentType != null &&
                            part.mContentType.toUpperCase().contains("SMIL")){
                        values.put(Mms.Part.SEQ, -1);
                        values.put(Mms.Part.CONTENT_TYPE, "application/smil");
                        if(part.mContentId != null) {
                            values.put(Mms.Part.CONTENT_ID, part.mContentId);
                        } else {
                            values.put(Mms.Part.CONTENT_ID, "<smil_" + count + ">");
                        }
                        if(part.mContentLocation != null) {
                            values.put(Mms.Part.CONTENT_LOCATION, part.mContentLocation);
                        } else {
                            values.put(Mms.Part.CONTENT_LOCATION, "smil_" + count + ".xml");
                        }

                        if(part.mContentDisposition != null)
                            values.put(Mms.Part.CONTENT_DISPOSITION, part.mContentDisposition);
                        values.put(Mms.Part.FILENAME, "smil.xml");
                        values.put(Mms.Part.NAME, "smil.xml");
                        values.put(Mms.Part.TEXT, new String(part.mData, "UTF-8"));

                        uri = Uri.parse(Mms.CONTENT_URI+ "/" + handle + "/part");
                        uri = mResolver.insert(uri, values);
                        if (V) Log.v(TAG, "Added SMIL part");

                    }else /*VIDEO/AUDIO/IMAGE*/ {
                        writeMmsDataPart(handle, part, count);
                        if (V) Log.v(TAG, "Added OTHER part");
                    }
                    if (uri != null){
                        if (V) Log.v(TAG, "Added part with content-type: " + part.mContentType
                                + " to Uri: " + uri.toString());
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, e);
        } catch (IOException e) {
            Log.w(TAG, e);
        }

        values.clear();
        values.put(Mms.Addr.CONTACT_ID, "null");
        values.put(Mms.Addr.ADDRESS, "insert-address-token");
        values.put(Mms.Addr.TYPE, BluetoothMapContent.MMS_FROM);
        values.put(Mms.Addr.CHARSET, 106);

        uri = Uri.parse(Mms.CONTENT_URI + "/"  + handle + "/addr");
        uri = mResolver.insert(uri, values);
        if (uri != null && V){
            Log.v(TAG, " NEW URI " + uri.toString());
        }

        values.clear();
        values.put(Mms.Addr.CONTACT_ID, "null");
        values.put(Mms.Addr.ADDRESS, to_address);
        values.put(Mms.Addr.TYPE, BluetoothMapContent.MMS_TO);
        values.put(Mms.Addr.CHARSET, 106);

        uri = Uri.parse(Mms.CONTENT_URI + "/"  + handle + "/addr");
        uri = mResolver.insert(uri, values);
        if (uri != null && V){
            Log.v(TAG, " NEW URI " + uri.toString());
        }
        return handle;
    }


    private void writeMmsDataPart(long handle, MimePart part, int count) throws IOException{
        ContentValues values = new ContentValues();
        values.put(Mms.Part.MSG_ID, handle);
        if(part.mContentType != null) {
            values.put(Mms.Part.CONTENT_TYPE, part.mContentType);
        } else {
            Log.w(TAG, "MMS has no CONTENT_TYPE for part " + count);
        }
        if(part.mContentId != null) {
            values.put(Mms.Part.CONTENT_ID, part.mContentId);
        } else {
            if(part.mPartName != null) {
                values.put(Mms.Part.CONTENT_ID, "<" + part.mPartName + ">");
            } else {
                values.put(Mms.Part.CONTENT_ID, "<part_" + count + ">");
            }
        }

        if(part.mContentLocation != null) {
            values.put(Mms.Part.CONTENT_LOCATION, part.mContentLocation);
        } else {
            if(part.mPartName != null) {
                values.put(Mms.Part.CONTENT_LOCATION, part.mPartName + ".dat");
            } else {
                values.put(Mms.Part.CONTENT_LOCATION, "part_" + count + ".dat");
            }
        }
        if(part.mContentDisposition != null)
            values.put(Mms.Part.CONTENT_DISPOSITION, part.mContentDisposition);
        if(part.mPartName != null) {
            values.put(Mms.Part.FILENAME, part.mPartName);
            values.put(Mms.Part.NAME, part.mPartName);
        } else {
            /* We must set at least one part identifier */
            values.put(Mms.Part.FILENAME, "part_" + count + ".dat");
            values.put(Mms.Part.NAME, "part_" + count + ".dat");
        }
        Uri partUri = Uri.parse(Mms.CONTENT_URI + "/" + handle + "/part");
        Uri res = mResolver.insert(partUri, values);

        // Add data to part
        OutputStream os = mResolver.openOutputStream(res);
        os.write(part.mData);
        os.close();
    }


    public void sendMessage(PushMsgInfo msgInfo, String msgBody) {

        SmsManager smsMng = SmsManager.getDefault();
        ArrayList<String> parts = smsMng.divideMessage(msgBody);
        msgInfo.parts = parts.size();
        // We add a time stamp to differentiate delivery reports from each other for resent messages
        msgInfo.timestamp = Calendar.getInstance().getTime().getTime();
        msgInfo.partsDelivered = 0;
        msgInfo.partsSent = 0;

        ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(msgInfo.parts);
        ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(msgInfo.parts);

        /*       We handle the SENT intent in the MAP service, as this object
         *       is destroyed at disconnect, hence if a disconnect occur while sending
         *       a message, there is no intent handler to move the message from outbox
         *       to the correct folder.
         *       The correct solution would be to create a service that will start based on
         *       the intent, if BT is turned off. */

        if (parts != null && parts.size() > 0) {
            for (int i = 0; i < msgInfo.parts; i++) {
                Intent intentDelivery, intentSent;

                intentDelivery = new Intent(ACTION_MESSAGE_DELIVERY, null);
                /* Add msgId and part number to ensure the intents are different, and we
                 * thereby get an intent for each msg part.
                 * setType is needed to create different intents for each message id/ time stamp,
                 * as the extras are not used when comparing. */
                intentDelivery.setType("message/" + Long.toString(msgInfo.id) +
                        msgInfo.timestamp + i);
                intentDelivery.putExtra(EXTRA_MESSAGE_SENT_HANDLE, msgInfo.id);
                intentDelivery.putExtra(EXTRA_MESSAGE_SENT_TIMESTAMP, msgInfo.timestamp);
                PendingIntent pendingIntentDelivery = PendingIntent.getBroadcast(mContext, 0,
                        intentDelivery, PendingIntent.FLAG_UPDATE_CURRENT);

                intentSent = new Intent(ACTION_MESSAGE_SENT, null);
                /* Add msgId and part number to ensure the intents are different, and we
                 * thereby get an intent for each msg part.
                 * setType is needed to create different intents for each message id/ time stamp,
                 * as the extras are not used when comparing. */
                intentSent.setType("message/" + Long.toString(msgInfo.id) + msgInfo.timestamp + i);
                intentSent.putExtra(EXTRA_MESSAGE_SENT_HANDLE, msgInfo.id);
                intentSent.putExtra(EXTRA_MESSAGE_SENT_URI, msgInfo.uri.toString());
                intentSent.putExtra(EXTRA_MESSAGE_SENT_RETRY, msgInfo.retry);
                intentSent.putExtra(EXTRA_MESSAGE_SENT_TRANSPARENT, msgInfo.transparent);

                PendingIntent pendingIntentSent = PendingIntent.getBroadcast(mContext, 0,
                        intentSent, PendingIntent.FLAG_UPDATE_CURRENT);

                // We use the same pending intent for all parts, but do not set the one shot flag.
                deliveryIntents.add(pendingIntentDelivery);
                sentIntents.add(pendingIntentSent);
            }

            Log.d(TAG, "sendMessage to " + msgInfo.phone);

            smsMng.sendMultipartTextMessage(msgInfo.phone, null, parts, sentIntents,
                    deliveryIntents);
        }
    }

    private class SmsBroadcastReceiver extends BroadcastReceiver {
        private final String[] ID_PROJECTION = new String[] { Sms._ID };
        private final Uri UPDATE_STATUS_URI = Uri.withAppendedPath(Sms.CONTENT_URI, "/status");

        public void register() {
            Handler handler = new Handler(Looper.getMainLooper());

            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_MESSAGE_DELIVERY);
            try{
                intentFilter.addDataType("message/*");
            } catch (MalformedMimeTypeException e) {
                Log.e(TAG, "Wrong mime type!!!", e);
            }

            mContext.registerReceiver(this, intentFilter, null, handler);
        }

        public void unregister() {
            try {
                mContext.unregisterReceiver(this);
            } catch (IllegalArgumentException e) {
                /* do nothing */
            }
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            long handle = intent.getLongExtra(EXTRA_MESSAGE_SENT_HANDLE, -1);
            PushMsgInfo msgInfo = mPushMsgList.get(handle);

            Log.d(TAG, "onReceive: action"  + action);

            if (msgInfo == null) {
                Log.d(TAG, "onReceive: no msgInfo found for handle " + handle);
                return;
            }

            if (action.equals(ACTION_MESSAGE_SENT)) {
                int result = intent.getIntExtra(EXTRA_MESSAGE_SENT_RESULT,
                        Activity.RESULT_CANCELED);
                msgInfo.partsSent++;
                if(result != Activity.RESULT_OK) {
                    /* If just one of the parts in the message fails, we need to send the
                     * entire message again
                     */
                    msgInfo.failedSent = true;
                }
                if(D) Log.d(TAG, "onReceive: msgInfo.partsSent = " + msgInfo.partsSent
                        + ", msgInfo.parts = " + msgInfo.parts + " result = " + result);

                if (msgInfo.partsSent == msgInfo.parts) {
                    actionMessageSent(context, intent, msgInfo);
                }
            } else if (action.equals(ACTION_MESSAGE_DELIVERY)) {
                long timestamp = intent.getLongExtra(EXTRA_MESSAGE_SENT_TIMESTAMP, 0);
                int status = -1;
                if(msgInfo.timestamp == timestamp) {
                    msgInfo.partsDelivered++;
                    byte[] pdu = intent.getByteArrayExtra("pdu");
                    String format = intent.getStringExtra("format");

                    SmsMessage message = SmsMessage.createFromPdu(pdu, format);
                    if (message == null) {
                        Log.d(TAG, "actionMessageDelivery: Can't get message from pdu");
                        return;
                    }
                    status = message.getStatus();
                    if(status != 0/*0 is success*/) {
                        msgInfo.statusDelivered = status;
                        if(D) Log.d(TAG, "msgInfo.statusDelivered = " + status);
                        Sms.moveMessageToFolder(mContext, msgInfo.uri, Sms.MESSAGE_TYPE_FAILED, 0);
                    } else {
                        Sms.moveMessageToFolder(mContext, msgInfo.uri, Sms.MESSAGE_TYPE_SENT, 0);
                    }
                }
                if (msgInfo.partsDelivered == msgInfo.parts) {
                    actionMessageDelivery(context, intent, msgInfo);
                }
            } else {
                Log.d(TAG, "onReceive: Unknown action " + action);
            }
        }

        private void actionMessageSent(Context context, Intent intent, PushMsgInfo msgInfo) {
            /* As the MESSAGE_SENT intent is forwarded from the MAP service, we use the intent
             * to carry the result, as getResult() will not return the correct value.
             */
            boolean delete = false;

            if(D) Log.d(TAG,"actionMessageSent(): msgInfo.failedSent = " + msgInfo.failedSent);

            msgInfo.sendInProgress = false;

            if (msgInfo.failedSent == false) {
                if(D) Log.d(TAG, "actionMessageSent: result OK");
                if (msgInfo.transparent == 0) {
                    if (!Sms.moveMessageToFolder(context, msgInfo.uri,
                            Sms.MESSAGE_TYPE_SENT, 0)) {
                        Log.w(TAG, "Failed to move " + msgInfo.uri + " to SENT");
                    }
                } else {
                    delete = true;
                }

                Event evt = new Event(EVENT_TYPE_SENDING_SUCCESS, msgInfo.id,
                        getSmsFolderName(Sms.MESSAGE_TYPE_SENT), null, mSmsType);
                sendEvent(evt);

            } else {
                if (msgInfo.retry == 1) {
                    /* Notify failure, but keep message in outbox for resending */
                    msgInfo.resend = true;
                    msgInfo.partsSent = 0; // Reset counter for the retry
                    msgInfo.failedSent = false;
                    Event evt = new Event(EVENT_TYPE_SENDING_FAILURE, msgInfo.id,
                            getSmsFolderName(Sms.MESSAGE_TYPE_OUTBOX), null, mSmsType);
                    sendEvent(evt);
                } else {
                    if (msgInfo.transparent == 0) {
                        if (!Sms.moveMessageToFolder(context, msgInfo.uri,
                                Sms.MESSAGE_TYPE_FAILED, 0)) {
                            Log.w(TAG, "Failed to move " + msgInfo.uri + " to FAILED");
                        }
                    } else {
                        delete = true;
                    }

                    Event evt = new Event(EVENT_TYPE_SENDING_FAILURE, msgInfo.id,
                            getSmsFolderName(Sms.MESSAGE_TYPE_FAILED), null, mSmsType);
                    sendEvent(evt);
                }
            }

            if (delete == true) {
                /* Delete from Observer message list to avoid delete notifications */
                synchronized(getMsgListSms()) {
                    getMsgListSms().remove(msgInfo.id);
                }

                /* Delete from DB */
                mResolver.delete(msgInfo.uri, null, null);
            }
        }

        private void actionMessageDelivery(Context context, Intent intent, PushMsgInfo msgInfo) {
            Uri messageUri = intent.getData();
            msgInfo.sendInProgress = false;

            Cursor cursor = mResolver.query(msgInfo.uri, ID_PROJECTION, null, null, null);

            try {
                if (cursor.moveToFirst()) {
                    int messageId = cursor.getInt(0);

                    Uri updateUri = ContentUris.withAppendedId(UPDATE_STATUS_URI, messageId);

                    if(D) Log.d(TAG, "actionMessageDelivery: uri=" + messageUri + ", status="
                            + msgInfo.statusDelivered);

                    ContentValues contentValues = new ContentValues(2);

                    contentValues.put(Sms.STATUS, msgInfo.statusDelivered);
                    contentValues.put(Inbox.DATE_SENT, System.currentTimeMillis());
                    mResolver.update(updateUri, contentValues, null, null);
                } else {
                    Log.d(TAG, "Can't find message for status update: " + messageUri);
                }
            } finally {
                if (cursor != null) cursor.close();
            }

            if (msgInfo.statusDelivered == 0) {
                Event evt = new Event(EVENT_TYPE_DELEVERY_SUCCESS, msgInfo.id,
                        getSmsFolderName(Sms.MESSAGE_TYPE_SENT), null, mSmsType);
                sendEvent(evt);
            } else {
                Event evt = new Event(EVENT_TYPE_DELIVERY_FAILURE, msgInfo.id,
                        getSmsFolderName(Sms.MESSAGE_TYPE_SENT), null, mSmsType);
                sendEvent(evt);
            }

            mPushMsgList.remove(msgInfo.id);
        }
    }

    /**
     * Handle MMS sent intents in disconnected(MNS) state, where we do not need to send any
     * notifications.
     * @param context The context to use for provider operations
     * @param intent The intent received
     * @param result The result
     */
    static public void actionMmsSent(Context context, Intent intent, int result,
            Map<Long, Msg> mmsMsgList) {
        /*
         * if transparent:
         *   delete message and send notification(regardless of result)
         * else
         *   Result == Success:
         *     move to sent folder (will trigger notification)
         *   Result == Fail:
         *     move to outbox (send delivery fail notification)
         */
        if(D) Log.d(TAG,"actionMmsSent()");
        int transparent = intent.getIntExtra(EXTRA_MESSAGE_SENT_TRANSPARENT, 0);
        long handle = intent.getLongExtra(EXTRA_MESSAGE_SENT_HANDLE, -1);
        if(handle < 0) {
            Log.w(TAG, "Intent received for an invalid handle");
            return;
        }
        ContentResolver resolver = context.getContentResolver();
        if(transparent == 1) {
            /* The specification is a bit unclear about the transparent flag. If it is set
             * no copy of the message shall be kept in the send folder after the message
             * was send, but in the case of a send error, it is unclear what to do.
             * As it will not be transparent if we keep the message in any folder,
             * we delete the message regardless of the result.
             * If we however do have a MNS connection we need to send a notification. */
            Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI, handle);
            /* Delete from observer message list to avoid delete notifications */
            if(mmsMsgList != null) {
                synchronized(mmsMsgList) {
                    mmsMsgList.remove(handle);
                }
            }
            /* Delete message */
            if(D) Log.d(TAG,"Transparent in use - delete");
            resolver.delete(uri, null, null);
        } else if (result == Activity.RESULT_OK) {
            /* This will trigger a notification */
            moveMmsToFolder(handle, resolver, Mms.MESSAGE_BOX_SENT);
        } else {
            if(mmsMsgList != null) {
                synchronized(mmsMsgList) {
                    Msg msg = mmsMsgList.get(handle);
                    if(msg != null) {
                    msg.type=Mms.MESSAGE_BOX_OUTBOX;
                    }
                }
            }
            /* Hand further retries over to the MMS application */
            moveMmsToFolder(handle, resolver, Mms.MESSAGE_BOX_OUTBOX);
        }
    }

    static public void actionMessageSentDisconnected(Context context, Intent intent, int result) {
        TYPE type = TYPE.fromOrdinal(
        intent.getIntExtra(EXTRA_MESSAGE_SENT_MSG_TYPE, TYPE.NONE.ordinal()));
        if(type == TYPE.MMS) {
            actionMmsSent(context, intent, result, null);
        } else {
            actionSmsSentDisconnected(context, intent, result);
        }
    }

    static public void actionSmsSentDisconnected(Context context, Intent intent, int result) {
        /* Check permission for message deletion. */
        if ((Binder.getCallingPid() != Process.myPid()) ||
            (context.checkCallingOrSelfPermission("android.Manifest.permission.WRITE_SMS")
                    != PackageManager.PERMISSION_GRANTED)) {
            Log.w(TAG, "actionSmsSentDisconnected: Not allowed to delete SMS/MMS messages");
            EventLog.writeEvent(0x534e4554, "b/22343270", Binder.getCallingUid(), "");
            return;
        }

        boolean delete = false;
        //int retry = intent.getIntExtra(EXTRA_MESSAGE_SENT_RETRY, 0);
        int transparent = intent.getIntExtra(EXTRA_MESSAGE_SENT_TRANSPARENT, 0);
        String uriString = intent.getStringExtra(EXTRA_MESSAGE_SENT_URI);
        if(uriString == null) {
            // Nothing we can do about it, just bail out
            return;
        }
        Uri uri = Uri.parse(uriString);

        if (result == Activity.RESULT_OK) {
            Log.d(TAG, "actionMessageSentDisconnected: result OK");
            if (transparent == 0) {
                if (!Sms.moveMessageToFolder(context, uri,
                        Sms.MESSAGE_TYPE_SENT, 0)) {
                    Log.d(TAG, "Failed to move " + uri + " to SENT");
                }
            } else {
                delete = true;
            }
        } else {
            /*if (retry == 1) {
                 The retry feature only works while connected, else we fail the send,
             * and move the message to failed, to let the user/app resend manually later.
            } else */{
                if (transparent == 0) {
                    if (!Sms.moveMessageToFolder(context, uri,
                            Sms.MESSAGE_TYPE_FAILED, 0)) {
                        Log.d(TAG, "Failed to move " + uri + " to FAILED");
                    }
                } else {
                    delete = true;
                }
            }
        }

        if (delete) {
            /* Delete from DB */
            ContentResolver resolver = context.getContentResolver();
            if (resolver != null) {
                resolver.delete(uri, null, null);
            } else {
                Log.w(TAG, "Unable to get resolver");
            }
        }
    }

    private void registerPhoneServiceStateListener() {
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
        tm.listen(mPhoneListener, PhoneStateListener.LISTEN_SERVICE_STATE);
    }

    private void unRegisterPhoneServiceStateListener() {
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
        tm.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);
    }

    private void resendPendingMessages() {
        /* Send pending messages in outbox */
        String where = "type = " + Sms.MESSAGE_TYPE_OUTBOX;
        Cursor c = mResolver.query(Sms.CONTENT_URI, SMS_PROJECTION, where, null,
                null);
        try {
            if (c != null && c.moveToFirst()) {
                do {
                    long id = c.getLong(c.getColumnIndex(Sms._ID));
                    String msgBody = c.getString(c.getColumnIndex(Sms.BODY));
                    PushMsgInfo msgInfo = mPushMsgList.get(id);
                    if (msgInfo == null || msgInfo.resend == false ||
                            msgInfo.sendInProgress == true) {
                        continue;
                    }
                    msgInfo.sendInProgress = true;
                    sendMessage(msgInfo, msgBody);
                } while (c.moveToNext());
            }
        } finally {
            if (c != null) c.close();
        }


    }

    private void failPendingMessages() {
        /* Move pending messages from outbox to failed */
        String where = "type = " + Sms.MESSAGE_TYPE_OUTBOX;
        Cursor c = mResolver.query(Sms.CONTENT_URI, SMS_PROJECTION, where, null,
                null);
        try {
            if (c != null && c.moveToFirst()) {
                do {
                    long id = c.getLong(c.getColumnIndex(Sms._ID));
                    String msgBody = c.getString(c.getColumnIndex(Sms.BODY));
                    PushMsgInfo msgInfo = mPushMsgList.get(id);
                    if (msgInfo == null || msgInfo.resend == false) {
                        continue;
                    }
                    Sms.moveMessageToFolder(mContext, msgInfo.uri,
                            Sms.MESSAGE_TYPE_FAILED, 0);
                } while (c.moveToNext());
            }
        } finally {
            if (c != null) c.close();
        }

    }

    private void removeDeletedMessages() {
        /* Remove messages from virtual "deleted" folder (thread_id -1) */
        mResolver.delete(Sms.CONTENT_URI,
                "thread_id = " + DELETED_THREAD_ID, null);
    }

    private PhoneStateListener mPhoneListener = new PhoneStateListener() {
        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            Log.d(TAG, "Phone service state change: " + serviceState.getState());
            if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
                resendPendingMessages();
            }
        }
    };

    public void init() {
        mSmsBroadcastReceiver.register();
        registerPhoneServiceStateListener();
        mInitialized = true;
    }

    public void deinit() {
        mInitialized = false;
        unregisterObserver();
        mSmsBroadcastReceiver.unregister();
        unRegisterPhoneServiceStateListener();
        failPendingMessages();
        removeDeletedMessages();
    }

    public boolean handleSmsSendIntent(Context context, Intent intent){
        TYPE type = TYPE.fromOrdinal(
            intent.getIntExtra(EXTRA_MESSAGE_SENT_MSG_TYPE, TYPE.NONE.ordinal()));
        if(type == TYPE.MMS) {
            return handleMmsSendIntent(context, intent);
        } else {
            if(mInitialized) {
                mSmsBroadcastReceiver.onReceive(context, intent);
                return true;
            }
        }
        return false;
    }

    public boolean handleMmsSendIntent(Context context, Intent intent){
        if(D) Log.w(TAG, "handleMmsSendIntent()");
        if(mMnsClient.isConnected() == false) {
            // No need to handle notifications, just use default handling
            if(D) Log.w(TAG, "MNS not connected - use static handling");
            return false;
        }
        long handle = intent.getLongExtra(EXTRA_MESSAGE_SENT_HANDLE, -1);
        int result = intent.getIntExtra(EXTRA_MESSAGE_SENT_RESULT, Activity.RESULT_CANCELED);
        actionMmsSent(context, intent, result, getMsgListMms());
        if(handle < 0) {
            Log.w(TAG, "Intent received for an invalid handle");
            return true;
        }
        if(result != Activity.RESULT_OK) {
            if(mObserverRegistered) {
                Event evt = new Event(EVENT_TYPE_SENDING_FAILURE, handle,
                        getMmsFolderName(Mms.MESSAGE_BOX_OUTBOX), null, TYPE.MMS);
                sendEvent(evt);
            }
        } else {
            int transparent = intent.getIntExtra(EXTRA_MESSAGE_SENT_TRANSPARENT, 0);
            if(transparent != 0) {
                if(mObserverRegistered) {
                    Event evt = new Event(EVENT_TYPE_SENDING_SUCCESS, handle,
                            getMmsFolderName(Mms.MESSAGE_BOX_OUTBOX), null, TYPE.MMS);
                    sendEvent(evt);
                }
            }
        }
        return true;
    }

}