File: gmMeasurementWidgets.py

package info (click to toggle)
gnumed-client 1.8.5%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 37,672 kB
  • sloc: python: 126,459; javascript: 6,113; sh: 1,192; xml: 36; makefile: 33
file content (4883 lines) | stat: -rw-r--r-- 160,344 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
"""GNUmed measurement widgets."""
#================================================================
__author__ = "Karsten Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL"


import sys
import logging
import datetime as pyDT
import decimal
import os
import subprocess
import io
import os.path


import wx
import wx.grid
import wx.adv as wxh


if __name__ == '__main__':
	sys.path.insert(0, '../../')
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmNetworkTools
from Gnumed.pycommon import gmI18N
from Gnumed.pycommon import gmShellAPI
from Gnumed.pycommon import gmCfg
from Gnumed.pycommon import gmDateTime
from Gnumed.pycommon import gmMatchProvider
from Gnumed.pycommon import gmDispatcher
from Gnumed.pycommon import gmMimeLib

from Gnumed.business import gmPerson
from Gnumed.business import gmStaff
from Gnumed.business import gmPathLab
from Gnumed.business import gmPraxis
from Gnumed.business import gmLOINC
from Gnumed.business import gmForms
from Gnumed.business import gmPersonSearch
from Gnumed.business import gmOrganization
from Gnumed.business import gmHL7
from Gnumed.business import gmIncomingData
from Gnumed.business import gmDocuments

from Gnumed.wxpython import gmRegetMixin
from Gnumed.wxpython import gmPlugin
from Gnumed.wxpython import gmEditArea
from Gnumed.wxpython import gmPhraseWheel
from Gnumed.wxpython import gmListWidgets
from Gnumed.wxpython import gmGuiHelpers
from Gnumed.wxpython import gmAuthWidgets
from Gnumed.wxpython import gmOrganizationWidgets
from Gnumed.wxpython import gmEMRStructWidgets
from Gnumed.wxpython import gmCfgWidgets
from Gnumed.wxpython import gmDocumentWidgets


_log = logging.getLogger('gm.ui')

#================================================================
# HL7 related widgets
#================================================================
def show_hl7_file(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	# select file
	paths = gmTools.gmPaths()
	dlg = wx.FileDialog (
		parent = parent,
		message = _('Show HL7 file:'),
		# make configurable:
		defaultDir = os.path.join(paths.home_dir, 'gnumed'),
		wildcard = "hl7 files|*.hl7|HL7 files|*.HL7|all files|*",
		style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
	)
	choice = dlg.ShowModal()
	hl7_name = dlg.GetPath()
	dlg.DestroyLater()
	if choice != wx.ID_OK:
		return False

	formatted_name = gmHL7.format_hl7_file (
		hl7_name,
		skip_empty_fields = True,
		return_filename = True,
		fix_hl7 = True
	)
	gmMimeLib.call_viewer_on_file(aFile = formatted_name, block = False)
	return True

#================================================================
def unwrap_HL7_from_XML(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	# select file
	paths = gmTools.gmPaths()
	dlg = wx.FileDialog (
		parent = parent,
		message = _('Extract HL7 from XML file:'),
		# make configurable:
		defaultDir = os.path.join(paths.home_dir, 'gnumed'),
		wildcard = "xml files|*.xml|XML files|*.XML|all files|*",
		style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
	)
	choice = dlg.ShowModal()
	xml_name = dlg.GetPath()
	dlg.DestroyLater()
	if choice != wx.ID_OK:
		return False

	target_dir = os.path.split(xml_name)[0]
	xml_path = './/Message'
	hl7_name = gmHL7.extract_HL7_from_XML_CDATA(xml_name, xml_path, target_dir = target_dir)
	if hl7_name is None:
		gmGuiHelpers.gm_show_error (
			title = _('Extracting HL7 from XML file'),
			error = (
			'Cannot unwrap HL7 data from XML file\n'
			'\n'
			' [%s]\n'
			'\n'
			'(CDATA of [%s] nodes)'
			) % (
				xml_name,
				xml_path
			)
		)
		return False

	gmDispatcher.send(signal = 'statustext', msg = _('Unwrapped HL7 into [%s] from [%s].') % (hl7_name, xml_name), beep = False)
	return True

#================================================================
def stage_hl7_file(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	paths = gmTools.gmPaths()
	dlg = wx.FileDialog (
		parent = parent,
		message = _('Select HL7 file for staging:'),
		# make configurable:
		defaultDir = os.path.join(paths.home_dir, 'gnumed'),
		wildcard = ".hl7 files|*.hl7|.HL7 files|*.HL7|all files|*",
		style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
	)
	choice = dlg.ShowModal()
	hl7_name = dlg.GetPath()
	dlg.DestroyLater()
	if choice != wx.ID_OK:
		return False

	target_dir = os.path.join(paths.home_dir, '.gnumed', 'hl7')
	success, PID_names = gmHL7.split_hl7_file(hl7_name, target_dir = target_dir, encoding = 'utf8')
	if not success:
		gmGuiHelpers.gm_show_error (
			title = _('Staging HL7 file'),
			error = _(
				'There was a problem with splitting the HL7 file\n'
				'\n'
				' %s'
			) % hl7_name
		)
		return False

	failed_files = []
	for PID_name in PID_names:
		if not gmHL7.stage_single_PID_hl7_file(PID_name, source = _('generic'), encoding = 'utf8'):
			failed_files.append(PID_name)
	if len(failed_files) > 0:
		gmGuiHelpers.gm_show_error (
			title = _('Staging HL7 file'),
			error = _(
				'There was a problem with staging the following files\n'
				'\n'
				' %s'
			) % '\n '.join(failed_files)
		)
		return False

	gmDispatcher.send(signal = 'statustext', msg = _('Staged HL7 from [%s].') % hl7_name, beep = False)
	return True

#================================================================
def browse_incoming_unmatched(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()
	#------------------------------------------------------------
	def show_hl7(staged_item):
		if staged_item is None:
			return False
		if 'HL7' not in staged_item['data_type']:
			return False
		filename = staged_item.save_to_file()
		if filename is None:
			filename = gmTools.get_unique_filename()
		tmp_file = io.open(filename, mode = 'at', encoding = 'utf8')
		tmp_file.write('\n')
		tmp_file.write('-' * 80)
		tmp_file.write('\n')
		tmp_file.write(gmTools.coalesce(staged_item['comment'], ''))
		tmp_file.close()
		gmMimeLib.call_viewer_on_file(aFile = filename, block = False)
		return False
	#------------------------------------------------------------
	def import_hl7(staged_item):
		if staged_item is None:
			return False
		if 'HL7' not in staged_item['data_type']:
			return False
		unset_identity_on_error = False
		if staged_item['pk_identity_disambiguated'] is None:
			pat = gmPerson.gmCurrentPatient()
			if pat.connected:
				answer = gmGuiHelpers.gm_show_question (
					title = _('Importing HL7 data'),
					question = _(
						'There has not been a patient explicitely associated\n'
						'with this chunk of HL7 data. However, the data file\n'
						'contains the following patient identification information:\n'
						'\n'
						' %s\n'
						'\n'
						'Do you want to import the HL7 under the current patient ?\n'
						'\n'
						' %s\n'
						'\n'
						'Selecting [NO] makes GNUmed try to find a patient matching the HL7 data.\n'
					) % (
						staged_item.patient_identification,
						pat['description_gender']
					),
					cancel_button = True
				)
				if answer is None:
					return False
				if answer is True:
					unset_identity_on_error = True
					staged_item['pk_identity_disambiguated'] = pat.ID

		success, log_name = gmHL7.process_staged_single_PID_hl7_file(staged_item)
		if success:
			return True

		if unset_identity_on_error:
			staged_item['pk_identity_disambiguated'] = None
			staged_item.save()

		gmGuiHelpers.gm_show_error (
			error = _('Error processing HL7 data.'),
			title = _('Processing staged HL7 data.')
		)
		return False

	#------------------------------------------------------------
	def delete(staged_item):
		if staged_item is None:
			return False
		do_delete = gmGuiHelpers.gm_show_question (
			title = _('Deleting incoming data'),
			question = _(
				'Do you really want to delete the incoming data ?\n'
				'\n'
				'Note that deletion is not reversible.'
			)
		)
		if not do_delete:
			return False
		return gmIncomingData.delete_incoming_data(pk_incoming_data = staged_item['pk_incoming_data_unmatched'])
	#------------------------------------------------------------
	def refresh(lctrl):
		incoming = gmIncomingData.get_incoming_data()
		items = [ [
			gmTools.coalesce(i['data_type'], ''),
			'%s, %s (%s) %s' % (
				gmTools.coalesce(i['lastnames'], ''),
				gmTools.coalesce(i['firstnames'], ''),
				gmDateTime.pydt_strftime(dt = i['dob'], format = '%Y %b %d', accuracy = gmDateTime.acc_days, none_str = _('unknown DOB')),
				gmTools.coalesce(i['gender'], '')
			),
			gmTools.coalesce(i['external_data_id'], ''),
			i['pk_incoming_data_unmatched']
		] for i in incoming ]
		lctrl.set_string_items(items)
		lctrl.set_data(incoming)
	#------------------------------------------------------------
	gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = None,
		caption = _('Showing unmatched incoming data'),
		columns = [ _('Type'), _('Identification'), _('Reference'), '#' ],
		single_selection = True,
		can_return_empty = False,
		ignore_OK_button = True,
		refresh_callback = refresh,
#		edit_callback=None,
#		new_callback=None,
		delete_callback = delete,
		left_extra_button = [_('Show'), _('Show formatted HL7'), show_hl7],
		middle_extra_button = [_('Import'), _('Import HL7 data into patient chart'), import_hl7]
#		right_extra_button=None
	)

#================================================================
# convenience functions
#================================================================
def call_browser_on_measurement_type(measurement_type=None):

	dbcfg = gmCfg.cCfgSQL()

	url = dbcfg.get2 (
		option = 'external.urls.measurements_search',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'user',
		default = gmPathLab.URL_test_result_information_search
	)

	base_url = dbcfg.get2 (
		option = 'external.urls.measurements_encyclopedia',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'user',
		default = gmPathLab.URL_test_result_information
	)

	if measurement_type is None:
		url = base_url

	measurement_type = measurement_type.strip()

	if measurement_type == '':
		url = base_url

	url = url % {'search_term': measurement_type}

	gmNetworkTools.open_url_in_browser(url = url)

#----------------------------------------------------------------
def edit_measurement(parent=None, measurement=None, single_entry=False, presets=None):
	ea = cMeasurementEditAreaPnl(parent, -1)
	ea.data = measurement
	ea.mode = gmTools.coalesce(measurement, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2(parent, -1, edit_area = ea, single_entry = single_entry)
	dlg.SetTitle(gmTools.coalesce(measurement, _('Adding new measurement'), _('Editing measurement')))
	if presets is not None:
		ea.set_fields(presets)
	if dlg.ShowModal() == wx.ID_OK:
		dlg.DestroyLater()
		return True

	dlg.DestroyLater()
	return False

#----------------------------------------------------------------
def manage_measurements(parent=None, single_selection=False, emr=None, measurements2manage=None, message=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	if emr is None:
		if measurements2manage is None:
			emr = gmPerson.gmCurrentPatient().emr

	#------------------------------------------------------------
	def edit(measurement=None):
		return edit_measurement(parent = parent, measurement = measurement, single_entry = True)

	#------------------------------------------------------------
	def delete(measurement):
		gmPathLab.delete_test_result(result = measurement)
		return True

	#------------------------------------------------------------
	def do_review(lctrl):
		data = lctrl.get_selected_item_data()
		if len(data) == 0:
			return

		return review_tests(parent = parent, tests = data)

	#------------------------------------------------------------
	def do_plot(lctrl):
		data = lctrl.get_selected_item_data()
		if len(data) == 0:
			return

		return plot_measurements(parent = parent, tests = data)

	#------------------------------------------------------------
	def get_tooltip(measurement):
		return measurement.format(with_review=True, with_evaluation=True, with_ranges=True)

	#------------------------------------------------------------
	def refresh(lctrl):
		if measurements2manage is None:
			results = emr.get_test_results(order_by = 'clin_when DESC, unified_abbrev, unified_name')
		else:
			results = measurements2manage
		items = [ [
			gmDateTime.pydt_strftime (
				r['clin_when'],
				'%Y %b %d %H:%M',
				accuracy = gmDateTime.acc_minutes
			),
			r['unified_abbrev'],
			'%s%s%s%s' % (
				gmTools.bool2subst (
					boolean = (not r['reviewed'] or (not r['review_by_you'] and r['you_are_responsible'])),
					true_return = 'u' + gmTools.u_writing_hand,
					false_return = ''
				),
				r['unified_val'],
				gmTools.coalesce(r['val_unit'], '', ' %s'),
				gmTools.coalesce(r['abnormality_indicator'], '', ' %s')
			),
			r['unified_name'],
			gmTools.coalesce(r['comment'], ''),
			r['pk_test_result']
		] for r in results ]
		lctrl.set_string_items(items)
		lctrl.set_data(results)

	#------------------------------------------------------------
	return gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = message,
		caption = _('Showing test results.'),
		columns = [ _('When'), _('Abbrev'), _('Value'), _('Name'), _('Comment'), '#' ],
		single_selection = single_selection,
		can_return_empty = False,
		refresh_callback = refresh,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete,
		list_tooltip_callback = get_tooltip,
		left_extra_button = (_('Review'), _('Review current selection'), do_review, True),
		middle_extra_button = (_('Plot'), _('Plot current selection'), do_plot, True)
	)

#================================================================
def configure_default_top_lab_panel(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	panels = gmPathLab.get_test_panels(order_by = 'description')
	gmCfgWidgets.configure_string_from_list_option (
		parent = parent,
		message = _('Select the measurements panel to show in the top pane for continuous monitoring.'),
		option = 'horstspace.top_panel.lab_panel',
		bias = 'user',
		default_value = None,
		choices = [ '%s%s' % (p['description'], gmTools.coalesce(p['comment'], '', ' (%s)')) for p in panels ],
		columns = [_('Lab panel')],
		data = [ p['pk_test_panel'] for p in panels ],
		caption = _('Configuring continuous monitoring measurements panel')
	)

#================================================================
def configure_default_gnuplot_template(parent=None):

	from Gnumed.wxpython import gmFormWidgets

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	template = gmFormWidgets.manage_form_templates (
		parent = parent,
		active_only = True,
		template_types = ['gnuplot script']
	)

	option = 'form_templates.default_gnuplot_template'

	if template is None:
		gmDispatcher.send(signal = 'statustext', msg = _('No default Gnuplot script template selected.'), beep = True)
		return None

	if template['engine'] != 'G':
		gmDispatcher.send(signal = 'statustext', msg = _('No default Gnuplot script template selected.'), beep = True)
		return None

	dbcfg = gmCfg.cCfgSQL()
	dbcfg.set (
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		option = option,
		value = '%s - %s' % (template['name_long'], template['external_version'])
	)
	return template

#============================================================
def get_default_gnuplot_template(parent = None):

	option = 'form_templates.default_gnuplot_template'

	dbcfg = gmCfg.cCfgSQL()

	# load from option
	default_template_name = dbcfg.get2 (
		option = option,
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'user'
	)

	# not configured -> try to configure
	if default_template_name is None:
		gmDispatcher.send('statustext', msg = _('No default Gnuplot template configured.'), beep = False)
		default_template = configure_default_gnuplot_template(parent = parent)
		# still not configured -> return
		if default_template is None:
			gmGuiHelpers.gm_show_error (
				aMessage = _('There is no default Gnuplot one-type script template configured.'),
				aTitle = _('Plotting test results')
			)
			return None
		return default_template

	# now it MUST be configured (either newly or previously)
	# but also *validly* ?
	try:
		name, ver = default_template_name.split(' - ')
	except Exception:
		# not valid
		_log.exception('problem splitting Gnuplot script template name [%s]', default_template_name)
		gmDispatcher.send(signal = 'statustext', msg = _('Problem loading Gnuplot script template.'), beep = True)
		return None

	default_template = gmForms.get_form_template(name_long = name, external_version = ver)
	if default_template is None:
		default_template = configure_default_gnuplot_template(parent = parent)
		# still not configured -> return
		if default_template is None:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Cannot load default Gnuplot script template [%s - %s]') % (name, ver),
				aTitle = _('Plotting test results')
			)
			return None

	return default_template

#----------------------------------------------------------------
def plot_measurements(parent=None, tests=None, format=None, show_year = True, use_default_template=False):

	from Gnumed.wxpython import gmFormWidgets

	# only valid for one-type plotting
	if use_default_template:
		template = get_default_gnuplot_template()
	else:
		template = gmFormWidgets.manage_form_templates (
			parent = parent,
			active_only = True,
			template_types = ['gnuplot script']
		)
	if template is None:
		gmGuiHelpers.gm_show_error (
			aMessage = _('Cannot plot without a plot script.'),
			aTitle = _('Plotting test results')
		)
		return False

	pat = gmPerson.gmCurrentPatient()
	fname_data = gmPathLab.export_results_for_gnuplot(results = tests, show_year = show_year, patient = pat)
	script = template.instantiate(use_sandbox = True)
	script.data_filename = fname_data
	script.generate_output(format = format) 		# Gnuplot output terminal, wxt = wxWidgets window

	fname_png = fname_data + '.png'
	if os.path.exists(fname_png):
		gmMimeLib.call_viewer_on_file(fname_png)
		store_in_export_area = gmGuiHelpers.gm_show_question (
			title = _('Plotted lab results'),
			question = _('Put a copy of the lab results plot into the export area of this patient ?')
		)
		if store_in_export_area:
			pat.export_area.add_file (
				filename = fname_png,
				hint = _('lab results plot')
			)

#----------------------------------------------------------------
def plot_adjacent_measurements(parent=None, test=None, format=None, show_year=True, plot_singular_result=True, use_default_template=False):

	earlier, later = test.get_adjacent_results(desired_earlier_results = 2, desired_later_results = 2)
	results2plot = []
	if earlier is not None:
		results2plot.extend(earlier)
	results2plot.append(test)
	if later is not None:
		results2plot.extend(later)
	if len(results2plot) == 1:
		if not plot_singular_result:
			return
	plot_measurements (
		parent = parent,
		tests = results2plot,
		format = format,
		show_year = show_year,
		use_default_template = use_default_template
	)

#================================================================
#from Gnumed.wxGladeWidgets import wxgPrimaryCareVitalsInputPnl
#
# Taillenumfang: Mitte zwischen unterster Rippe und
# hoechstem Teil des Beckenkamms
# Maenner: maessig: 94-102, deutlich: > 102  .. erhoeht
# Frauen:  maessig: 80-88,  deutlich: > 88   .. erhoeht
#
#================================================================
# display widgets
#================================================================
from Gnumed.wxGladeWidgets import wxgLabRelatedDocumentsPnl

class cLabRelatedDocumentsPnl(wxgLabRelatedDocumentsPnl.wxgLabRelatedDocumentsPnl):
	"""This panel handles documents related to the lab result it is handed.
	"""
	def __init__(self, *args, **kwargs):
		wxgLabRelatedDocumentsPnl.wxgLabRelatedDocumentsPnl.__init__(self, *args, **kwargs)

		self.__reference = None

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self.__repopulate_ui()

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

	#------------------------------------------------------------
	def __repopulate_ui(self):
		self._BTN_list_documents.Disable()
		self._LBL_no_of_docs.SetLabel(_('no related documents'))
		self._LBL_no_of_docs.ContainingSizer.Layout()

		if self.__reference is None:
			self._LBL_no_of_docs.SetToolTip(_('There is no lab reference to find related documents for.'))
			return

		dbcfg = gmCfg.cCfgSQL()
		lab_doc_types = dbcfg.get2 (
			option = 'horstspace.lab_doc_types',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user'
		)
		if lab_doc_types is None:
			self._LBL_no_of_docs.SetToolTip(_('No document types declared to contain lab results.'))
			return

		if len(lab_doc_types) == 0:
			self._LBL_no_of_docs.SetToolTip(_('No document types declared to contain lab results.'))
			return

		pks_doc_types = gmDocuments.map_types2pk(lab_doc_types)
		if len(pks_doc_types) == 0:
			self._LBL_no_of_docs.SetToolTip(_('No valid document types declared to contain lab results.'))
			return

		txt = _('Document types assumed to contain lab results:')
		txt += '\n '
		txt += '\n '.join(lab_doc_types)
		self._LBL_no_of_docs.SetToolTip(txt)
		if isinstance(self.__reference, gmPathLab.cTestResult):
			pk_current_episode = self.__reference['pk_episode']
		else:
			pk_current_episode = self.__reference
		docs = gmDocuments.search_for_documents (
			pk_episode = pk_current_episode,
			pk_types = [ dt['pk_doc_type'] for dt in pks_doc_types ]
		)
		if len(docs) == 0:
			return

		self._LBL_no_of_docs.SetLabel(_('Related documents: %s') % len(docs))
		self._LBL_no_of_docs.ContainingSizer.Layout()
		self._BTN_list_documents.Enable()

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__reference is None:
			return True

		if kwds['table'] not in ['clin.test_result', 'blobs.doc_med']:
			return True

		if isinstance(self.__reference, gmPathLab.cTestResult):
			if kwds['pk_of_row'] != self.__reference['pk_test_result']:
				return True

		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	def _on_select_lab_doc_types_button_pressed(self, event):
		event.Skip()
		doc_types = gmDocuments.get_document_types()
		gmCfgWidgets.configure_list_from_list_option (
			parent = self,
			message = _('Select the document types which are assumed to contain lab results.'),
			option = 'horstspace.lab_doc_types',
			bias = 'user',
			choices = [ dt['l10n_type'] for dt in doc_types ],
			columns = [_('Document types')]#,
			#data = None,
			#caption = None,
			#picks = None
		)
		self.__repopulate_ui()

	#------------------------------------------------------------
	def _on_list_documents_button_pressed(self, event):
		event.Skip()
		dbcfg = gmCfg.cCfgSQL()
		lab_doc_types = dbcfg.get2 (
			option = 'horstspace.lab_doc_types',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user'
		)
		d_types = gmDocuments.map_types2pk(lab_doc_types)
		if isinstance(self.__reference, gmPathLab.cTestResult):
			pk_current_episode = self.__reference['pk_episode']
		else:
			pk_current_episode = self.__reference
		gmDocumentWidgets.manage_documents (
			parent = self,
			msg = _('Documents possibly related to this episode'),
			pk_types = [ dt['pk_doc_type'] for dt in d_types ],
			pk_episodes = [ pk_current_episode ]
		)

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _set_lab_reference(self, value):
		"""Either a test result or an episode PK."""
		if isinstance(self.__reference, gmPathLab.cTestResult):
			pk_old_episode = self.__reference['pk_episode']
		else:
			pk_old_episode = self.__reference
		if isinstance(value, gmPathLab.cTestResult):
			pk_new_episode = value['pk_episode']
		else:
			pk_new_episode = value
		self.__reference = value
		if pk_new_episode != pk_old_episode:
			self.__repopulate_ui()
		return

	lab_reference = property(lambda x:x, _set_lab_reference)

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsAsListPnl

class cMeasurementsAsListPnl(wxgMeasurementsAsListPnl.wxgMeasurementsAsListPnl, gmRegetMixin.cRegetOnPaintMixin):
	"""A class for displaying all measurement results as a simple list.

	- operates on a cPatient instance handed to it and NOT on the currently active patient
	"""
	def __init__(self, *args, **kwargs):
		wxgMeasurementsAsListPnl.wxgMeasurementsAsListPnl.__init__(self, *args, **kwargs)

		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__patient = None

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_results.set_columns([_('When'), _('Test'), _('Result'), _('Reference')])
		self._LCTRL_results.edit_callback = self._on_edit
		self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

	#------------------------------------------------------------
	def __repopulate_ui(self):
		if self.__patient is None:
			self._LCTRL_results.set_string_items([])
			self._TCTRL_measurements.SetValue('')
			self._PNL_related_documents.lab_reference = None
			return

		results = self.__patient.emr.get_test_results(order_by = 'clin_when DESC, unified_abbrev, unified_name')
		items = []
		data = []
		for r in results:
			range_info = gmTools.coalesce (
				r.formatted_clinical_range,
				r.formatted_normal_range
			)
			review = gmTools.bool2subst (
				r['reviewed'],
				'',
				' ' + gmTools.u_writing_hand,
				' ' + gmTools.u_writing_hand
			)
			items.append ([
				gmDateTime.pydt_strftime(r['clin_when'], '%Y %b %d  %H:%M', accuracy = gmDateTime.acc_minutes),
				r['abbrev_tt'],
				'%s%s%s%s' % (
					gmTools.strip_empty_lines(text = r['unified_val'])[0],
					gmTools.coalesce(r['val_unit'], '', ' %s'),
					gmTools.coalesce(r['abnormality_indicator'], '', ' %s'),
					review
				),
				gmTools.coalesce(range_info, '')
			])
			data.append({'data': r, 'formatted': r.format(with_source_data = True)})

		self._LCTRL_results.set_string_items(items)
		self._LCTRL_results.set_column_widths([wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
		self._LCTRL_results.set_data(data)
		if len(items) > 0:
			self._LCTRL_results.Select(idx = 0, on = 1)
			self._TCTRL_measurements.SetValue(self._LCTRL_results.get_item_data(item_idx = 0)['formatted'])

		self._LCTRL_results.SetFocus()

	#------------------------------------------------------------
	def _on_edit(self):
		item_data = self._LCTRL_results.get_selected_item_data(only_one = True)
		if item_data is None:
			return
		if edit_measurement(parent = self, measurement = item_data['data'], single_entry = True):
			self.__repopulate_ui()

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__patient is None:
			return True

		if kwds['pk_identity'] is not None:				# review table doesn't have pk_identity yet
			if kwds['pk_identity'] != self.__patient.ID:
				return True

		if kwds['table'] not in ['clin.test_result', 'clin.reviewed_test_results']:
			return True

		self._schedule_data_reget()
		return True

	#------------------------------------------------------------
	def _on_result_selected(self, event):
		event.Skip()
		item_data = self._LCTRL_results.get_item_data(item_idx = event.Index)
		self._TCTRL_measurements.SetValue(item_data['formatted'])
		self._PNL_related_documents.lab_reference = item_data['data']

	#------------------------------------------------------------
	# reget mixin API
	#------------------------------------------------------------
	def _populate_with_data(self):
		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		if (self.__patient is None) and (patient is None):
			return
		if (self.__patient is None) or (patient is None):
			self.__patient = patient
			self._schedule_data_reget()
			return
		if self.__patient.ID == patient.ID:
			return
		self.__patient = patient
		self._schedule_data_reget()

	patient = property(_get_patient, _set_patient)

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsByDayPnl

class cMeasurementsByDayPnl(wxgMeasurementsByDayPnl.wxgMeasurementsByDayPnl, gmRegetMixin.cRegetOnPaintMixin):
	"""A class for displaying measurement results as a list partitioned by day.

	- operates on a cPatient instance handed to it and NOT on the currently active patient
	"""
	def __init__(self, *args, **kwargs):
		wxgMeasurementsByDayPnl.wxgMeasurementsByDayPnl.__init__(self, *args, **kwargs)

		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__patient = None
		self.__date_format = str('%Y %b %d')

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_days.set_columns([_('Day')])
		self._LCTRL_results.set_columns([_('Time'), _('Test'), _('Result'), _('Reference')])
		self._LCTRL_results.new_callback = self._on_add
		self._LCTRL_results.edit_callback = self._on_edit
		self._LCTRL_results.delete_callback = self._on_delete
		self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

	#------------------------------------------------------------
	def __clear(self):
		self._LCTRL_days.set_string_items()
		self._LCTRL_results.set_string_items()
		self._TCTRL_measurements.SetValue('')
		self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def __repopulate_ui(self):
		if self.__patient is None:
			self.__clear()
			return

		idx_selected_day = self._LCTRL_days.GetFirstSelected()
		if idx_selected_day == -1:
			idx_selected_day = 0
		dates = self.__patient.emr.get_dates_for_results(reverse_chronological = True)
		items = [ ['%s%s' % (
					gmDateTime.pydt_strftime(d['clin_when_day'], self.__date_format),
					gmTools.bool2subst(d['is_reviewed'], '', gmTools.u_writing_hand, gmTools.u_writing_hand)
				)]
			for d in dates
		]
		self._LCTRL_days.set_string_items(items)
		self._LCTRL_days.set_data(dates)
		if len(items) > 0:
			if idx_selected_day > len(items):
				idx_selected_day = 0
			self._LCTRL_days.Select(idx = idx_selected_day, on = 1)
			self._LCTRL_days.SetFocus()

	#------------------------------------------------------------
	def _on_edit(self):
		item_data = self._LCTRL_results.get_selected_item_data(only_one = True)
		if item_data is None:
			return
		if edit_measurement(parent = self, measurement = item_data['data'], single_entry = True):
			self.__repopulate_ui()

	#------------------------------------------------------------
	def _on_add(self):
		result = self._LCTRL_results.get_item_data(item_idx = 0)['data']
		presets = {
			'clin_when': {'data': result['clin_when']},
			'pk_episode': {'data': result['pk_episode']}
		}
		added = edit_measurement(parent = self, measurement = None, single_entry = False, presets = presets)
		if added:
			self.__repopulate_ui()
		self._LCTRL_results.SetFocus()

	#------------------------------------------------------------
	def _on_delete(self):
		item_data = self._LCTRL_results.get_selected_item_data(only_one = True)
		if item_data is None:
			return False

		result = item_data['data']
		delete = gmGuiHelpers.gm_show_question (
			question = _('Really delete test result ?\n\n%s') % result.format(),
			title = _('Deleting test result')
		)
		if not delete:
			return False

		return gmPathLab.delete_test_result(result = result)

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__patient is None:
			return True

		if kwds['pk_identity'] is not None:				# review table doesn't have pk_identity yet
			if kwds['pk_identity'] != self.__patient.ID:
				return True

		if kwds['table'] not in ['clin.test_result', 'clin.reviewed_test_results']:
			return True

		self._schedule_data_reget()
		return True

	#------------------------------------------------------------
	def _on_day_selected(self, event):
		event.Skip()

		day = self._LCTRL_days.get_item_data(item_idx = event.Index)['clin_when_day']
		results = self.__patient.emr.get_results_for_day(timestamp = day)
		items = []
		data = []
		for r in results:
			range_info = gmTools.coalesce (
				r.formatted_clinical_range,
				r.formatted_normal_range
			)
			review = gmTools.bool2subst (
				r['reviewed'],
				'',
				' ' + gmTools.u_writing_hand,
				' ' + gmTools.u_writing_hand
			)
			items.append ([
				gmDateTime.pydt_strftime(r['clin_when'], '%H:%M'),
				r['abbrev_tt'],
				'%s%s%s%s' % (
					gmTools.strip_empty_lines(text = r['unified_val'])[0],
					gmTools.coalesce(r['val_unit'], '', ' %s'),
					gmTools.coalesce(r['abnormality_indicator'], '', ' %s'),
					review
				),
				gmTools.coalesce(range_info, '')
			])
			data.append({'data': r, 'formatted': r.format(with_source_data = True)})

		self._LCTRL_results.set_string_items(items)
		self._LCTRL_results.set_column_label(1, _('Test (%s%s)') % (gmTools.u_sum, len(items)))
		self._LCTRL_results.set_column_widths([wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
		self._LCTRL_results.set_data(data)
		self._LCTRL_results.Select(idx = 0, on = 1)

	#------------------------------------------------------------
	def _on_result_selected(self, event):
		event.Skip()
		item_data = self._LCTRL_results.get_item_data(item_idx = event.Index)
		self._TCTRL_measurements.SetValue(item_data['formatted'])
		self._PNL_related_documents.lab_reference = item_data['data']

	#------------------------------------------------------------
	# reget mixin API
	#------------------------------------------------------------
	def _populate_with_data(self):
		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		if (self.__patient is None) and (patient is None):
			return
		if patient is None:
			self.__patient = None
			self.__clear()
			return
		if self.__patient is None:
			self.__patient = patient
			self._schedule_data_reget()
			return
		if self.__patient.ID == patient.ID:
			return
		self.__patient = patient
		self._schedule_data_reget()

	patient = property(_get_patient, _set_patient)

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsByIssuePnl

class cMeasurementsByIssuePnl(wxgMeasurementsByIssuePnl.wxgMeasurementsByIssuePnl, gmRegetMixin.cRegetOnPaintMixin):
	"""A class for displaying measurement results as a list partitioned by issue/episode.

	- operates on a cPatient instance handed to it and NOT on the currently active patient
	"""
	def __init__(self, *args, **kwargs):
		wxgMeasurementsByIssuePnl.wxgMeasurementsByIssuePnl.__init__(self, *args, **kwargs)

		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__patient = None

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_issues.set_columns([_('Problem')])
		self._LCTRL_results.set_columns([_('When'), _('Test'), _('Result'), _('Reference')])
		self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)
		self._LCTRL_issues.select_callback = self._on_problem_selected
		self._LCTRL_results.edit_callback = self._on_edit
		self._LCTRL_results.select_callback = self._on_result_selected

	#------------------------------------------------------------
	def __clear(self):
		self._LCTRL_issues.set_string_items()
		self._LCTRL_results.set_string_items()
		self._TCTRL_measurements.SetValue('')
		self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def __repopulate_ui(self):
		if self.__patient is None:
			self.__clear()
			return

		probs = self.__patient.emr.get_issues_or_episodes_for_results()
		items = [ ['%s%s' % (
			gmTools.coalesce (
				value2test = p['pk_health_issue'],
				value2return = '',
				return_instead = gmTools.u_diameter + ':'
			),
			gmTools.shorten_words_in_line(text = p['problem'], min_word_length = 5, max_length = 30)
		)] for p in probs ]
		self._LCTRL_issues.set_string_items(items)
		self._LCTRL_issues.set_data([ {'pk_issue': p['pk_health_issue'], 'pk_episode': p['pk_episode']} for p in probs ])
		if len(items) > 0:
			self._LCTRL_issues.Select(idx = 0, on = 1)
			self._LCTRL_issues.SetFocus()

	#------------------------------------------------------------
	def _on_edit(self):
		item_data = self._LCTRL_results.get_selected_item_data(only_one = True)
		if item_data is None:
			return
		if edit_measurement(parent = self, measurement = item_data['data'], single_entry = True):
			self.__repopulate_ui()

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__patient is None:
			return True

		if kwds['pk_identity'] is not None:				# review table doesn't have pk_identity yet
			if kwds['pk_identity'] != self.__patient.ID:
				return True

		if kwds['table'] not in ['clin.test_result', 'clin.reviewed_test_results']:
			return True

		self._schedule_data_reget()
		return True

	#------------------------------------------------------------
	def _on_problem_selected(self, event):
		event.Skip()

		pk_issue = self._LCTRL_issues.get_item_data(item_idx = event.Index)['pk_issue']
		if pk_issue is None:
			pk_episode = self._LCTRL_issues.get_item_data(item_idx = event.Index)['pk_episode']
			results = self.__patient.emr.get_results_for_episode(pk_episode = pk_episode)
		else:
			results = self.__patient.emr.get_results_for_issue(pk_health_issue = pk_issue)
		items = []
		data = []
		for r in results:
			range_info = gmTools.coalesce (
				r.formatted_clinical_range,
				r.formatted_normal_range
			)
			review = gmTools.bool2subst (
				r['reviewed'],
				'',
				' ' + gmTools.u_writing_hand,
				' ' + gmTools.u_writing_hand
			)
			items.append ([
				gmDateTime.pydt_strftime(r['clin_when'], '%Y %b %d  %H:%M'),
				r['abbrev_tt'],
				'%s%s%s%s' % (
					gmTools.strip_empty_lines(text = r['unified_val'])[0],
					gmTools.coalesce(r['val_unit'], '', ' %s'),
					gmTools.coalesce(r['abnormality_indicator'], '', ' %s'),
					review
				),
				gmTools.coalesce(range_info, '')
			])
			data.append({'data': r, 'formatted': r.format(with_source_data = True)})

		self._LCTRL_results.set_string_items(items)
		self._LCTRL_results.set_column_widths([wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
		self._LCTRL_results.set_data(data)
		self._LCTRL_results.Select(idx = 0, on = 1)
		self._TCTRL_measurements.SetValue(self._LCTRL_results.get_item_data(item_idx = 0)['formatted'])

	#------------------------------------------------------------
	def _on_result_selected(self, event):
		event.Skip()
		item_data = self._LCTRL_results.get_item_data(item_idx = event.Index)
		self._TCTRL_measurements.SetValue(item_data['formatted'])
		self._PNL_related_documents.lab_reference = item_data['data']

	#------------------------------------------------------------
	# reget mixin API
	#------------------------------------------------------------
	def _populate_with_data(self):
		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		if (self.__patient is None) and (patient is None):
			return
		if patient is None:
			self.__patient = None
			self.__clear()
			return
		if self.__patient is None:
			self.__patient = patient
			self._schedule_data_reget()
			return
		if self.__patient.ID == patient.ID:
			return
		self.__patient = patient
		self._schedule_data_reget()

	patient = property(_get_patient, _set_patient)

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsByBatteryPnl

class cMeasurementsByBatteryPnl(wxgMeasurementsByBatteryPnl.wxgMeasurementsByBatteryPnl, gmRegetMixin.cRegetOnPaintMixin):
	"""A grid class for displaying measurement results filtered by battery/panel.

	- operates on a cPatient instance handed to it and NOT on the currently active patient
	"""
	def __init__(self, *args, **kwargs):
		wxgMeasurementsByBatteryPnl.wxgMeasurementsByBatteryPnl.__init__(self, *args, **kwargs)

		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__patient = None

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self._GRID_results_battery.show_by_panel = True

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

		self._PRW_panel.add_callback_on_selection(callback = self._on_panel_selected)
		self._PRW_panel.add_callback_on_modified(callback = self._on_panel_selection_modified)

	#------------------------------------------------------------
	def __repopulate_ui(self):
		self._GRID_results_battery.patient = self.__patient
		return True

	#--------------------------------------------------------
	def __on_panel_selected(self, panel):
		if panel is None:
			self._TCTRL_panel_comment.SetValue('')
			self._GRID_results_battery.panel_to_show = None
		else:
			pnl = self._PRW_panel.GetData(as_instance = True)
			self._TCTRL_panel_comment.SetValue(gmTools.coalesce (
				pnl['comment'],
				''
			))
			self._GRID_results_battery.panel_to_show = pnl
#		self.Layout()

	#--------------------------------------------------------
	def __on_panel_selection_modified(self):
		self._TCTRL_panel_comment.SetValue('')
		if self._PRW_panel.GetValue().strip() == '':
			self._GRID_results_battery.panel_to_show = None
#			self.Layout()

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__patient is None:
			return True

		if kwds['pk_identity'] is not None:				# review table doesn't have pk_identity yet
			if kwds['pk_identity'] != self.__patient.ID:
				return True

		if kwds['table'] not in ['clin.test_result', 'clin.reviewed_test_results']:
			return True

		self._schedule_data_reget()
		return True

	#------------------------------------------------------------
	def _on_manage_panels_button_pressed(self, event):
		manage_test_panels(parent = self)

	#--------------------------------------------------------
	def _on_panel_selected(self, panel):
		wx.CallAfter(self.__on_panel_selected, panel=panel)

	#--------------------------------------------------------
	def _on_panel_selection_modified(self):
		wx.CallAfter(self.__on_panel_selection_modified)

	#------------------------------------------------------------
	# reget mixin API
	#------------------------------------------------------------
	def _populate_with_data(self):
		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		if (self.__patient is None) and (patient is None):
			return
		if (self.__patient is None) or (patient is None):
			self.__patient = patient
			self._schedule_data_reget()
			return
		if self.__patient.ID == patient.ID:
			return
		self.__patient = patient
		self._schedule_data_reget()

	patient = property(_get_patient, _set_patient)

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsAsMostRecentListPnl

class cMeasurementsAsMostRecentListPnl(wxgMeasurementsAsMostRecentListPnl.wxgMeasurementsAsMostRecentListPnl, gmRegetMixin.cRegetOnPaintMixin):
	"""A list ctrl class for displaying measurement results.

		- most recent results
		- possibly filtered by battery/panel

	- operates on a cPatient instance handed to it and NOT on the currently active patient
	"""
	def __init__(self, *args, **kwargs):
		wxgMeasurementsAsMostRecentListPnl.wxgMeasurementsAsMostRecentListPnl.__init__(self, *args, **kwargs)

		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__patient = None

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_results.set_columns([_('Test'), _('Result'), _('When'), _('Range')])
		self._CHBOX_show_missing.Disable()
		self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

		self._PRW_panel.add_callback_on_selection(callback = self._on_panel_selected)
		self._PRW_panel.add_callback_on_modified(callback = self._on_panel_selection_modified)

		self._LCTRL_results.select_callback = self._on_result_selected
		self._LCTRL_results.edit_callback = self._on_edit

	#------------------------------------------------------------
	def __repopulate_ui(self):

		self._TCTRL_details.SetValue('')
		self._PNL_related_documents.lab_reference = None
		if self.__patient is None:
			self._LCTRL_results.remove_items_safely()
			return

		pnl = self._PRW_panel.GetData(as_instance = True)
		if pnl is None:
			results = gmPathLab.get_most_recent_result_for_test_types (
				pk_patient = self.__patient.ID,
				consider_meta_type = True
			)
		else:
			results = pnl.get_most_recent_results (
				pk_patient = self.__patient.ID,
				#order_by = ,
				group_by_meta_type = True,
				include_missing = self._CHBOX_show_missing.IsChecked()
			)
		items = []
		data = []
		for r in results:
			if isinstance(r, gmPathLab.cTestResult):
				result_type = gmTools.coalesce (
					value2test = r['pk_meta_test_type'],
					return_instead = r['abbrev_tt'],
					value2return = '%s%s' % (gmTools.u_sum, r['abbrev_meta'])
				)
				review = gmTools.bool2subst (
					r['reviewed'],
					'',
					' ' + gmTools.u_writing_hand,
					' ' + gmTools.u_writing_hand
				)
				result_val = '%s%s%s%s' % (
					gmTools.strip_empty_lines(text = r['unified_val'])[0],
					gmTools.coalesce(r['val_unit'], '', ' %s'),
					gmTools.coalesce(r['abnormality_indicator'], '', ' %s'),
					review
				)
				result_when = _('%s ago (%s)') % (
					gmDateTime.format_interval_medically(interval = gmDateTime.pydt_now_here() - r['clin_when']),
					gmDateTime.pydt_strftime(r['clin_when'], '%Y %b %d  %H:%M', accuracy = gmDateTime.acc_minutes)
				)
				range_info = gmTools.coalesce (
					r.formatted_clinical_range,
					r.formatted_normal_range
				)
				tt = r.format(with_source_data = True)
			else:
				result_type = r
				result_val = _('missing')
				loinc_data = gmLOINC.loinc2data(r)
				if loinc_data is None:
					result_when = _('LOINC not found')
					tt = u''
				else:
					result_when = loinc_data['term']
					tt = gmLOINC.format_loinc(r)
				range_info = None
			items.append([result_type, result_val, result_when, gmTools.coalesce(range_info, '')])
			data.append({'data': r, 'formatted': tt})

		self._LCTRL_results.set_string_items(items)
		self._LCTRL_results.set_column_widths([wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
		self._LCTRL_results.set_data(data)

		if len(items) > 0:
			self._LCTRL_results.Select(idx = 0, on = 1)
		self._LCTRL_results.SetFocus()

		return True

	#--------------------------------------------------------
	def __on_panel_selected(self, panel):
		if panel is None:
			self._TCTRL_panel_comment.SetValue('')
			self._CHBOX_show_missing.Disable()
		else:
			pnl = self._PRW_panel.GetData(as_instance = True)
			self._TCTRL_panel_comment.SetValue(gmTools.coalesce(pnl['comment'], ''))
		self.__repopulate_ui()
		self._CHBOX_show_missing.Enable()

	#--------------------------------------------------------
	def __on_panel_selection_modified(self):
		self._TCTRL_panel_comment.SetValue('')
		if self._PRW_panel.Value.strip() == u'':
			self.__repopulate_ui()
			self._CHBOX_show_missing.Disable()

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__patient is None:
			return True

		if kwds['pk_identity'] is not None:				# review table doesn't have pk_identity yet
			if kwds['pk_identity'] != self.__patient.ID:
				return True

		if kwds['table'] not in ['clin.test_result', 'clin.reviewed_test_results', 'clin.test_panel']:
			return True

		self._schedule_data_reget()
		return True

	#------------------------------------------------------------
	def _on_manage_panels_button_pressed(self, event):
		manage_test_panels(parent = self)

	#--------------------------------------------------------
	def _on_panel_selected(self, panel):
		wx.CallAfter(self.__on_panel_selected, panel = panel)

	#--------------------------------------------------------
	def _on_panel_selection_modified(self):
		wx.CallAfter(self.__on_panel_selection_modified)

	#------------------------------------------------------------
	def _on_result_selected(self, event):
		event.Skip()
		item_data = self._LCTRL_results.get_item_data(item_idx = event.Index)
		self._TCTRL_details.SetValue(item_data['formatted'])
		if isinstance(item_data['data'], gmPathLab.cTestResult):
			self._PNL_related_documents.lab_reference = item_data['data']
		else:
			self._PNL_related_documents.lab_reference = None

	#------------------------------------------------------------
	def _on_edit(self):
		item_data = self._LCTRL_results.get_selected_item_data(only_one = True)
		if item_data is None:
			return
		if isinstance(item_data['data'], gmPathLab.cTestResult):
			if edit_measurement(parent = self, measurement = item_data['data'], single_entry = True):
				self.__repopulate_ui()

	#------------------------------------------------------------
	def _on_show_missing_toggled(self, event):
		event.Skip()
		# should not happen
		if self._PRW_panel.GetData(as_instance = False) is None:
			return
		self.__repopulate_ui()

	#------------------------------------------------------------
	# reget mixin API
	#------------------------------------------------------------
	def _populate_with_data(self):
		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		if (self.__patient is None) and (patient is None):
			return
		if (self.__patient is None) or (patient is None):
			self.__patient = patient
			self._schedule_data_reget()
			return
		if self.__patient.ID == patient.ID:
			return
		self.__patient = patient
		self._schedule_data_reget()

	patient = property(_get_patient, _set_patient)

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsAsTablePnl

class cMeasurementsAsTablePnl(wxgMeasurementsAsTablePnl.wxgMeasurementsAsTablePnl, gmRegetMixin.cRegetOnPaintMixin):
	"""A panel for holding a grid displaying all measurement results.

	- operates on a cPatient instance handed to it and NOT on the currently active patient
	"""
	def __init__(self, *args, **kwargs):
		wxgMeasurementsAsTablePnl.wxgMeasurementsAsTablePnl.__init__(self, *args, **kwargs)

		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__patient = None

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		self.__action_button_popup = wx.Menu(title = _('Perform on selected results:'))

		item = self.__action_button_popup.Append(-1, _('Review and &sign'))
		self.Bind(wx.EVT_MENU, self.__on_sign_current_selection, item)

		item = self.__action_button_popup.Append(-1, _('Plot'))
		self.Bind(wx.EVT_MENU, self.__on_plot_current_selection, item)

		#item = self.__action_button_popup.Append(-1, _('Export to &file'))
		#self.Bind(wx.EVT_MENU, self._GRID_results_all.current_selection_to_file, item)
		#self.__action_button_popup.Enable(id = item.Id, enable = False)

		#item = self.__action_button_popup.Append(-1, _('Export to &clipboard'))
		#self.Bind(wx.EVT_MENU, self._GRID_results_all.current_selection_to_clipboard, item)
		#self.__action_button_popup.Enable(id = item.Id, enable = False)

		item = self.__action_button_popup.Append(-1, _('&Delete'))
		self.Bind(wx.EVT_MENU, self.__on_delete_current_selection, item)

		# FIXME: create inbox message to staff to phone patient to come in
		# FIXME: generate and let edit a SOAP narrative and include the values

		self._GRID_results_all.show_by_panel = False

	#------------------------------------------------------------
	def __register_events(self):
		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

	#------------------------------------------------------------
	def __repopulate_ui(self):
		self._GRID_results_all.patient = self.__patient
		#self._GRID_results_battery.Fit()
		self.Layout()
		return True

	#------------------------------------------------------------
	def __on_sign_current_selection(self, evt):
		self._GRID_results_all.sign_current_selection()

	#------------------------------------------------------------
	def __on_plot_current_selection(self, evt):
		self._GRID_results_all.plot_current_selection()

	#------------------------------------------------------------
	def __on_delete_current_selection(self, evt):
		self._GRID_results_all.delete_current_selection()

	#------------------------------------------------------------
	# event handlers
	#------------------------------------------------------------
	def _on_database_signal(self, **kwds):
		if self.__patient is None:
			return True

		if kwds['pk_identity'] is not None:				# review table doesn't have pk_identity yet
			if kwds['pk_identity'] != self.__patient.ID:
				return True

		if kwds['table'] not in ['clin.test_result', 'clin.reviewed_test_results']:
			return True

		self._schedule_data_reget()
		return True

	#--------------------------------------------------------
	def _on_add_button_pressed(self, event):
		edit_measurement(parent = self, measurement = None)

	#--------------------------------------------------------
	def _on_manage_types_button_pressed(self, event):
		event.Skip()
		manage_measurement_types(parent = self)

	#--------------------------------------------------------
	def _on_review_button_pressed(self, evt):
		self.PopupMenu(self.__action_button_popup)

	#--------------------------------------------------------
	def _on_select_button_pressed(self, evt):
		if self._RBTN_my_unsigned.GetValue() is True:
			self._GRID_results_all.select_cells(unsigned_only = True, accountables_only = True, keep_preselections = False)
		elif self._RBTN_all_unsigned.GetValue() is True:
			self._GRID_results_all.select_cells(unsigned_only = True, accountables_only = False, keep_preselections = False)

	#------------------------------------------------------------
	# reget mixin API
	#------------------------------------------------------------
	def _populate_with_data(self):
		self.__repopulate_ui()
		return True

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		if (self.__patient is None) and (patient is None):
			return
		if (self.__patient is None) or (patient is None):
			self.__patient = patient
			self._schedule_data_reget()
			return
		if self.__patient.ID == patient.ID:
			return
		self.__patient = patient
		self._schedule_data_reget()

	patient = property(_get_patient, _set_patient)

#================================================================
# notebook based measurements plugin
#================================================================
class cMeasurementsNb(wx.Notebook, gmPlugin.cPatientChange_PluginMixin):
	"""Notebook displaying measurements pages:

		- by test battery
		- by day
		- by issue/episode
		- most-recent list, perhaps by panel
		- full grid
		- full list

	Used as a main notebook plugin page.

	Operates on the active patient.
	"""
	#--------------------------------------------------------
	def __init__(self, parent, id):

		wx.Notebook.__init__ (
			self,
			parent = parent,
			id = id,
			style = wx.NB_TOP | wx.NB_MULTILINE | wx.NO_BORDER,
			name = self.__class__.__name__
		)
		_log.debug('created wx.Notebook: %s with ID %s', self.__class__.__name__, self.Id)
		gmPlugin.cPatientChange_PluginMixin.__init__(self)
		self.__patient = gmPerson.gmCurrentPatient()
		self.__init_ui()
		self.SetSelection(0)

	#--------------------------------------------------------
	# patient change plugin API
	#--------------------------------------------------------
	def _on_current_patient_unset(self, **kwds):
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.patient = None

	#--------------------------------------------------------
	def _post_patient_selection(self, **kwds):
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.patient = self.__patient.patient

	#--------------------------------------------------------
	# notebook plugin API
	#--------------------------------------------------------
	def repopulate_ui(self):
		if self.__patient.connected:
			pat = self.__patient.patient
		else:
			pat = None
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.patient = pat

		return True

	#--------------------------------------------------------
	# internal API
	#--------------------------------------------------------
	def __init_ui(self):

		# by day
		new_page = cMeasurementsByDayPnl(self, -1)
		new_page.patient = None
		self.AddPage (
			page = new_page,
			text = _('Days'),
			select = True
		)

		# by issue
		new_page = cMeasurementsByIssuePnl(self, -1)
		new_page.patient = None
		self.AddPage (
			page = new_page,
			text = _('Problems'),
			select = False
		)

		# by test panel
		new_page = cMeasurementsByBatteryPnl(self, -1)
		new_page.patient = None
		self.AddPage (
			page = new_page,
			text = _('Panels'),
			select = False
		)

		# most-recent, by panel
		new_page = cMeasurementsAsMostRecentListPnl(self, -1)
		new_page.patient = None
		self.AddPage (
			page = new_page,
			text = _('Most recent'),
			select = False
		)

		# full grid
		new_page = cMeasurementsAsTablePnl(self, -1)
		new_page.patient = None
		self.AddPage (
			page = new_page,
			text = _('Table'),
			select = False
		)

		# full list
		new_page = cMeasurementsAsListPnl(self, -1)
		new_page.patient = None
		self.AddPage (
			page = new_page,
			text = _('List'),
			select = False
		)

	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		self.__patient = patient
		if self.__patient.connected:
			pat = self.__patient.patient
		else:
			pat = None
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.patient = pat

	patient = property(_get_patient, _set_patient)

#================================================================
class cMeasurementsGrid(wx.grid.Grid):
	"""A grid class for displaying measurement results.

	- operates on a cPatient instance handed to it
	- does NOT listen to the currently active patient
	- thereby it can display any patient at any time
	"""
	# FIXME: sort-by-battery
	# FIXME: filter out empty
	# FIXME: filter by tests of a selected date
	# FIXME: dates DESC/ASC by cfg
	# FIXME: mouse over column header: display date info
	def __init__(self, *args, **kwargs):

		wx.grid.Grid.__init__(self, *args, **kwargs)

		self.__patient = None
		self.__panel_to_show = None
		self.__show_by_panel = False
		self.__cell_data = {}
		self.__row_label_data = []
		self.__col_label_data = []

		self.__prev_row = None
		self.__prev_col = None
		self.__prev_label_row = None
		self.__date_format = str((_('lab_grid_date_format::%Y\n%b %d')).lstrip('lab_grid_date_format::'))

		self.__init_ui()
		self.__register_events()

	#------------------------------------------------------------
	# external API
	#------------------------------------------------------------
	def delete_current_selection(self):
		if not self.IsSelection():
			gmDispatcher.send(signal = 'statustext', msg = _('No results selected for deletion.'))
			return True

		selected_cells = self.get_selected_cells()
		if len(selected_cells) > 20:
			results = None
			msg = _(
				'There are %s results marked for deletion.\n'
				'\n'
				'Are you sure you want to delete these results ?'
			) % len(selected_cells)
		else:
			results = self.__cells_to_data(cells = selected_cells, exclude_multi_cells = False)
			txt = '\n'.join([ '%s %s (%s): %s %s%s' % (
					r['clin_when'].strftime('%x %H:%M'),
					r['unified_abbrev'],
					r['unified_name'],
					r['unified_val'],
					r['val_unit'],
					gmTools.coalesce(r['abnormality_indicator'], '', ' (%s)')
				) for r in results
			])
			msg = _(
				'The following results are marked for deletion:\n'
				'\n'
				'%s\n'
				'\n'
				'Are you sure you want to delete these results ?'
			) % txt

		dlg = gmGuiHelpers.c2ButtonQuestionDlg (
			self,
			-1,
			caption = _('Deleting test results'),
			question = msg,
			button_defs = [
				{'label': _('Delete'), 'tooltip': _('Yes, delete all the results.'), 'default': False},
				{'label': _('Cancel'), 'tooltip': _('No, do NOT delete any results.'), 'default': True}
			]
		)
		decision = dlg.ShowModal()

		if decision == wx.ID_YES:
			if results is None:
				results = self.__cells_to_data(cells = selected_cells, exclude_multi_cells = False)
			for result in results:
				gmPathLab.delete_test_result(result)

	#------------------------------------------------------------
	def sign_current_selection(self):
		if not self.IsSelection():
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot sign results. No results selected.'))
			return True

		selected_cells = self.get_selected_cells()
		tests = self.__cells_to_data(cells = selected_cells, exclude_multi_cells = False)

		return review_tests(parent = self, tests = tests)

	#------------------------------------------------------------
	def plot_current_selection(self):

		if not self.IsSelection():
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot plot results. No results selected.'))
			return True

		tests = self.__cells_to_data (
			cells = self.get_selected_cells(),
			exclude_multi_cells = False,
			auto_include_multi_cells = True
		)

		plot_measurements(parent = self, tests = tests)

	#------------------------------------------------------------
	def get_selected_cells(self):
		"""Assemble list of all selected cells."""

		all_selected_cells = []
		# individually selected cells (ctrl-click)
		all_selected_cells += [ cell_coords.Get() for cell_coords in self.GetSelectedCells() ]
		# add cells from fully selected rows
		fully_selected_rows = self.GetSelectedRows()
		all_selected_cells += list (
			(row, col)
				for row in fully_selected_rows
				for col in range(self.GetNumberCols())
		)
		# add cells from fully selected columns
		fully_selected_cols = self.GetSelectedCols()
		all_selected_cells += list (
			(row, col)
				for row in range(self.GetNumberRows())
				for col in fully_selected_cols
		)
		# add cells from selection blocks
		selected_blocks = zip(self.GetSelectionBlockTopLeft(), self.GetSelectionBlockBottomRight())
		for top_left_corner, bottom_right_corner in selected_blocks:
			all_selected_cells += [
				(row, col)
					for row in range(top_left_corner[0], bottom_right_corner[0] + 1)
					for col in range(top_left_corner[1], bottom_right_corner[1] + 1)
			]
		return set(all_selected_cells)

	#------------------------------------------------------------
	def select_cells(self, unsigned_only=False, accountables_only=False, keep_preselections=False):
		"""Select a range of cells according to criteria.

		unsigned_only: include only those which are not signed at all yet
		accountable_only: include only those for which the current user is responsible
		keep_preselections: broaden (rather than replace) the range of selected cells

		Combinations are powerful !
		"""
		wx.BeginBusyCursor()
		self.BeginBatch()

		if not keep_preselections:
			self.ClearSelection()

		for col_idx in self.__cell_data:
			for row_idx in self.__cell_data[col_idx]:
				# loop over results in cell and only include
				# those multi-value cells that are not ambiguous
				do_not_include = False
				for result in self.__cell_data[col_idx][row_idx]:
					if unsigned_only:
						if result['reviewed']:
							do_not_include = True
							break
					if accountables_only:
						if not result['you_are_responsible']:
							do_not_include = True
							break
				if do_not_include:
					continue

				self.SelectBlock(row_idx, col_idx, row_idx, col_idx, addToSelected = True)

		self.EndBatch()
		wx.EndBusyCursor()

	#------------------------------------------------------------
	def repopulate_grid(self):
		self.empty_grid()
		if self.__patient is None:
			return

		if self.__show_by_panel:
			if self.__panel_to_show is None:
				return
			tests = self.__panel_to_show.get_test_types_for_results (
				self.__patient.ID,
				order_by = 'unified_abbrev',
				unique_meta_types = True
			)
			self.__repopulate_grid (
				tests4rows = tests,
				test_pks2show = [ tt['pk_test_type'] for tt in self.__panel_to_show['test_types'] ]
			)
			return

		emr = self.__patient.emr
		tests = emr.get_test_types_for_results(order_by = 'unified_abbrev', unique_meta_types = True)
		self.__repopulate_grid(tests4rows = tests)

	#------------------------------------------------------------
	def __repopulate_grid(self, tests4rows=None, test_pks2show=None):

		if len(tests4rows) == 0:
			return

		emr = self.__patient.emr

		self.__row_label_data = tests4rows
		row_labels = [ '%s%s' % (
				gmTools.bool2subst(test_type['is_fake_meta_type'], '', gmTools.u_sum, ''),
				test_type['unified_abbrev']
			) for test_type in self.__row_label_data
		]

		self.__col_label_data = [ d['clin_when_day'] for d in emr.get_dates_for_results (
			tests = test_pks2show,
			reverse_chronological = True
		)]
		col_labels = [ gmDateTime.pydt_strftime(date, self.__date_format, accuracy = gmDateTime.acc_days) for date in self.__col_label_data ]

		results = emr.get_test_results_by_date (
			tests = test_pks2show,
			reverse_chronological = True
		)

		self.BeginBatch()

		# rows
		self.AppendRows(numRows = len(row_labels))
		for row_idx in range(len(row_labels)):
			self.SetRowLabelValue(row_idx, row_labels[row_idx])

		# columns
		self.AppendCols(numCols = len(col_labels))
		for col_idx in range(len(col_labels)):
			self.SetColLabelValue(col_idx, col_labels[col_idx])

		# cell values (list of test results)
		for result in results:
			row_idx = row_labels.index('%s%s' % (
				gmTools.bool2subst(result['is_fake_meta_type'], '', gmTools.u_sum, ''),
				result['unified_abbrev']
			))
			col_idx = col_labels.index(gmDateTime.pydt_strftime(result['clin_when'], self.__date_format, accuracy = gmDateTime.acc_days))

			try:
				self.__cell_data[col_idx]
			except KeyError:
				self.__cell_data[col_idx] = {}

			# the tooltip always shows the youngest sub result details
			if row_idx in self.__cell_data[col_idx]:
				self.__cell_data[col_idx][row_idx].append(result)
				self.__cell_data[col_idx][row_idx].sort(key = lambda x: x['clin_when'], reverse = True)
			else:
				self.__cell_data[col_idx][row_idx] = [result]

			# rebuild cell display string
			vals2display = []
			cell_has_out_of_bounds_value = False
			for sub_result in self.__cell_data[col_idx][row_idx]:

				if sub_result.is_considered_abnormal:
					cell_has_out_of_bounds_value = True

				abnormality_indicator = sub_result.formatted_abnormality_indicator
				if abnormality_indicator is None:
					abnormality_indicator = ''
				if abnormality_indicator != '':
					abnormality_indicator = ' (%s)' % abnormality_indicator[:3]

				missing_review = False
				# warn on missing review if
				# a) no review at all exists or
				if not sub_result['reviewed']:
					missing_review = True
				# b) there is a review but
				else:
					# current user is reviewer and hasn't reviewed
					if sub_result['you_are_responsible'] and not sub_result['review_by_you']:
						missing_review = True

				needs_superscript = False

				# can we display the full sub_result length ?
				if sub_result.is_long_text:
					lines = gmTools.strip_empty_lines (
						text = sub_result['unified_val'],
						eol = '\n',
						return_list = True
					)
					needs_superscript = True
					tmp = lines[0][:7]
				else:
					val = gmTools.strip_empty_lines (
						text = sub_result['unified_val'],
						eol = '\n',
						return_list = False
					).replace('\n', '//')
					if len(val) > 8:
						needs_superscript = True
						tmp = val[:7]
					else:
						tmp = '%.8s' % val[:8]

				# abnormal ?
				tmp = '%s%.6s' % (tmp, abnormality_indicator)

				# is there a comment ?
				has_sub_result_comment = gmTools.coalesce (
					gmTools.coalesce(sub_result['note_test_org'], sub_result['comment']),
					''
				).strip() != ''
				if has_sub_result_comment:
					needs_superscript = True

				if needs_superscript:
					tmp = '%s%s' % (tmp, gmTools.u_superscript_one)

				# lacking a review ?
				if missing_review:
					tmp = '%s %s' % (tmp, gmTools.u_writing_hand)
				else:
					if sub_result['is_clinically_relevant']:
						tmp += ' !'

				# part of a multi-result cell ?
				if len(self.__cell_data[col_idx][row_idx]) > 1:
					tmp = '%s %s' % (sub_result['clin_when'].strftime('%H:%M'), tmp)

				vals2display.append(tmp)

			self.SetCellValue(row_idx, col_idx, '\n'.join(vals2display))
			self.SetCellAlignment(row_idx, col_idx, horiz = wx.ALIGN_RIGHT, vert = wx.ALIGN_CENTRE)
			# We used to color text in cells holding abnormals
			# in firebrick red but that would color ALL text (including
			# normals) and not only the abnormals within that
			# cell. Shading, however, only says that *something*
			# inside that cell is worthy of attention.
			#if sub_result_relevant:
			#	font = self.GetCellFont(row_idx, col_idx)
			#	self.SetCellTextColour(row_idx, col_idx, 'firebrick')
			#	font.SetWeight(wx.FONTWEIGHT_BOLD)
			#	self.SetCellFont(row_idx, col_idx, font)
			if cell_has_out_of_bounds_value:
				#self.SetCellBackgroundColour(row_idx, col_idx, 'cornflower blue')
				self.SetCellBackgroundColour(row_idx, col_idx, 'PALE TURQUOISE')

		self.EndBatch()

		self.AutoSize()
		self.AdjustScrollbars()
		self.ForceRefresh()

		#self.Fit()

		return

	#------------------------------------------------------------
	def empty_grid(self):
		self.BeginBatch()
		self.ClearGrid()
		# Windows cannot do nothing, it rather decides to assert()
		# on thinking it is supposed to do nothing
		if self.GetNumberRows() > 0:
			self.DeleteRows(pos = 0, numRows = self.GetNumberRows())
		if self.GetNumberCols() > 0:
			self.DeleteCols(pos = 0, numCols = self.GetNumberCols())
		self.EndBatch()
		self.__cell_data = {}
		self.__row_label_data = []
		self.__col_label_data = []

	#------------------------------------------------------------
	def get_row_tooltip(self, row=None):
		# include details about test types included ?

		# sometimes, for some reason, there is no row and
		# wxPython still tries to find a tooltip for it
		try:
			tt = self.__row_label_data[row]
		except IndexError:
			return ' '

		if tt['is_fake_meta_type']:
			return tt.format(patient = self.__patient.ID)

		meta_tt = tt.meta_test_type
		txt = meta_tt.format(with_tests = True, patient = self.__patient.ID)

		return txt

	#------------------------------------------------------------
	def get_cell_tooltip(self, col=None, row=None):
		try:
			cell_results = self.__cell_data[col][row]
		except KeyError:
			# FIXME: maybe display the most recent or when the most recent was ?
			cell_results = None

		if cell_results is None:
			return ' '

		is_multi_cell = False
		if len(cell_results) > 1:
			is_multi_cell = True
		result = cell_results[0]

		tt = ''
		# header
		if is_multi_cell:
			tt += _('Details of most recent (topmost) result !               \n')
		if result.is_long_text:
			tt += gmTools.strip_empty_lines(text = result['val_alpha'], eol = '\n', return_list = False)
			return tt

		tt += result.format(with_review = True, with_evaluation = True, with_ranges = True)
		return tt

	#------------------------------------------------------------
	# internal helpers
	#------------------------------------------------------------
	def __init_ui(self):
		#self.SetMinSize(wx.DefaultSize)
		self.SetMinSize((10, 10))

		self.CreateGrid(0, 1)
		self.EnableEditing(0)
		self.EnableDragGridSize(1)

		# column labels
		# setting this screws up the labels: they are cut off and displaced
		#self.SetColLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_BOTTOM)

		# row labels
		self.SetRowLabelSize(wx.grid.GRID_AUTOSIZE)		# starting with 2.8.8
		#self.SetRowLabelSize(150)
		self.SetRowLabelAlignment(horiz = wx.ALIGN_LEFT, vert = wx.ALIGN_CENTRE)
		font = self.GetLabelFont()
		font.SetWeight(wx.FONTWEIGHT_LIGHT)
		self.SetLabelFont(font)

		# add link to left upper corner
		dbcfg = gmCfg.cCfgSQL()
		url = dbcfg.get2 (
			option = 'external.urls.measurements_encyclopedia',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user',
			default = gmPathLab.URL_test_result_information
		)

		self.__WIN_corner = self.GetGridCornerLabelWindow()		# a wx.Window instance

		LNK_lab = wxh.HyperlinkCtrl (
			self.__WIN_corner,
			-1,
			label = _('Tests'),
			style = wxh.HL_DEFAULT_STYLE			# wx.TE_READONLY|wx.TE_CENTRE| wx.NO_BORDER |
		)
		LNK_lab.SetURL(url)
		LNK_lab.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND))
		LNK_lab.SetToolTip(_(
			'Navigate to an encyclopedia of measurements\n'
			'and test methods on the web.\n'
			'\n'
			' <%s>'
		) % url)

		SZR_inner = wx.BoxSizer(wx.HORIZONTAL)
		SZR_inner.Add((20, 20), 1, wx.EXPAND, 0)		# spacer
		SZR_inner.Add(LNK_lab, 0, wx.ALIGN_CENTER_VERTICAL, 0)		#wx.ALIGN_CENTER wx.EXPAND
		SZR_inner.Add((20, 20), 1, wx.EXPAND, 0)		# spacer

		SZR_corner = wx.BoxSizer(wx.VERTICAL)
		SZR_corner.Add((20, 20), 1, wx.EXPAND, 0)		# spacer
		SZR_corner.Add(SZR_inner, 0, wx.EXPAND)			# inner sizer with centered hyperlink
		SZR_corner.Add((20, 20), 1, wx.EXPAND, 0)		# spacer

		self.__WIN_corner.SetSizer(SZR_corner)
		SZR_corner.Fit(self.__WIN_corner)

	#------------------------------------------------------------
	def __resize_corner_window(self, evt):
		self.__WIN_corner.Layout()

	#------------------------------------------------------------
	def __cells_to_data(self, cells=None, exclude_multi_cells=False, auto_include_multi_cells=False):
		"""List of <cells> must be in row / col order."""
		data = []
		for row, col in cells:
			try:
				# cell data is stored col / row
				data_list = self.__cell_data[col][row]
			except KeyError:
				continue

			if len(data_list) == 1:
				data.append(data_list[0])
				continue

			if exclude_multi_cells:
				gmDispatcher.send(signal = 'statustext', msg = _('Excluding multi-result field from further processing.'))
				continue

			if auto_include_multi_cells:
				data.extend(data_list)
				continue

			data_to_include = self.__get_choices_from_multi_cell(cell_data = data_list)
			if data_to_include is None:
				continue
			data.extend(data_to_include)

		return data

	#------------------------------------------------------------
	def __get_choices_from_multi_cell(self, cell_data=None, single_selection=False):
		data = gmListWidgets.get_choices_from_list (
			parent = self,
			msg = _(
				'Your selection includes a field with multiple results.\n'
				'\n'
				'Please select the individual results you want to work on:'
			),
			caption = _('Selecting test results'),
			choices = [ [d['clin_when'], '%s: %s' % (d['abbrev_tt'], d['name_tt']), d['unified_val']] for d in cell_data ],
			columns = [ _('Date / Time'), _('Test'), _('Result') ],
			data = cell_data,
			single_selection = single_selection
		)
		return data

	#------------------------------------------------------------
	# event handling
	#------------------------------------------------------------
	def __register_events(self):
		# dynamic tooltips: GridWindow, GridRowLabelWindow, GridColLabelWindow, GridCornerLabelWindow
		self.GetGridWindow().Bind(wx.EVT_MOTION, self.__on_mouse_over_cells)
		self.GetGridRowLabelWindow().Bind(wx.EVT_MOTION, self.__on_mouse_over_row_labels)
		#self.GetGridColLabelWindow().Bind(wx.EVT_MOTION, self.__on_mouse_over_col_labels)

		# sizing left upper corner window
		self.Bind(wx.EVT_SIZE, self.__resize_corner_window)

		# editing cells
		self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.__on_cell_left_dclicked)

	#------------------------------------------------------------
	def __on_cell_left_dclicked(self, evt):
		col = evt.GetCol()
		row = evt.GetRow()

		try:
			self.__cell_data[col][row]
		except KeyError:		# empty cell
			presets = {}
			col_date = self.__col_label_data[col]
			presets['clin_when'] = {'data': col_date}
			test_type = self.__row_label_data[row]
			if test_type['pk_meta_test_type'] is not None:
				temporally_closest_result_of_row_type = test_type.meta_test_type.get_temporally_closest_result(col_date, self.__patient.ID)
				if temporally_closest_result_of_row_type is not None:
					# pre-set test type field to test type of
					# "temporally most adjacent" existing result :-)
					presets['pk_test_type'] = {'data': temporally_closest_result_of_row_type['pk_test_type']}
				# one might also, instead of considering only the "temporally most adjacent"
				# one, look at the most adjacent one coming from the same *lab* as other
				# results on the desired data ....
			same_day_results = gmPathLab.get_results_for_day (
				timestamp = col_date,
				patient = self.__patient.ID,
				order_by = None
			)
			if len(same_day_results) > 0:
				# pre-set episode field to episode of
				# existing results on the day in question
				presets['pk_episode'] = {'data': same_day_results[0]['pk_episode']}
			# maybe ['comment'] as in "medical context" ? - not thought through yet
			# no need to set because because setting pk_test_type will do so:
			#	presets['val_unit']
			#	presets['val_normal_min']
			#	presets['val_normal_max']
			#	presets['val_normal_range']
			#	presets['val_target_min']
			#	presets['val_target_max']
			#	presets['val_target_range']
			edit_measurement (
				parent = self,
				measurement = None,
				single_entry = True,
				presets = presets
			)
			return

		if len(self.__cell_data[col][row]) > 1:
			data = self.__get_choices_from_multi_cell(cell_data = self.__cell_data[col][row], single_selection = True)
		else:
			data = self.__cell_data[col][row][0]

		if data is None:
			return

		edit_measurement(parent = self, measurement = data, single_entry = True)

	#------------------------------------------------------------
#     def OnMouseMotionRowLabel(self, evt):
#         x, y = self.CalcUnscrolledPosition(evt.GetPosition())
#         row = self.YToRow(y)
#         label = self.table().GetRowHelpValue(row)
#         self.GetGridRowLabelWindow().SetToolTip(label or "")
#         evt.Skip()
	def __on_mouse_over_row_labels(self, evt):

		# Use CalcUnscrolledPosition() to get the mouse position within the
		# entire grid including what's offscreen
		x, y = self.CalcUnscrolledPosition(evt.GetX(), evt.GetY())

		row = self.YToRow(y)

		if self.__prev_label_row == row:
			return

		self.__prev_label_row == row

		evt.GetEventObject().SetToolTip(self.get_row_tooltip(row = row))
	#------------------------------------------------------------
#     def OnMouseMotionColLabel(self, evt):
#         x, y = self.CalcUnscrolledPosition(evt.GetPosition())
#         col = self.XToCol(x)
#         label = self.table().GetColHelpValue(col)
#         self.GetGridColLabelWindow().SetToolTip(label or "")
#         evt.Skip()
	#------------------------------------------------------------
	def __on_mouse_over_cells(self, evt):
		"""Calculate where the mouse is and set the tooltip dynamically."""

		# Use CalcUnscrolledPosition() to get the mouse position within the
		# entire grid including what's offscreen
		x, y = self.CalcUnscrolledPosition(evt.GetX(), evt.GetY())

		# use this logic to prevent tooltips outside the actual cells
		# apply to GetRowSize, too
#        tot = 0
#        for col in range(self.NumberCols):
#            tot += self.GetColSize(col)
#            if xpos <= tot:
#                self.tool_tip.Tip = 'Tool tip for Column %s' % (
#                    self.GetColLabelValue(col))
#                break
#            else:  # mouse is in label area beyond the right-most column
#            self.tool_tip.Tip = ''

		row, col = self.XYToCell(x, y)

		if (row == self.__prev_row) and (col == self.__prev_col):
			return

		self.__prev_row = row
		self.__prev_col = col

		evt.GetEventObject().SetToolTip(self.get_cell_tooltip(col=col, row=row))

	#------------------------------------------------------------
	# properties
	#------------------------------------------------------------
	def _get_patient(self):
		return self.__patient

	def _set_patient(self, patient):
		self.__patient = patient
		self.repopulate_grid()

	patient = property(_get_patient, _set_patient)
	#------------------------------------------------------------
	def _set_panel_to_show(self, panel):
		self.__panel_to_show = panel
		self.repopulate_grid()

	panel_to_show = property(lambda x:x, _set_panel_to_show)
	#------------------------------------------------------------
	def _set_show_by_panel(self, show_by_panel):
		self.__show_by_panel = show_by_panel
		self.repopulate_grid()

	show_by_panel = property(lambda x:x, _set_show_by_panel)

#================================================================
# integrated measurements plugin
#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementsPnl

class cMeasurementsPnl(wxgMeasurementsPnl.wxgMeasurementsPnl, gmRegetMixin.cRegetOnPaintMixin):
	"""Panel holding a grid with lab data. Used as notebook page."""

	def __init__(self, *args, **kwargs):

		wxgMeasurementsPnl.wxgMeasurementsPnl.__init__(self, *args, **kwargs)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)
		self.__display_mode = 'grid'
		self.__init_ui()
		self.__register_interests()
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		gmDispatcher.connect(signal = 'pre_patient_unselection', receiver = self._on_pre_patient_unselection)
		gmDispatcher.connect(signal = 'post_patient_selection', receiver = self._on_post_patient_selection)
		gmDispatcher.connect(signal = 'clin.test_result_mod_db', receiver = self._schedule_data_reget)
		gmDispatcher.connect(signal = 'clin.reviewed_test_results_mod_db', receiver = self._schedule_data_reget)
	#--------------------------------------------------------
	def _on_post_patient_selection(self):
		self._schedule_data_reget()
	#--------------------------------------------------------
	def _on_pre_patient_unselection(self):
		self._GRID_results_all.patient = None
		self._GRID_results_battery.patient = None
	#--------------------------------------------------------
	def _on_add_button_pressed(self, event):
		edit_measurement(parent = self, measurement = None)
	#--------------------------------------------------------
	def _on_manage_types_button_pressed(self, event):
		event.Skip()
		manage_measurement_types(parent = self)
	#--------------------------------------------------------
	def _on_list_button_pressed(self, event):
		event.Skip()
		manage_measurements(parent = self, single_selection = True)#, emr = pat.emr)
	#--------------------------------------------------------
	def _on_review_button_pressed(self, evt):
		self.PopupMenu(self.__action_button_popup)
	#--------------------------------------------------------
	def _on_select_button_pressed(self, evt):
		if self._RBTN_my_unsigned.GetValue() is True:
			self._GRID_results_all.select_cells(unsigned_only = True, accountables_only = True, keep_preselections = False)
		elif self._RBTN_all_unsigned.GetValue() is True:
			self._GRID_results_all.select_cells(unsigned_only = True, accountables_only = False, keep_preselections = False)
	#--------------------------------------------------------
	def _on_manage_panels_button_pressed(self, event):
		manage_test_panels(parent = self)
	#--------------------------------------------------------
	def _on_display_mode_button_pressed(self, event):
		event.Skip()
		if self.__display_mode == 'grid':
			self._BTN_display_mode.SetLabel(_('All: as &Grid'))
			self.__display_mode = 'day'
			#self._GRID_results_all.Hide()
			self._PNL_results_all_grid.Hide()
			if self._PNL_results_all_listed.patient is None:
				self._PNL_results_all_listed.patient = self._GRID_results_all.patient
			self._PNL_results_all_listed.Show()
		else:
			self._BTN_display_mode.SetLabel(_('All: by &Day'))
			self.__display_mode = 'grid'
			self._PNL_results_all_listed.Hide()
			if self._GRID_results_all.patient is None:
				self._GRID_results_all.patient = self._PNL_results_all_listed.patient
			#self._GRID_results_all.Show()
			self._PNL_results_all_grid.Show()
		self.Layout()
	#--------------------------------------------------------
	def __on_sign_current_selection(self, evt):
		self._GRID_results_all.sign_current_selection()
	#--------------------------------------------------------
	def __on_plot_current_selection(self, evt):
		self._GRID_results_all.plot_current_selection()
	#--------------------------------------------------------
	def __on_delete_current_selection(self, evt):
		self._GRID_results_all.delete_current_selection()
	#--------------------------------------------------------
	def _on_panel_selected(self, panel):
		wx.CallAfter(self.__on_panel_selected, panel=panel)
	#--------------------------------------------------------
	def __on_panel_selected(self, panel):
		if panel is None:
			self._TCTRL_panel_comment.SetValue('')
			self._GRID_results_battery.panel_to_show = None
			#self._GRID_results_battery.Hide()
			self._PNL_results_battery_grid.Hide()
		else:
			pnl = self._PRW_panel.GetData(as_instance = True)
			self._TCTRL_panel_comment.SetValue(gmTools.coalesce (
				pnl['comment'],
				''
			))
			self._GRID_results_battery.panel_to_show = pnl
			#self._GRID_results_battery.Show()
			self._PNL_results_battery_grid.Show()
		self._GRID_results_battery.Fit()
		self._GRID_results_all.Fit()
		self.Layout()
	#--------------------------------------------------------
	def _on_panel_selection_modified(self):
		wx.CallAfter(self.__on_panel_selection_modified)
	#--------------------------------------------------------
	def __on_panel_selection_modified(self):
		self._TCTRL_panel_comment.SetValue('')
		if self._PRW_panel.GetValue().strip() == '':
			self._GRID_results_battery.panel_to_show = None
			#self._GRID_results_battery.Hide()
			self._PNL_results_battery_grid.Hide()
			self.Layout()
	#--------------------------------------------------------
	# internal API
	#--------------------------------------------------------
	def __init_ui(self):
		self.SetMinSize((10, 10))

		self.__action_button_popup = wx.Menu(title = _('Perform on selected results:'))

		item = self.__action_button_popup.Append(-1, _('Review and &sign'))
		self.Bind(wx.EVT_MENU, self.__on_sign_current_selection, item)

		item = self.__action_button_popup.Append(-1, _('Plot'))
		self.Bind(wx.EVT_MENU, self.__on_plot_current_selection, item)

		item = self.__action_button_popup.Append(-1, _('Export to &file'))
		self.Bind(wx.EVT_MENU, self._GRID_results_all.current_selection_to_file, item)
		self.__action_button_popup.Enable(id = menu_id, enable = False)

		item = self.__action_button_popup.Append(-1, _('Export to &clipboard'))
		self.Bind(wx.EVT_MENU, self._GRID_results_all.current_selection_to_clipboard, item)
		self.__action_button_popup.Enable(id = menu_id, enable = False)

		item = self.__action_button_popup.Append(-1, _('&Delete'))
		self.Bind(wx.EVT_MENU, self.__on_delete_current_selection, item)

		# FIXME: create inbox message to staff to phone patient to come in
		# FIXME: generate and let edit a SOAP narrative and include the values

		self._PRW_panel.add_callback_on_selection(callback = self._on_panel_selected)
		self._PRW_panel.add_callback_on_modified(callback = self._on_panel_selection_modified)

		self._GRID_results_battery.show_by_panel = True
		self._GRID_results_battery.panel_to_show = None
		#self._GRID_results_battery.Hide()
		self._PNL_results_battery_grid.Hide()
		self._BTN_display_mode.SetLabel(_('All: by &Day'))
		#self._GRID_results_all.Show()
		self._PNL_results_all_grid.Show()
		self._PNL_results_all_listed.Hide()
		self.Layout()

		self._PRW_panel.SetFocus()
	#--------------------------------------------------------
	# reget mixin API
	#--------------------------------------------------------
	def _populate_with_data(self):
		pat = gmPerson.gmCurrentPatient()
		if pat.connected:
			self._GRID_results_battery.patient = pat
			if self.__display_mode == 'grid':
				self._GRID_results_all.patient = pat
				self._PNL_results_all_listed.patient = None
			else:
				self._GRID_results_all.patient = None
				self._PNL_results_all_listed.patient = pat
		else:
			self._GRID_results_battery.patient = None
			self._GRID_results_all.patient = None
			self._PNL_results_all_listed.patient = None
		return True

#================================================================
# editing widgets
#================================================================
def review_tests(parent=None, tests=None):

	if tests is None:
		return True

	if len(tests) == 0:
		return True

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	if len(tests) > 10:
		test_count = len(tests)
		tests2show = None
	else:
		test_count = None
		tests2show = tests
		if len(tests) == 0:
			return True

	dlg = cMeasurementsReviewDlg(parent, -1, tests = tests, test_count = test_count)
	decision = dlg.ShowModal()
	if decision != wx.ID_APPLY:
		return True

	wx.BeginBusyCursor()
	if dlg._RBTN_confirm_abnormal.GetValue():
		abnormal = None
	elif dlg._RBTN_results_normal.GetValue():
		abnormal = False
	else:
		abnormal = True

	if dlg._RBTN_confirm_relevance.GetValue():
		relevant = None
	elif dlg._RBTN_results_not_relevant.GetValue():
		relevant = False
	else:
		relevant = True

	comment = None
	if len(tests) == 1:
		comment = dlg._TCTRL_comment.GetValue()

	make_responsible = dlg._CHBOX_responsible.IsChecked()
	dlg.DestroyLater()

	for test in tests:
		test.set_review (
			technically_abnormal = abnormal,
			clinically_relevant = relevant,
			comment = comment,
			make_me_responsible = make_responsible
		)
	wx.EndBusyCursor()

	return True

#----------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgMeasurementsReviewDlg

class cMeasurementsReviewDlg(wxgMeasurementsReviewDlg.wxgMeasurementsReviewDlg):

	def __init__(self, *args, **kwargs):

		try:
			tests = kwargs['tests']
			del kwargs['tests']
			test_count = len(tests)
			try: del kwargs['test_count']
			except KeyError: pass
		except KeyError:
			tests = None
			test_count = kwargs['test_count']
			del kwargs['test_count']

		wxgMeasurementsReviewDlg.wxgMeasurementsReviewDlg.__init__(self, *args, **kwargs)

		if tests is None:
			msg = _('%s results selected. Too many to list individually.') % test_count
		else:
			msg = '\n'.join (
				[	'%s: %s %s (%s)' % (
						t['unified_abbrev'],
						t['unified_val'],
						t['val_unit'],
						gmDateTime.pydt_strftime(t['clin_when'], '%Y %b %d')
					) for t in tests
				]
			)

		self._LBL_tests.SetLabel(msg)

		if test_count == 1:
			self._TCTRL_comment.Enable(True)
			self._TCTRL_comment.SetValue(gmTools.coalesce(tests[0]['review_comment'], ''))
			if tests[0]['you_are_responsible']:
				self._CHBOX_responsible.Enable(False)

		self.Fit()
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def _on_signoff_button_pressed(self, evt):
		if self.IsModal():
			self.EndModal(wx.ID_APPLY)
		else:
			self.Close()

#================================================================
from Gnumed.wxGladeWidgets import wxgMeasurementEditAreaPnl

class cMeasurementEditAreaPnl(wxgMeasurementEditAreaPnl.wxgMeasurementEditAreaPnl, gmEditArea.cGenericEditAreaMixin):
	"""This edit area saves *new* measurements into the active patient only."""

	def __init__(self, *args, **kwargs):

		try:
			self.__default_date = kwargs['date']
			del kwargs['date']
		except KeyError:
			self.__default_date = None

		wxgMeasurementEditAreaPnl.wxgMeasurementEditAreaPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.__register_interests()

		self.successful_save_msg = _('Successfully saved measurement.')

		self._DPRW_evaluated.display_accuracy = gmDateTime.acc_minutes

	#--------------------------------------------------------
	# generic edit area mixin API
	#----------------------------------------------------------------
	def set_fields(self, fields):
		self._TCTRL_result.SetFocus()
		try:
			self._PRW_test.SetData(data = fields['pk_test_type']['data'])
		except KeyError:
			self._PRW_test.SetFocus()
		try:
			self._DPRW_evaluated.SetData(data = fields['clin_when']['data'])
		except KeyError:
			pass
		try:
			self._PRW_problem.SetData(data = fields['pk_episode']['data'])
		except KeyError:
			pass
		try:
			self._PRW_units.SetText(fields['val_unit']['data'], fields['val_unit']['data'], True)
		except KeyError:
			pass
		try:
			self._TCTRL_normal_min.SetValue(fields['val_normal_min']['data'])
		except KeyError:
			pass
		try:
			self._TCTRL_normal_max.SetValue(fields['val_normal_max']['data'])
		except KeyError:
			pass
		try:
			self._TCTRL_normal_range.SetValue(fields['val_normal_range']['data'])
		except KeyError:
			pass
		try:
			self._TCTRL_target_min.SetValue(fields['val_target_min']['data'])
		except KeyError:
			pass
		try:
			self._TCTRL_target_max.SetValue(fields['val_target_max']['data'])
		except KeyError:
			pass
		try:
			self._TCTRL_target_range.SetValue(fields['val_target_range']['data'])
		except KeyError:
			pass

	#--------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_test.SetText('', None, True)
		self.__refresh_loinc_info()
		self.__refresh_previous_value()
		self.__update_units_context()
		self._TCTRL_result.SetValue('')
		self._PRW_units.SetText('', None, True)
		self._PRW_abnormality_indicator.SetText('', None, True)
		if self.__default_date is None:
			self._DPRW_evaluated.SetData(data = pyDT.datetime.now(tz = gmDateTime.gmCurrentLocalTimezone))
		else:
			self._DPRW_evaluated.SetData(data =	None)
		self._TCTRL_note_test_org.SetValue('')
		self._PRW_intended_reviewer.SetData(gmStaff.gmCurrentProvider()['pk_staff'])
		self._PRW_problem.SetData()
		self._TCTRL_narrative.SetValue('')
		self._CHBOX_review.SetValue(False)
		self._CHBOX_abnormal.SetValue(False)
		self._CHBOX_relevant.SetValue(False)
		self._CHBOX_abnormal.Enable(False)
		self._CHBOX_relevant.Enable(False)
		self._TCTRL_review_comment.SetValue('')
		self._TCTRL_normal_min.SetValue('')
		self._TCTRL_normal_max.SetValue('')
		self._TCTRL_normal_range.SetValue('')
		self._TCTRL_target_min.SetValue('')
		self._TCTRL_target_max.SetValue('')
		self._TCTRL_target_range.SetValue('')
		self._TCTRL_norm_ref_group.SetValue('')

		self._PRW_test.SetFocus()
	#--------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_test.SetData(data = self.data['pk_test_type'])
		self.__refresh_loinc_info()
		self.__refresh_previous_value()
		self.__update_units_context()
		self._TCTRL_result.SetValue(self.data['unified_val'])
		self._PRW_units.SetText(self.data['val_unit'], self.data['val_unit'], True)
		self._PRW_abnormality_indicator.SetText (
			gmTools.coalesce(self.data['abnormality_indicator'], ''),
			gmTools.coalesce(self.data['abnormality_indicator'], ''),
			True
		)
		self._DPRW_evaluated.SetData(data = self.data['clin_when'])
		self._TCTRL_note_test_org.SetValue(gmTools.coalesce(self.data['note_test_org'], ''))
		self._PRW_intended_reviewer.SetData(self.data['pk_intended_reviewer'])
		self._PRW_problem.SetData(self.data['pk_episode'])
		self._TCTRL_narrative.SetValue(gmTools.coalesce(self.data['comment'], ''))
		self._CHBOX_review.SetValue(False)
		self._CHBOX_abnormal.SetValue(gmTools.coalesce(self.data['is_technically_abnormal'], False))
		self._CHBOX_relevant.SetValue(gmTools.coalesce(self.data['is_clinically_relevant'], False))
		self._CHBOX_abnormal.Enable(False)
		self._CHBOX_relevant.Enable(False)
		self._TCTRL_review_comment.SetValue(gmTools.coalesce(self.data['review_comment'], ''))
		self._TCTRL_normal_min.SetValue(str(gmTools.coalesce(self.data['val_normal_min'], '')))
		self._TCTRL_normal_max.SetValue(str(gmTools.coalesce(self.data['val_normal_max'], '')))
		self._TCTRL_normal_range.SetValue(gmTools.coalesce(self.data['val_normal_range'], ''))
		self._TCTRL_target_min.SetValue(str(gmTools.coalesce(self.data['val_target_min'], '')))
		self._TCTRL_target_max.SetValue(str(gmTools.coalesce(self.data['val_target_max'], '')))
		self._TCTRL_target_range.SetValue(gmTools.coalesce(self.data['val_target_range'], ''))
		self._TCTRL_norm_ref_group.SetValue(gmTools.coalesce(self.data['norm_ref_group'], ''))

		self._TCTRL_result.SetFocus()
	#--------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._PRW_test.SetText('', None, True)
		self.__refresh_loinc_info()
		self.__refresh_previous_value()
		self.__update_units_context()
		self._TCTRL_result.SetValue('')
		self._PRW_units.SetText('', None, True)
		self._PRW_abnormality_indicator.SetText('', None, True)
		self._DPRW_evaluated.SetData(data = self.data['clin_when'])
		self._TCTRL_note_test_org.SetValue('')
		self._PRW_intended_reviewer.SetData(self.data['pk_intended_reviewer'])
		self._PRW_problem.SetData(self.data['pk_episode'])
		self._TCTRL_narrative.SetValue('')
		self._CHBOX_review.SetValue(False)
		self._CHBOX_abnormal.SetValue(False)
		self._CHBOX_relevant.SetValue(False)
		self._CHBOX_abnormal.Enable(False)
		self._CHBOX_relevant.Enable(False)
		self._TCTRL_review_comment.SetValue('')
		self._TCTRL_normal_min.SetValue('')
		self._TCTRL_normal_max.SetValue('')
		self._TCTRL_normal_range.SetValue('')
		self._TCTRL_target_min.SetValue('')
		self._TCTRL_target_max.SetValue('')
		self._TCTRL_target_range.SetValue('')
		self._TCTRL_norm_ref_group.SetValue('')

		self._PRW_test.SetFocus()
	#--------------------------------------------------------
	def _valid_for_save(self):

		validity = True

		if not self._DPRW_evaluated.is_valid_timestamp():
			self._DPRW_evaluated.display_as_valid(False)
			validity = False
		else:
			self._DPRW_evaluated.display_as_valid(True)

		val = self._TCTRL_result.GetValue().strip()
		if val == '':
			validity = False
			self.display_ctrl_as_valid(self._TCTRL_result, False)
		else:
			self.display_ctrl_as_valid(self._TCTRL_result, True)
			numeric, val = gmTools.input2decimal(val)
			if numeric:
				if self._PRW_units.GetValue().strip() == '':
					self._PRW_units.display_as_valid(False)
					validity = False
				else:
					self._PRW_units.display_as_valid(True)
			else:
				self._PRW_units.display_as_valid(True)

		if self._PRW_problem.GetValue().strip() == '':
			self._PRW_problem.display_as_valid(False)
			validity = False
		else:
			self._PRW_problem.display_as_valid(True)

		if self._PRW_test.GetValue().strip() == '':
			self._PRW_test.display_as_valid(False)
			validity = False
		else:
			self._PRW_test.display_as_valid(True)

		if self._PRW_intended_reviewer.GetData() is None:
			self._PRW_intended_reviewer.display_as_valid(False)
			validity = False
		else:
			self._PRW_intended_reviewer.display_as_valid(True)

		ctrls = [self._TCTRL_normal_min, self._TCTRL_normal_max, self._TCTRL_target_min, self._TCTRL_target_max]
		for widget in ctrls:
			val = widget.GetValue().strip()
			if val == '':
				continue
			try:
				decimal.Decimal(val.replace(',', '.', 1))
				self.display_ctrl_as_valid(widget, True)
			except Exception:
				validity = False
				self.display_ctrl_as_valid(widget, False)

		if validity is False:
			self.StatusText = _('Cannot save result. Invalid or missing essential input.')

		return validity
	#--------------------------------------------------------
	def _save_as_new(self):

		emr = gmPerson.gmCurrentPatient().emr

		success, result = gmTools.input2decimal(self._TCTRL_result.GetValue())
		if success:
			v_num = result
			v_al = None
		else:
			v_al = self._TCTRL_result.GetValue().strip()
			v_num = None

		pk_type = self._PRW_test.GetData()
		if pk_type is None:
			abbrev = self._PRW_test.GetValue().strip()
			name = self._PRW_test.GetValue().strip()
			unit = gmTools.coalesce(self._PRW_units.GetData(), self._PRW_units.GetValue()).strip()
			lab = manage_measurement_orgs (
				parent = self,
				msg = _('Please select (or create) a lab for the new test type [%s in %s]') % (name, unit)
			)
			if lab is not None:
				lab = lab['pk_test_org']
			tt = gmPathLab.create_measurement_type (
				lab = lab,
				abbrev = abbrev,
				name = name,
				unit = unit
			)
			pk_type = tt['pk_test_type']

		tr = emr.add_test_result (
			episode = self._PRW_problem.GetData(can_create=True, is_open=False),
			type = pk_type,
			intended_reviewer = self._PRW_intended_reviewer.GetData(),
			val_num = v_num,
			val_alpha = v_al,
			unit = self._PRW_units.GetValue()
		)

		tr['clin_when'] = self._DPRW_evaluated.GetData().get_pydt()

		ctrls = [
			('abnormality_indicator', self._PRW_abnormality_indicator),
			('note_test_org', self._TCTRL_note_test_org),
			('comment', self._TCTRL_narrative),
			('val_normal_range', self._TCTRL_normal_range),
			('val_target_range', self._TCTRL_target_range),
			('norm_ref_group', self._TCTRL_norm_ref_group)
		]
		for field, widget in ctrls:
			tr[field] = widget.GetValue().strip()

		ctrls = [
			('val_normal_min', self._TCTRL_normal_min),
			('val_normal_max', self._TCTRL_normal_max),
			('val_target_min', self._TCTRL_target_min),
			('val_target_max', self._TCTRL_target_max)
		]
		for field, widget in ctrls:
			val = widget.GetValue().strip()
			if val == '':
				tr[field] = None
			else:
				tr[field] = decimal.Decimal(val.replace(',', '.', 1))

		tr.save_payload()

		if self._CHBOX_review.GetValue() is True:
			tr.set_review (
				technically_abnormal = self._CHBOX_abnormal.GetValue(),
				clinically_relevant = self._CHBOX_relevant.GetValue(),
				comment = gmTools.none_if(self._TCTRL_review_comment.GetValue().strip(), ''),
				make_me_responsible = False
			)

		self.data = tr

#		wx.CallAfter (
#			plot_adjacent_measurements,
#			test = self.data,
#			plot_singular_result = False,
#			use_default_template = True
#		)

		return True
	#--------------------------------------------------------
	def _save_as_update(self):

		success, result = gmTools.input2decimal(self._TCTRL_result.GetValue())
		if success:
			v_num = result
			v_al = None
		else:
			v_num = None
			v_al = self._TCTRL_result.GetValue().strip()

		pk_type = self._PRW_test.GetData()
		if pk_type is None:
			abbrev = self._PRW_test.GetValue().strip()
			name = self._PRW_test.GetValue().strip()
			unit = gmTools.coalesce(self._PRW_units.GetData(), self._PRW_units.GetValue()).strip()
			lab = manage_measurement_orgs (
				parent = self,
				msg = _('Please select (or create) a lab for the new test type [%s in %s]') % (name, unit)
			)
			if lab is not None:
				lab = lab['pk_test_org']
			tt = gmPathLab.create_measurement_type (
				lab = None,
				abbrev = abbrev,
				name = name,
				unit = unit
			)
			pk_type = tt['pk_test_type']

		tr = self.data

		tr['pk_episode'] = self._PRW_problem.GetData(can_create=True, is_open=False)
		tr['pk_test_type'] = pk_type
		tr['pk_intended_reviewer'] = self._PRW_intended_reviewer.GetData()
		tr['val_num'] = v_num
		tr['val_alpha'] = v_al
		tr['val_unit'] = gmTools.coalesce(self._PRW_units.GetData(), self._PRW_units.GetValue()).strip()
		tr['clin_when'] = self._DPRW_evaluated.GetData().get_pydt()

		ctrls = [
			('abnormality_indicator', self._PRW_abnormality_indicator),
			('note_test_org', self._TCTRL_note_test_org),
			('comment', self._TCTRL_narrative),
			('val_normal_range', self._TCTRL_normal_range),
			('val_target_range', self._TCTRL_target_range),
			('norm_ref_group', self._TCTRL_norm_ref_group)
		]
		for field, widget in ctrls:
			tr[field] = widget.GetValue().strip()

		ctrls = [
			('val_normal_min', self._TCTRL_normal_min),
			('val_normal_max', self._TCTRL_normal_max),
			('val_target_min', self._TCTRL_target_min),
			('val_target_max', self._TCTRL_target_max)
		]
		for field, widget in ctrls:
			val = widget.GetValue().strip()
			if val == '':
				tr[field] = None
			else:
				tr[field] = decimal.Decimal(val.replace(',', '.', 1))

		tr.save_payload()

		if self._CHBOX_review.GetValue() is True:
			tr.set_review (
				technically_abnormal = self._CHBOX_abnormal.GetValue(),
				clinically_relevant = self._CHBOX_relevant.GetValue(),
				comment = gmTools.none_if(self._TCTRL_review_comment.GetValue().strip(), ''),
				make_me_responsible = False
			)

#		wx.CallAfter (
#			plot_adjacent_measurements,
#			test = self.data,
#			plot_singular_result = False,
#			use_default_template = True
#		)

		return True
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		self._PRW_test.add_callback_on_lose_focus(self._on_leave_test_prw)
		self._PRW_abnormality_indicator.add_callback_on_lose_focus(self._on_leave_indicator_prw)
		self._PRW_units.add_callback_on_lose_focus(self._on_leave_unit_prw)
	#--------------------------------------------------------
	def _on_leave_test_prw(self):
		self.__refresh_loinc_info()
		self.__refresh_previous_value()
		self.__update_units_context()
		# only works if we've got a unit set
		self.__update_normal_range()
		self.__update_clinical_range()
	#--------------------------------------------------------
	def _on_leave_unit_prw(self):
		# maybe we've got a unit now ?
		self.__update_normal_range()
		self.__update_clinical_range()
	#--------------------------------------------------------
	def _on_leave_indicator_prw(self):
		# if the user hasn't explicitly enabled reviewing
		if not self._CHBOX_review.GetValue():
			self._CHBOX_abnormal.SetValue(self._PRW_abnormality_indicator.GetValue().strip() != '')
	#--------------------------------------------------------
	def _on_review_box_checked(self, evt):
		self._CHBOX_abnormal.Enable(self._CHBOX_review.GetValue())
		self._CHBOX_relevant.Enable(self._CHBOX_review.GetValue())
		self._TCTRL_review_comment.Enable(self._CHBOX_review.GetValue())
	#--------------------------------------------------------
	def _on_test_info_button_pressed(self, event):
		pk = self._PRW_test.GetData()
		if pk is not None:
			tt = gmPathLab.cMeasurementType(aPK_obj = pk)
			search_term = '%s %s %s' % (
				tt['name'],
				tt['abbrev'],
				gmTools.coalesce(tt['loinc'], '')
			)
		else:
			search_term = self._PRW_test.GetValue()

		search_term = search_term.replace(' ', '+')

		call_browser_on_measurement_type(measurement_type = search_term)
	#--------------------------------------------------------
	def _on_manage_episodes_button_pressed(self, event):
		event.Skip()
		gmEMRStructWidgets.manage_episodes(parent = self)
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __update_units_context(self):

		if self._PRW_test.GetData() is None:
			self._PRW_units.unset_context(context = 'pk_type')
			self._PRW_units.unset_context(context = 'loinc')
			if self._PRW_test.GetValue().strip() == '':
				self._PRW_units.unset_context(context = 'test_name')
			else:
				self._PRW_units.set_context(context = 'test_name', val = self._PRW_test.GetValue().strip())
			return

		tt = self._PRW_test.GetData(as_instance = True)

		self._PRW_units.set_context(context = 'pk_type', val = tt['pk_test_type'])
		self._PRW_units.set_context(context = 'test_name', val = tt['name'])

		if tt['loinc'] is not None:
			self._PRW_units.set_context(context = 'loinc', val = tt['loinc'])

		# closest unit
		if self._PRW_units.GetValue().strip() == '':
			clin_when = self._DPRW_evaluated.GetData()
			if clin_when is None:
				unit = tt.temporally_closest_unit
			else:
				clin_when = clin_when.get_pydt()
				unit = tt.get_temporally_closest_unit(timestamp = clin_when)
			if unit is None:
				self._PRW_units.SetText('', unit, True)
			else:
				self._PRW_units.SetText(unit, unit, True)

	#--------------------------------------------------------
	def __update_normal_range(self):
		unit = self._PRW_units.GetValue().strip()
		if unit == '':
			return
		if self._PRW_test.GetData() is None:
			return
		for ctrl in [self._TCTRL_normal_min, self._TCTRL_normal_max, self._TCTRL_normal_range, self._TCTRL_norm_ref_group]:
			if ctrl.GetValue().strip() != '':
				return
		tt = self._PRW_test.GetData(as_instance = True)
		test_w_range = tt.get_temporally_closest_normal_range (
			unit,
			timestamp = self._DPRW_evaluated.GetData().get_pydt()
		)
		if test_w_range is None:
			return
		self._TCTRL_normal_min.SetValue(str(gmTools.coalesce(test_w_range['val_normal_min'], '')))
		self._TCTRL_normal_max.SetValue(str(gmTools.coalesce(test_w_range['val_normal_max'], '')))
		self._TCTRL_normal_range.SetValue(gmTools.coalesce(test_w_range['val_normal_range'], ''))
		self._TCTRL_norm_ref_group.SetValue(gmTools.coalesce(test_w_range['norm_ref_group'], ''))

	#--------------------------------------------------------
	def __update_clinical_range(self):
		unit = self._PRW_units.GetValue().strip()
		if unit == '':
			return
		if self._PRW_test.GetData() is None:
			return
		for ctrl in [self._TCTRL_target_min, self._TCTRL_target_max, self._TCTRL_target_range]:
			if ctrl.GetValue().strip() != '':
				return
		tt = self._PRW_test.GetData(as_instance = True)
		test_w_range = tt.get_temporally_closest_target_range (
			unit,
			gmPerson.gmCurrentPatient().ID,
			timestamp = self._DPRW_evaluated.GetData().get_pydt()
		)
		if test_w_range is None:
			return
		self._TCTRL_target_min.SetValue(str(gmTools.coalesce(test_w_range['val_target_min'], '')))
		self._TCTRL_target_max.SetValue(str(gmTools.coalesce(test_w_range['val_target_max'], '')))
		self._TCTRL_target_range.SetValue(gmTools.coalesce(test_w_range['val_target_range'], ''))

	#--------------------------------------------------------
	def __refresh_loinc_info(self):

		self._TCTRL_loinc.SetValue('')

		if self._PRW_test.GetData() is None:
			return

		tt = self._PRW_test.GetData(as_instance = True)

		if tt['loinc'] is None:
			return

		info = gmLOINC.loinc2term(loinc = tt['loinc'])
		if len(info) == 0:
			self._TCTRL_loinc.SetValue('')
			return

		self._TCTRL_loinc.SetValue('%s: %s' % (tt['loinc'], info[0]))

	#--------------------------------------------------------
	def __refresh_previous_value(self):
		self._TCTRL_previous_value.SetValue('')
		# it doesn't make much sense to show the most
		# recent value when editing an existing one
		if self.data is not None:
			return

		if self._PRW_test.GetData() is None:
			return

		tt = self._PRW_test.GetData(as_instance = True)
		most_recent_results = tt.get_most_recent_results (
			max_no_of_results = 1,
			patient = gmPerson.gmCurrentPatient().ID
		)
		if len(most_recent_results) == 0:
			return

		most_recent = most_recent_results[0]
		self._TCTRL_previous_value.SetValue(_('%s ago: %s%s%s - %s%s') % (
			gmDateTime.format_interval_medically(gmDateTime.pydt_now_here() - most_recent['clin_when']),
			most_recent['unified_val'],
			most_recent['val_unit'],
			gmTools.coalesce(most_recent['abnormality_indicator'], '', ' (%s)'),
			most_recent['abbrev_tt'],
			gmTools.coalesce(most_recent.formatted_range, '', ' [%s]')
		))
		self._TCTRL_previous_value.SetToolTip(most_recent.format (
			with_review = True,
			with_evaluation = False,
			with_ranges = True,
			with_episode = True,
			with_type_details=True
		))

#================================================================
# measurement type handling
#================================================================
def pick_measurement_types(parent=None, msg=None, right_column=None, picks=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	if msg is None:
		msg = _('Pick the relevant measurement types.')

	if right_column is None:
		right_columns = [_('Picked')]
	else:
		right_columns = [right_column]

	picker = gmListWidgets.cItemPickerDlg(parent, -1, msg = msg)
	picker.set_columns(columns = [_('Known measurement types')], columns_right = right_columns)
	types = gmPathLab.get_measurement_types(order_by = 'unified_abbrev')
	picker.set_choices (
		choices = [
			'%s: %s%s' % (
				t['unified_abbrev'],
				t['unified_name'],
				gmTools.coalesce(t['name_org'], '', ' (%s)')
			)
			for t in types
		],
		data = types
	)
	if picks is not None:
		picker.set_picks (
			picks = [
				'%s: %s%s' % (
					p['unified_abbrev'],
					p['unified_name'],
					gmTools.coalesce(p['name_org'], '', ' (%s)')
				)
				for p in picks
			],
			data = picks
		)
	result = picker.ShowModal()

	if result == wx.ID_CANCEL:
		picker.DestroyLater()
		return None

	picks = picker.picks
	picker.DestroyLater()
	return picks

#----------------------------------------------------------------
def manage_measurement_types(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#------------------------------------------------------------
	def edit(test_type=None):
		ea = cMeasurementTypeEAPnl(parent, -1, type = test_type)
		dlg = gmEditArea.cGenericEditAreaDlg2 (
			parent = parent,
			id = -1,
			edit_area = ea,
			single_entry = gmTools.bool2subst((test_type is None), False, True)
		)
		dlg.SetTitle(gmTools.coalesce(test_type, _('Adding measurement type'), _('Editing measurement type')))

		if dlg.ShowModal() == wx.ID_OK:
			dlg.DestroyLater()
			return True

		dlg.DestroyLater()
		return False

	#------------------------------------------------------------
	def delete(measurement_type):
		if measurement_type.in_use:
			gmDispatcher.send (
				signal = 'statustext',
				beep = True,
				msg = _('Cannot delete measurement type [%s (%s)] because it is in use.') % (measurement_type['name'], measurement_type['abbrev'])
			)
			return False
		gmPathLab.delete_measurement_type(measurement_type = measurement_type['pk_test_type'])
		return True

	#------------------------------------------------------------
	def get_tooltip(test_type):
		return test_type.format()

	#------------------------------------------------------------
	def manage_aggregates(test_type):
		manage_meta_test_types(parent = parent)
		return False

	#------------------------------------------------------------
	def manage_panels_of_type(test_type):
		if test_type['loinc'] is None:
			return False
		all_panels = gmPathLab.get_test_panels(order_by = 'description')
		curr_panels = test_type.test_panels
		if curr_panels is None:
			curr_panels = []
		panel_candidates = [ p for p in all_panels if p['pk_test_panel'] not in [
			c_pnl['pk_test_panel'] for c_pnl in curr_panels
		] ]
		picker = gmListWidgets.cItemPickerDlg(parent, -1, title = 'Panels with [%s]' % test_type['abbrev'])
		picker.set_columns(['Panels available'], ['Panels [%s] is to be on' % test_type['abbrev']])
		picker.set_choices (
			choices = [ u'%s (%s)' % (c['description'], gmTools.coalesce(c['comment'], '')) for c in panel_candidates ],
			data = panel_candidates
		)
		picker.set_picks (
			picks = [ u'%s (%s)' % (c['description'], gmTools.coalesce(c['comment'], '')) for c in curr_panels ],
			data = curr_panels
		)
		exit_type = picker.ShowModal()
		if exit_type == wx.ID_CANCEL:
			return False

		# add picked panels which aren't currently in the panel list
		panels2add = [ p for p in picker.picks if p['pk_test_panel'] not in [
			c_pnl['pk_test_panel'] for c_pnl in curr_panels
		] ]
		# remove unpicked panels off the current panel list
		panels2remove = [ p for p in curr_panels if p['pk_test_panel'] not in [
			picked_pnl['pk_test_panel'] for picked_pnl in picker.picks
		] ]
		for new_panel in panels2add:
			new_panel.add_loinc(test_type['loinc'])
		for stale_panel in panels2remove:
			stale_panel.remove_loinc(test_type['loinc'])

		return True

	#------------------------------------------------------------
	def refresh(lctrl):
		mtypes = gmPathLab.get_measurement_types(order_by = 'name, abbrev')
		items = [ [
			m['abbrev'],
			m['name'],
			gmTools.coalesce(m['reference_unit'], ''),
			gmTools.coalesce(m['loinc'], ''),
			gmTools.coalesce(m['comment_type'], ''),
			gmTools.coalesce(m['name_org'], '?'),
			gmTools.coalesce(m['comment_org'], ''),
			m['pk_test_type']
		] for m in mtypes ]
		lctrl.set_string_items(items)
		lctrl.set_data(mtypes)

	#------------------------------------------------------------
	gmListWidgets.get_choices_from_list (
		parent = parent,
		caption = _('Measurement types.'),
		columns = [ _('Abbrev'), _('Name'), _('Unit'), _('LOINC'), _('Comment'), _('Org'), _('Comment'), '#' ],
		single_selection = True,
		refresh_callback = refresh,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete,
		list_tooltip_callback = get_tooltip,
		left_extra_button = (_('%s &Aggregate') % gmTools.u_sum, _('Manage aggregations (%s) of tests into groups.') % gmTools.u_sum, manage_aggregates),
		middle_extra_button = (_('Select panels'), _('Select panels the focussed test type is to belong to.'), manage_panels_of_type)
	)

#----------------------------------------------------------------
class cMeasurementTypePhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):

		query = """
SELECT DISTINCT ON (field_label)
	pk_test_type AS data,
	name
		|| ' ('
		|| coalesce (
			(SELECT unit || ' @ ' || organization FROM clin.v_test_orgs c_vto WHERE c_vto.pk_test_org = c_vtt.pk_test_org),
			'%(in_house)s'
			)
		|| ')'
	AS field_label,
	name
		|| ' ('
		|| abbrev || ', '
		|| coalesce(abbrev_meta || ': ' || name_meta || ', ', '')
		|| coalesce (
			(SELECT unit || ' @ ' || organization FROM clin.v_test_orgs c_vto WHERE c_vto.pk_test_org = c_vtt.pk_test_org),
			'%(in_house)s'
			)
		|| ')'
	AS list_label
FROM
	clin.v_test_types c_vtt
WHERE
	abbrev_meta %%(fragment_condition)s
		OR
	name_meta %%(fragment_condition)s
		OR
	abbrev %%(fragment_condition)s
		OR
	name %%(fragment_condition)s
ORDER BY field_label
LIMIT 50""" % {'in_house': _('generic / in house lab')}

		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 2, 4)
		mp.word_separators = '[ \t:@]+'
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.matcher = mp
		self.SetToolTip(_('Select the type of measurement.'))
		self.selection_only = False

	#------------------------------------------------------------
	def _data2instance(self):
		if self.GetData() is None:
			return None

		return gmPathLab.cMeasurementType(aPK_obj = self.GetData())

	#------------------------------------------------------------
	def set_from_instance(self, instance):
		lab = gmPathLab.cTestOrg(aPK_obj = instance['pk_test_org'])
		field_label = '%s (%s @ %s)' % (
			instance['name'],
			lab['unit'],
			lab['organization']
		)
		return self.SetText(value = field_label, data = instance['pk_test_type'])

	#------------------------------------------------------------
	def set_from_pk(self, pk):
		return self.set_from_instance(gmPathLab.cMeasurementType(aPK_obj = pk))

	#---------------------------------------------------------
	def SetData(self, data=None):
		return self.set_from_pk(pk = data)

#----------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgMeasurementTypeEAPnl

class cMeasurementTypeEAPnl(wxgMeasurementTypeEAPnl.wxgMeasurementTypeEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['type']
			del kwargs['type']
		except KeyError:
			data = None

		wxgMeasurementTypeEAPnl.wxgMeasurementTypeEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)
		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		self.__init_ui()

	#----------------------------------------------------------------
	def __init_ui(self):

		# name phraseweel
		query = """
select distinct on (name)
	pk,
	name
from clin.test_type
where
	name %(fragment_condition)s
order by name
limit 50"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 2, 4)
		self._PRW_name.matcher = mp
		self._PRW_name.selection_only = False
		self._PRW_name.add_callback_on_lose_focus(callback = self._on_name_lost_focus)

		# abbreviation
		query = """
select distinct on (abbrev)
	pk,
	abbrev
from clin.test_type
where
	abbrev %(fragment_condition)s
order by abbrev
limit 50"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 2, 3)
		self._PRW_abbrev.matcher = mp
		self._PRW_abbrev.selection_only = False

		# unit
		self._PRW_reference_unit.selection_only = False

		# loinc
		mp = gmLOINC.cLOINCMatchProvider()
		mp.setThresholds(1, 2, 4)
		#mp.print_queries = True
		#mp.word_separators = '[ \t:@]+'
		self._PRW_loinc.matcher = mp
		self._PRW_loinc.selection_only = False
		self._PRW_loinc.add_callback_on_lose_focus(callback = self._on_loinc_lost_focus)

	#----------------------------------------------------------------
	def _on_name_lost_focus(self):

		test = self._PRW_name.GetValue().strip()

		if test == '':
			self._PRW_reference_unit.unset_context(context = 'test_name')
			return

		self._PRW_reference_unit.set_context(context = 'test_name', val = test)

	#----------------------------------------------------------------
	def _on_loinc_lost_focus(self):
		loinc = self._PRW_loinc.GetData()

		if loinc is None:
			self._TCTRL_loinc_info.SetValue('')
			self._PRW_reference_unit.unset_context(context = 'loinc')
			return

		self._PRW_reference_unit.set_context(context = 'loinc', val = loinc)

		info = gmLOINC.loinc2term(loinc = loinc)
		if len(info) == 0:
			self._TCTRL_loinc_info.SetValue('')
			return

		self._TCTRL_loinc_info.SetValue(info[0])

	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):

		has_errors = False
		for field in [self._PRW_name, self._PRW_abbrev, self._PRW_reference_unit]:
			if field.GetValue().strip() in ['', None]:
				has_errors = True
				field.display_as_valid(valid = False)
			else:
				field.display_as_valid(valid = True)
			field.Refresh()

		return (not has_errors)

	#----------------------------------------------------------------
	def _save_as_new(self):

		pk_org = self._PRW_test_org.GetData()
		if pk_org is None:
			pk_org = gmPathLab.create_test_org (
				name = gmTools.none_if(self._PRW_test_org.GetValue().strip(), '')
			)['pk_test_org']

		tt = gmPathLab.create_measurement_type (
			lab = pk_org,
			abbrev = self._PRW_abbrev.GetValue().strip(),
			name = self._PRW_name.GetValue().strip(),
			unit = gmTools.coalesce (
				self._PRW_reference_unit.GetData(),
				self._PRW_reference_unit.GetValue()
			).strip()
		)
		if self._PRW_loinc.GetData() is not None:
			tt['loinc'] = gmTools.none_if(self._PRW_loinc.GetData().strip(), '')
		else:
			tt['loinc'] = gmTools.none_if(self._PRW_loinc.GetValue().strip(), '')
		tt['comment_type'] = gmTools.none_if(self._TCTRL_comment_type.GetValue().strip(), '')
		tt['pk_meta_test_type'] = self._PRW_meta_type.GetData()

		tt.save()

		self.data = tt

		return True
	#----------------------------------------------------------------
	def _save_as_update(self):

		pk_org = self._PRW_test_org.GetData()
		if pk_org is None:
			pk_org = gmPathLab.create_test_org (
				name = gmTools.none_if(self._PRW_test_org.GetValue().strip(), '')
			)['pk_test_org']

		self.data['pk_test_org'] = pk_org
		self.data['abbrev'] = self._PRW_abbrev.GetValue().strip()
		self.data['name'] = self._PRW_name.GetValue().strip()
		self.data['reference_unit'] = gmTools.coalesce (
			self._PRW_reference_unit.GetData(),
			self._PRW_reference_unit.GetValue()
		).strip()
		old_loinc = self.data['loinc']
		if self._PRW_loinc.GetData() is not None:
			self.data['loinc'] = gmTools.none_if(self._PRW_loinc.GetData().strip(), '')
		else:
			self.data['loinc'] = gmTools.none_if(self._PRW_loinc.GetValue().strip(), '')
		new_loinc = self.data['loinc']
		self.data['comment_type'] = gmTools.none_if(self._TCTRL_comment_type.GetValue().strip(), '')
		self.data['pk_meta_test_type'] = self._PRW_meta_type.GetData()
		self.data.save()

		# was it, AND can it be, on any panel ?
		if None not in [old_loinc, new_loinc]:
			# would it risk being dropped from any panel ?
			if new_loinc != old_loinc:
				for panel in gmPathLab.get_test_panels(loincs = [old_loinc]):
					pnl_loincs = panel.included_loincs
					if new_loinc not in pnl_loincs:
						pnl_loincs.append(new_loinc)
						panel.included_loincs = pnl_loincs
					# do not remove old_loinc as it may sit on another
					# test type which we haven't removed it from yet

		return True

	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_name.SetText('', None, True)
		self._on_name_lost_focus()
		self._PRW_abbrev.SetText('', None, True)
		self._PRW_reference_unit.SetText('', None, True)
		self._PRW_loinc.SetText('', None, True)
		self._on_loinc_lost_focus()
		self._TCTRL_comment_type.SetValue('')
		self._PRW_test_org.SetText('', None, True)
		self._PRW_meta_type.SetText('', None, True)

		self._PRW_name.SetFocus()
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_name.SetText(self.data['name'], self.data['name'], True)
		self._on_name_lost_focus()
		self._PRW_abbrev.SetText(self.data['abbrev'], self.data['abbrev'], True)
		self._PRW_reference_unit.SetText (
			gmTools.coalesce(self.data['reference_unit'], ''),
			self.data['reference_unit'],
			True
		)
		self._PRW_loinc.SetText (
			gmTools.coalesce(self.data['loinc'], ''),
			self.data['loinc'],
			True
		)
		self._on_loinc_lost_focus()
		self._TCTRL_comment_type.SetValue(gmTools.coalesce(self.data['comment_type'], ''))
		self._PRW_test_org.SetText (
			gmTools.coalesce(self.data['pk_test_org'], '', self.data['name_org']),
			self.data['pk_test_org'],
			True
		)
		if self.data['pk_meta_test_type'] is None:
			self._PRW_meta_type.SetText('', None, True)
		else:
			self._PRW_meta_type.SetText('%s: %s' % (self.data['abbrev_meta'], self.data['name_meta']), self.data['pk_meta_test_type'], True)

		self._PRW_name.SetFocus()
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()
		self._PRW_test_org.SetText (
			gmTools.coalesce(self.data['pk_test_org'], '', self.data['name_org']),
			self.data['pk_test_org'],
			True
		)
		self._PRW_name.SetFocus()

#================================================================
_SQL_units_from_test_results = """
	-- via clin.v_test_results.pk_type (for types already used in results)
	SELECT
		val_unit AS data,
		val_unit AS field_label,
		val_unit || ' (' || name_tt || ')' AS list_label,
		1 AS rank
	FROM
		clin.v_test_results
	WHERE
		(
			val_unit %(fragment_condition)s
				OR
			reference_unit %(fragment_condition)s
		)
		%(ctxt_type_pk)s
		%(ctxt_test_name)s
"""

_SQL_units_from_test_types = """
	-- via clin.test_type (for types not yet used in results)
	SELECT
		reference_unit AS data,
		reference_unit AS field_label,
		reference_unit || ' (' || name || ')' AS list_label,
		2 AS rank
	FROM
		clin.test_type
	WHERE
		reference_unit %(fragment_condition)s
		%(ctxt_ctt)s
"""

_SQL_units_from_loinc_ipcc = """
	-- via ref.loinc.ipcc_units
	SELECT
		ipcc_units AS data,
		ipcc_units AS field_label,
		ipcc_units || ' (LOINC.ipcc: ' || term || ')' AS list_label,
		3 AS rank
	FROM
		ref.loinc
	WHERE
		ipcc_units %(fragment_condition)s
		%(ctxt_loinc)s
		%(ctxt_loinc_term)s
"""

_SQL_units_from_loinc_submitted = """
	-- via ref.loinc.submitted_units
	SELECT
		submitted_units AS data,
		submitted_units AS field_label,
		submitted_units || ' (LOINC.submitted:' || term || ')' AS list_label,
		3 AS rank
	FROM
		ref.loinc
	WHERE
		submitted_units %(fragment_condition)s
		%(ctxt_loinc)s
		%(ctxt_loinc_term)s
"""

_SQL_units_from_loinc_example = """
	-- via ref.loinc.example_units
	SELECT
		example_units AS data,
		example_units AS field_label,
		example_units || ' (LOINC.example: ' || term || ')' AS list_label,
		3 AS rank
	FROM
		ref.loinc
	WHERE
		example_units %(fragment_condition)s
		%(ctxt_loinc)s
		%(ctxt_loinc_term)s
"""

_SQL_units_from_substance_doses = """
	-- via ref.v_substance_doses.unit
	SELECT
		unit AS data,
		unit AS field_label,
		unit || ' (' || substance || ')' AS list_label,
		2 AS rank
	FROM
		ref.v_substance_doses
	WHERE
		unit %(fragment_condition)s
		%(ctxt_substance)s
"""

_SQL_units_from_substance_doses2 = """
	-- via ref.v_substance_doses.dose_unit
	SELECT
		dose_unit AS data,
		dose_unit AS field_label,
		dose_unit || ' (' || substance || ')' AS list_label,
		2 AS rank
	FROM
		ref.v_substance_doses
	WHERE
		dose_unit %(fragment_condition)s
		%(ctxt_substance)s
"""

#----------------------------------------------------------------
class cUnitPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):

		query = """
SELECT DISTINCT ON (data)
	data,
	field_label,
	list_label
FROM (

	SELECT
		data,
		field_label,
		list_label,
		rank
	FROM (
		(%s) UNION ALL
		(%s) UNION ALL
		(%s) UNION ALL
		(%s) UNION ALL
		(%s) UNION ALL
		(%s) UNION ALL
		(%s)
	) AS all_matching_units
	WHERE data IS NOT NULL
	ORDER BY rank, list_label

) AS ranked_matching_units
LIMIT 50""" % (
			_SQL_units_from_test_results,
			_SQL_units_from_test_types,
			_SQL_units_from_loinc_ipcc,
			_SQL_units_from_loinc_submitted,
			_SQL_units_from_loinc_example,
			_SQL_units_from_substance_doses,
			_SQL_units_from_substance_doses2
		)

		ctxt = {
			'ctxt_type_pk': {
				'where_part': 'AND pk_test_type = %(pk_type)s',
				'placeholder': 'pk_type'
			},
			'ctxt_test_name': {
				'where_part': 'AND %(test_name)s IN (name_tt, name_meta, abbrev_meta)',
				'placeholder': 'test_name'
			},
			'ctxt_ctt': {
				'where_part': 'AND %(test_name)s IN (name, abbrev)',
				'placeholder': 'test_name'
			},
			'ctxt_loinc': {
				'where_part': 'AND code = %(loinc)s',
				'placeholder': 'loinc'
			},
			'ctxt_loinc_term': {
				'where_part': 'AND term ~* %(test_name)s',
				'placeholder': 'test_name'
			},
			'ctxt_substance': {
				'where_part': 'AND description ~* %(substance)s',
				'placeholder': 'substance'
			}
		}

		mp = gmMatchProvider.cMatchProvider_SQL2(queries = query, context = ctxt)
		mp.setThresholds(1, 2, 4)
		#mp.print_queries = True
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.matcher = mp
		self.SetToolTip(_('Select the desired unit for the amount or measurement.'))
		self.selection_only = False
		self.phrase_separators = '[;|]+'

#================================================================

#================================================================
class cTestResultIndicatorPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):

		query = """
select distinct abnormality_indicator,
	abnormality_indicator, abnormality_indicator
from clin.v_test_results
where
	abnormality_indicator %(fragment_condition)s
order by abnormality_indicator
limit 25"""

		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 1, 2)
		mp.ignored_chars = "[.'\\\[\]#$%_]+" + '"'
		mp.word_separators = '[ \t&:]+'
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
		self.matcher = mp
		self.SetToolTip(_('Select an indicator for the level of abnormality.'))
		self.selection_only = False

#================================================================
# measurement org widgets / functions
#----------------------------------------------------------------
def edit_measurement_org(parent=None, org=None):
	ea = cMeasurementOrgEAPnl(parent, -1)
	ea.data = org
	ea.mode = gmTools.coalesce(org, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2(parent, -1, edit_area = ea)
	dlg.SetTitle(gmTools.coalesce(org, _('Adding new diagnostic org'), _('Editing diagnostic org')))
	if dlg.ShowModal() == wx.ID_OK:
		dlg.DestroyLater()
		return True
	dlg.DestroyLater()
	return False
#----------------------------------------------------------------
def manage_measurement_orgs(parent=None, msg=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#------------------------------------------------------------
	def edit(org=None):
		return edit_measurement_org(parent = parent, org = org)
	#------------------------------------------------------------
	def refresh(lctrl):
		orgs = gmPathLab.get_test_orgs()
		lctrl.set_string_items ([
			(o['unit'], o['organization'], gmTools.coalesce(o['test_org_contact'], ''), gmTools.coalesce(o['comment'], ''), o['pk_test_org'])
			for o in orgs
		])
		lctrl.set_data(orgs)
	#------------------------------------------------------------
	def delete(test_org):
		gmPathLab.delete_test_org(test_org = test_org['pk_test_org'])
		return True
	#------------------------------------------------------------
	if msg is None:
		msg = _('\nThese are the diagnostic orgs (path labs etc) currently defined in GNUmed.\n\n')

	return gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = msg,
		caption = _('Showing diagnostic orgs.'),
		columns = [_('Name'), _('Organization'), _('Contact'), _('Comment'), '#'],
		single_selection = True,
		refresh_callback = refresh,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete
	)

#----------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgMeasurementOrgEAPnl

class cMeasurementOrgEAPnl(wxgMeasurementOrgEAPnl.wxgMeasurementOrgEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['org']
			del kwargs['org']
		except KeyError:
			data = None

		wxgMeasurementOrgEAPnl.wxgMeasurementOrgEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		#self.__init_ui()
	#----------------------------------------------------------------
#	def __init_ui(self):
#		# adjust phrasewheels etc
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):
		has_errors = False
		if self._PRW_org_unit.GetData() is None:
			if self._PRW_org_unit.GetValue().strip() == '':
				has_errors = True
				self._PRW_org_unit.display_as_valid(valid = False)
			else:
				self._PRW_org_unit.display_as_valid(valid = True)
		else:
			self._PRW_org_unit.display_as_valid(valid = True)

		return (not has_errors)
	#----------------------------------------------------------------
	def _save_as_new(self):
		data = gmPathLab.create_test_org (
			name = self._PRW_org_unit.GetValue().strip(),
			comment = self._TCTRL_comment.GetValue().strip(),
			pk_org_unit = self._PRW_org_unit.GetData()
		)
		data['test_org_contact'] = self._TCTRL_contact.GetValue().strip()
		data.save()
		self.data = data
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):
		# get or create the org unit
		name = self._PRW_org_unit.GetValue().strip()
		org = gmOrganization.org_exists(organization = name)
		if org is None:
			org = gmOrganization.create_org (
				organization = name,
				category = 'Laboratory'
			)
		org_unit = gmOrganization.create_org_unit (
			pk_organization = org['pk_org'],
			unit = name
		)
		# update test_org fields
		self.data['pk_org_unit'] = org_unit['pk_org_unit']
		self.data['test_org_contact'] = self._TCTRL_contact.GetValue().strip()
		self.data['comment'] = self._TCTRL_comment.GetValue().strip()
		self.data.save()
		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_org_unit.SetText(value = '', data = None)
		self._TCTRL_contact.SetValue('')
		self._TCTRL_comment.SetValue('')
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_org_unit.SetText(value = self.data['unit'], data = self.data['pk_org_unit'])
		self._TCTRL_contact.SetValue(gmTools.coalesce(self.data['test_org_contact'], ''))
		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], ''))
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()
	#----------------------------------------------------------------
	def _on_manage_orgs_button_pressed(self, event):
		gmOrganizationWidgets.manage_orgs(parent = self)

#----------------------------------------------------------------
class cMeasurementOrgPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):

		query = """
SELECT DISTINCT ON (list_label)
	pk_test_org AS data,
	unit || ' (' || organization || ')' AS field_label,
	unit || ' @ ' || organization AS list_label
FROM clin.v_test_orgs
WHERE
	unit %(fragment_condition)s
		OR
	organization %(fragment_condition)s
ORDER BY list_label
LIMIT 50"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 2, 4)
		#mp.word_separators = '[ \t:@]+'
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.matcher = mp
		self.SetToolTip(_('The name of the path lab/diagnostic organisation.'))
		self.selection_only = False
	#------------------------------------------------------------
	def _create_data(self):
		if self.GetData() is not None:
			_log.debug('data already set, not creating')
			return

		if self.GetValue().strip() == '':
			_log.debug('cannot create new lab, missing name')
			return

		lab = gmPathLab.create_test_org(name = self.GetValue().strip())
		self.SetText(value = lab['unit'], data = lab['pk_test_org'])
		return
	#------------------------------------------------------------
	def _data2instance(self):
		return gmPathLab.cTestOrg(aPK_obj = self.GetData())

#================================================================
# Meta test type widgets
#----------------------------------------------------------------
def edit_meta_test_type(parent=None, meta_test_type=None):
	ea = cMetaTestTypeEAPnl(parent, -1)
	ea.data = meta_test_type
	ea.mode = gmTools.coalesce(meta_test_type, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2 (
		parent = parent,
		id = -1,
		edit_area = ea,
		single_entry = gmTools.bool2subst((meta_test_type is None), False, True)
	)
	dlg.SetTitle(gmTools.coalesce(meta_test_type, _('Adding new meta test type'), _('Editing meta test type')))
	if dlg.ShowModal() == wx.ID_OK:
		dlg.DestroyLater()
		return True
	dlg.DestroyLater()
	return False

#----------------------------------------------------------------
def manage_meta_test_types(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#------------------------------------------------------------
	def edit(meta_test_type=None):
		return edit_meta_test_type(parent = parent, meta_test_type = meta_test_type)
	#------------------------------------------------------------
	def delete(meta_test_type):
		gmPathLab.delete_meta_type(meta_type = meta_test_type['pk'])
		return True
	#----------------------------------------
	def get_tooltip(data):
		if data is None:
			return None
		return data.format(with_tests = True)
	#------------------------------------------------------------
	def refresh(lctrl):
		mtts = gmPathLab.get_meta_test_types()
		items = [ [
			m['abbrev'],
			m['name'],
			gmTools.coalesce(m['loinc'], ''),
			gmTools.coalesce(m['comment'], ''),
			m['pk']
		] for m in mtts ]
		lctrl.set_string_items(items)
		lctrl.set_data(mtts)
	#----------------------------------------

	msg = _(
		'\n'
		'These are the meta test types currently defined in GNUmed.\n'
		'\n'
		'Meta test types allow you to aggregate several actual test types used\n'
		'by pathology labs into one logical type.\n'
		'\n'
		'This is useful for grouping together results of tests which come under\n'
		'different names but really are the same thing. This often happens when\n'
		'you switch labs or the lab starts using another test method.\n'
	)

	gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = msg,
		caption = _('Showing meta test types.'),
		columns = [_('Abbrev'), _('Name'), _('LOINC'), _('Comment'), '#'],
		single_selection = True,
		list_tooltip_callback = get_tooltip,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete,
		refresh_callback = refresh
	)

#----------------------------------------------------------------
class cMetaTestTypePRW(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):

		query = """
SELECT DISTINCT ON (field_label)
	c_mtt.pk
		AS data,
	c_mtt.abbrev || ': ' || name
		AS field_label,
	c_mtt.abbrev || ': ' || name
		||	coalesce (
				' (' || c_mtt.comment || ')',
				''
			)
		||	coalesce (
				', LOINC: ' || c_mtt.loinc,
				''
			)
	AS list_label
FROM
	clin.meta_test_type c_mtt
WHERE
	abbrev %(fragment_condition)s
		OR
	name %(fragment_condition)s
		OR
	loinc %(fragment_condition)s
ORDER BY field_label
LIMIT 50"""

		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 2, 4)
		mp.word_separators = '[ \t:@]+'
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.matcher = mp
		self.SetToolTip(_('Select the meta test type.'))
		self.selection_only = True
	#------------------------------------------------------------
	def _data2instance(self):
		if self.GetData() is None:
			return None

		return gmPathLab.cMetaTestType(aPK_obj = self.GetData())

#----------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgMetaTestTypeEAPnl

class cMetaTestTypeEAPnl(wxgMetaTestTypeEAPnl.wxgMetaTestTypeEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['meta_test_type']
			del kwargs['meta_test_type']
		except KeyError:
			data = None

		wxgMetaTestTypeEAPnl.wxgMetaTestTypeEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		# Code using this mixin should set mode and data
		# after instantiating the class:
		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		self.__init_ui()
	#----------------------------------------------------------------
	def __init_ui(self):
		# loinc
		mp = gmLOINC.cLOINCMatchProvider()
		mp.setThresholds(1, 2, 4)
		#mp.print_queries = True
		#mp.word_separators = '[ \t:@]+'
		self._PRW_loinc.matcher = mp
		self._PRW_loinc.selection_only = False
		self._PRW_loinc.add_callback_on_lose_focus(callback = self._on_loinc_lost_focus)

	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):

		validity = True

		if self._PRW_abbreviation.GetValue().strip() == '':
			validity = False
			self._PRW_abbreviation.display_as_valid(False)
			self.StatusText = _('Missing abbreviation for meta test type.')
			self._PRW_abbreviation.SetFocus()
		else:
			self._PRW_abbreviation.display_as_valid(True)

		if self._PRW_name.GetValue().strip() == '':
			validity = False
			self._PRW_name.display_as_valid(False)
			self.StatusText = _('Missing name for meta test type.')
			self._PRW_name.SetFocus()
		else:
			self._PRW_name.display_as_valid(True)

		return validity
	#----------------------------------------------------------------
	def _save_as_new(self):

		# save the data as a new instance
		data = gmPathLab.create_meta_type (
			name = self._PRW_name.GetValue().strip(),
			abbreviation = self._PRW_abbreviation.GetValue().strip(),
			return_existing = False
		)
		if data is None:
			self.StatusText = _('This meta test type already exists.')
			return False
		data['loinc'] = self._PRW_loinc.GetData()
		data['comment'] = self._TCTRL_comment.GetValue().strip()
		data.save()
		self.data = data
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):
		self.data['name'] = self._PRW_name.GetValue().strip()
		self.data['abbrev'] = self._PRW_abbreviation.GetValue().strip()
		self.data['loinc'] = self._PRW_loinc.GetData()
		self.data['comment'] = self._TCTRL_comment.GetValue().strip()
		self.data.save()
		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_name.SetText('', None)
		self._PRW_abbreviation.SetText('', None)
		self._PRW_loinc.SetText('', None)
		self._TCTRL_loinc_info.SetValue('')
		self._TCTRL_comment.SetValue('')
		self._LBL_member_detail.SetLabel('')

		self._PRW_name.SetFocus()
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_name.SetText(self.data['name'], self.data['pk'])
		self._PRW_abbreviation.SetText(self.data['abbrev'], self.data['abbrev'])
		self._PRW_loinc.SetText(gmTools.coalesce(self.data['loinc'], ''), self.data['loinc'])
		self.__refresh_loinc_info()
		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], ''))
		self.__refresh_members()

		self._PRW_name.SetFocus()
	#----------------------------------------------------------------
	# event handlers
	#----------------------------------------------------------------
	def _on_loinc_lost_focus(self):
		self.__refresh_loinc_info()
	#----------------------------------------------------------------
	# internal helpers
	#----------------------------------------------------------------
	def __refresh_loinc_info(self):
		loinc = self._PRW_loinc.GetData()

		if loinc is None:
			self._TCTRL_loinc_info.SetValue('')
			return

		info = gmLOINC.loinc2term(loinc = loinc)
		if len(info) == 0:
			self._TCTRL_loinc_info.SetValue('')
			return

		self._TCTRL_loinc_info.SetValue(info[0])
	#----------------------------------------------------------------
	def __refresh_members(self):
		if self.data is None:
			self._LBL_member_detail.SetLabel('')
			return

		types = self.data.included_test_types
		if len(types) == 0:
			self._LBL_member_detail.SetLabel('')
			return

		lines = []
		for tt in types:
			lines.append('%s (%s%s) [#%s] @ %s' % (
				tt['name'],
				tt['abbrev'],
				gmTools.coalesce(tt['loinc'], '', ', LOINC: %s'),
				tt['pk_test_type'],
				tt['name_org']
			))
		self._LBL_member_detail.SetLabel('\n'.join(lines))

#================================================================
# test panel handling
#================================================================
def edit_test_panel(parent=None, test_panel=None):
	ea = cTestPanelEAPnl(parent, -1)
	ea.data = test_panel
	ea.mode = gmTools.coalesce(test_panel, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2 (
		parent = parent,
		id = -1,
		edit_area = ea,
		single_entry = gmTools.bool2subst((test_panel is None), False, True)
	)
	dlg.SetTitle(gmTools.coalesce(test_panel, _('Adding new test panel'), _('Editing test panel')))
	if dlg.ShowModal() == wx.ID_OK:
		dlg.DestroyLater()
		return True
	dlg.DestroyLater()
	return False

#----------------------------------------------------------------
def manage_test_panels(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#------------------------------------------------------------
	def edit(test_panel=None):
		return edit_test_panel(parent = parent, test_panel = test_panel)
	#------------------------------------------------------------
	def delete(test_panel):
		gmPathLab.delete_test_panel(pk = test_panel['pk_test_panel'])
		return True
	#------------------------------------------------------------
	def get_tooltip(test_panel):
		return test_panel.format()
	#------------------------------------------------------------
	def refresh(lctrl):
		panels = gmPathLab.get_test_panels(order_by = 'description')
		items = [ [
			p['description'],
			gmTools.coalesce(p['comment'], ''),
			p['pk_test_panel']
		] for p in panels ]
		lctrl.set_string_items(items)
		lctrl.set_data(panels)
	#------------------------------------------------------------
	gmListWidgets.get_choices_from_list (
		parent = parent,
		caption = 'GNUmed: ' + _('Test panels list'),
		columns = [ _('Name'), _('Comment'), '#' ],
		single_selection = True,
		refresh_callback = refresh,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete,
		list_tooltip_callback = get_tooltip
	)

#----------------------------------------------------------------
class cTestPanelPRW(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = """
SELECT
	pk_test_panel
		AS data,
	description
		AS field_label,
	description
		AS list_label
FROM
	clin.v_test_panels
WHERE
	description %(fragment_condition)s
ORDER BY field_label
LIMIT 30"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 2, 4)
		#mp.word_separators = '[ \t:@]+'
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.matcher = mp
		self.SetToolTip(_('Select a test panel.'))
		self.selection_only = True
	#------------------------------------------------------------
	def _data2instance(self):
		if self.GetData() is None:
			return None
		return gmPathLab.cTestPanel(aPK_obj = self.GetData())
	#------------------------------------------------------------
	def _get_data_tooltip(self):
		if self.GetData() is None:
			return None
		return gmPathLab.cTestPanel(aPK_obj = self.GetData()).format()

#====================================================================
from Gnumed.wxGladeWidgets import wxgTestPanelEAPnl

class cTestPanelEAPnl(wxgTestPanelEAPnl.wxgTestPanelEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['panel']
			del kwargs['panel']
		except KeyError:
			data = None

		wxgTestPanelEAPnl.wxgTestPanelEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.__loincs = None

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		self.__init_ui()

	#----------------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_loincs.set_columns([_('LOINC'), _('Term'), _('Units')])
		self._LCTRL_loincs.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
		#self._LCTRL_loincs.set_resize_column(column = 2)
		self._LCTRL_loincs.delete_callback = self._remove_loincs_from_list
		self.__refresh_loinc_list()

		self._PRW_loinc.final_regex = r'.*'
		self._PRW_loinc.add_callback_on_selection(callback = self._on_loinc_selected)

	#----------------------------------------------------------------
	def __refresh_loinc_list(self):
		self._LCTRL_loincs.remove_items_safely()
		if self.__loincs is None:
			if self.data is None:
				return
			self.__loincs = self.data['loincs']

		items = []
		for loinc in self.__loincs:
			loinc_detail = gmLOINC.loinc2data(loinc = loinc)
			if loinc_detail is None:
				# check for test type with this pseudo loinc
				ttypes = gmPathLab.get_measurement_types(loincs = [loinc])
				if len(ttypes) == 0:
					items.append([loinc, _('LOINC not found'), ''])
				else:
					for tt in ttypes:
						items.append([loinc, _('not a LOINC') + u'; %(name)s @ %(name_org)s [#%(pk_test_type)s]' % tt, ''])
				continue
			items.append ([
				loinc,
				loinc_detail['term'],
				gmTools.coalesce(loinc_detail['example_units'], '', '%s')
			])

		self._LCTRL_loincs.set_string_items(items)
		self._LCTRL_loincs.set_column_widths()

	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):
		validity = True

		if self.__loincs is None:
			if self.data is not None:
				self.__loincs = self.data['loincs']

		if self.__loincs is None:
			# not fatal despite panel being useless
			self.StatusText = _('No LOINC codes selected.')
			self._PRW_loinc.SetFocus()

		if self._TCTRL_description.GetValue().strip() == '':
			validity = False
			self.display_tctrl_as_valid(tctrl = self._TCTRL_description, valid = False)
			self._TCTRL_description.SetFocus()
		else:
			self.display_tctrl_as_valid(tctrl = self._TCTRL_description, valid = True)

		return validity

	#----------------------------------------------------------------
	def _save_as_new(self):
		data = gmPathLab.create_test_panel(description = self._TCTRL_description.GetValue().strip())
		data['comment'] = self._TCTRL_comment.GetValue().strip()
		data.save()
		if self.__loincs is not None:
			data.included_loincs = self.__loincs
		self.data = data
		return True

	#----------------------------------------------------------------
	def _save_as_update(self):
		self.data['description'] = self._TCTRL_description.GetValue().strip()
		self.data['comment'] = self._TCTRL_comment.GetValue().strip()
		self.data.save()
		if self.__loincs is not None:
			self.data.included_loincs = self.__loincs
		return True

	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._TCTRL_description.SetValue('')
		self._TCTRL_comment.SetValue('')
		self._PRW_loinc.SetText('', None)
		self._LBL_loinc.SetLabel('')
		self.__loincs = None
		self.__refresh_loinc_list()

		self._TCTRL_description.SetFocus()

	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()

	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._TCTRL_description.SetValue(self.data['description'])
		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], ''))
		self._PRW_loinc.SetText('', None)
		self._LBL_loinc.SetLabel('')
		self.__loincs = self.data['loincs']
		self.__refresh_loinc_list()

		self._PRW_loinc.SetFocus()

	#----------------------------------------------------------------
	# event handlers
	#----------------------------------------------------------------
	def _on_loinc_selected(self, loinc):
		loinc = self._PRW_loinc.GetData()
		if loinc is None:
			self._LBL_loinc.SetLabel('')
			return
		loinc_detail = gmLOINC.loinc2data(loinc = loinc)
		if loinc_detail is None:
			loinc_str = _('no LOINC details found')
		else:
			loinc_str = '%s: %s%s' % (
				loinc,
				loinc_detail['term'],
				gmTools.coalesce(loinc_detail['example_units'], '', ' (%s)')
			)
		self._LBL_loinc.SetLabel(loinc_str)

	#----------------------------------------------------------------
	def _on_add_loinc_button_pressed(self, event):
		event.Skip()

		loinc = self._PRW_loinc.GetData()
		if loinc is None:
			loinc = self._PRW_loinc.GetValue().strip()
		if loinc.strip() == '':
			return

		if self.__loincs is None:
			self.__loincs = [loinc]
		else:
			if loinc in self.__loincs:
				return
			self.__loincs.append(loinc)

		self.__refresh_loinc_list()
		self._PRW_loinc.SetText('', None)
		self._LBL_loinc.SetLabel('')

		self._PRW_loinc.SetFocus()

	#----------------------------------------------------------------
	def _on_remove_loinc_button_pressed(self, event):
		event.Skip()
		self._remove_loincs_from_list()

	#----------------------------------------------------------------
	def _remove_loincs_from_list(self):
		loincs2remove = self._LCTRL_loincs.selected_item_data
		if loincs2remove is None:
			return
		for loinc in loincs2remove:
			try:
				while True:
					self.__loincs.remove(loinc[0])
			except ValueError:
				pass
		self.__refresh_loinc_list()

#================================================================
# main
#----------------------------------------------------------------
if __name__ == '__main__':

	from Gnumed.pycommon import gmLog2
	from Gnumed.wxpython import gmPatSearchWidgets

	gmI18N.activate_locale()
	gmI18N.install_domain()
	gmDateTime.init()

	#------------------------------------------------------------
	def test_grid():
		pat = gmPersonSearch.ask_for_patient()
		app = wx.PyWidgetTester(size = (500, 300))
		lab_grid = cMeasurementsGrid(app.frame, -1)
		lab_grid.patient = pat
		app.frame.Show()
		app.MainLoop()
	#------------------------------------------------------------
	def test_test_ea_pnl():
		pat = gmPersonSearch.ask_for_patient()
		gmPatSearchWidgets.set_active_patient(patient=pat)
		app = wx.PyWidgetTester(size = (500, 300))
		ea = cMeasurementEditAreaPnl(app.frame, -1)
		app.frame.Show()
		app.MainLoop()
	#------------------------------------------------------------
#	def test_primary_care_vitals_pnl():
#		app = wx.PyWidgetTester(size = (500, 300))
#		pnl = wxgPrimaryCareVitalsInputPnl.wxgPrimaryCareVitalsInputPnl(app.frame, -1)
#		app.frame.Show()
#		app.MainLoop()
	#------------------------------------------------------------
	if (len(sys.argv) > 1) and (sys.argv[1] == 'test'):
		#test_grid()
		test_test_ea_pnl()
		#test_primary_care_vitals_pnl()

#================================================================