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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const io = require('./utility/io')
const log = console.log
const warn = console.warn
const error = console.error
const should_log = false
if (should_log) {
    window.addEventListener('error', (event) => {
        const [a, b, c, d, e] = [1, 2, 3, 4, 5]
        console.log(`message: ${a}`)
        console.log(`source: ${b}`)
        console.log(`lineno: ${c}`)
        console.log(`colno: ${d}`)
        console.log(`error: ${e}`)
    })

    console.log = (data, ...optional_param) => {
        log(data, ...optional_param)
        io.IOLog.saveLogToFile({ data, ...optional_param }, 'log.txt')
    }
    console.warn = (data, ...optional_param) => {
        try {
            warn(data, ...optional_param)
            io.IOLog.saveLogToFile({ data, ...optional_param }, 'warn.txt')
        } catch (e) {
            warn('error while logging: ')
            warn(e)
        }
    }
    console.error = (data, ...optional_param) => {
        error(data, ...optional_param)
        io.IOLog.saveLogToFile({ data, ...optional_param }, 'error.txt')
    }
}

// import {helloHelper} from 'helper.js'
// helloHelper2 = require('./helper.js')
// for organizational proposes
// let g_sdapi_path = 'sdapi'
let g_version = 'v1.2.5'
let g_sd_url = 'http://127.0.0.1:7860'
let g_online_data_url =
    'https://raw.githubusercontent.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/master/utility/online_data.json'
const Enum = require('./enum')
const helper = require('./helper')
const sd_tab = require('./utility/tab/sd')
// let g_sdapi_path = 'sdapi_py_re'
// const sdapi = require(`./${g_sdapi_path}`)
const sdapi = require('./sdapi_py_re')

// const exportHelper = require('./export_png')
const outpaint = require('./outpaint')
const psapi = require('./psapi')
const app = window.require('photoshop').app

const { batchPlay } = require('photoshop').action
const { executeAsModal } = require('photoshop').core
const dialog_box = require('./dialog_box')
// const {entrypoints} = require('uxp')
const html_manip = require('./utility/html_manip')
// const export_png = require('./export_png')
const viewer = require('./viewer')
const selection = require('./selection')
const layer_util = require('./utility/layer')
const sd_options = require('./utility/sdapi/options')
const sd_config = require('./utility/sdapi/config')
const session = require('./utility/session')
const ui = require('./utility/ui')
const preset_util = require('./utility/presets/preset')
const script_horde = require('./utility/sd_scripts/horde')
const prompt_shortcut = require('./utility/sdapi/prompt_shortcut')
const formats = require('uxp').storage.formats
const storage = require('uxp').storage
const shell = require('uxp').shell
const fs = storage.localFileSystem
const horde_native = require('./utility/sdapi/horde_native')

const dummy = require('./utility/dummy')
const general = require('./utility/general')
const thumbnail = require('./thumbnail')
const note = require('./utility/notification')
const sampler_data = require('./utility/sampler')
const settings_tab = require('./utility/tab/settings')
const control_net = require('./utility/tab/control_net')
//load tabs
const history_tab = require('./utility/tab/history_tab')
const image_search_tab = require('./utility/tab/image_search_tab')
const lexica_tab = require('./utility/tab/lexica_tab')
const share_tab = require('./utility/tab/share_tab')
// const ultimate_sd_upscaler = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler')
const ultimate_sd_upscaler_script = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler.bundle')
const scripts = require('./ultimate_sd_upscaler/dist/scripts.bundle')

// const ultimate_sd_upscaler_script_test = require('./ultimate_sd_upscaler/dist/main')

// const {
//     script_args,
//     script_name,
// } = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler')

let g_horde_generator = new horde_native.hordeGenerator()
let g_automatic_status = Enum.AutomaticStatusEnum['Offline']
let g_models_status = false
let g_current_batch_index = 0
//REFACTOR: move to session.js
async function hasSessionSelectionChanged() {
    try {
        const isSelectionActive = await psapi.checkIfSelectionAreaIsActive()
        if (isSelectionActive) {
            const current_selection = isSelectionActive // Note: don't use checkIfSelectionAreaIsActive to return the selection object, change this.

            if (
                await hasSelectionChanged(
                    current_selection,
                    g_generation_session.selectionInfo
                )
            ) {
                return true
            } else {
                //selection has not changed
                return false
            }
        }
    } catch (e) {
        console.warn(e)
        return false
    }
}
//REFACTOR: move to selection.js, add selection mode as attribute (linked to rbSelectionMode event)
async function calcWidthHeightFromSelection() {
    //set the width and height, hrWidth, and hrHeight using selection info and selection mode
    const selection_mode = html_manip.getSelectionMode()
    if (selection_mode === 'ratio') {
        //change (width and height) and (hrWidth, hrHeight) to match the ratio of selection
        const [width, height, hr_width, hr_height] =
            await selection.selectionToFinalWidthHeight()

        html_manip.autoFillInWidth(width)
        html_manip.autoFillInHeight(height)
        html_manip.autoFillInHRWidth(hr_width)
        html_manip.autoFillInHRHeight(hr_height)
    } else if (selection_mode === 'precise') {
        const selectionInfo = await psapi.getSelectionInfoExe()
        const [width, height, hr_width, hr_height] = [
            selectionInfo.width,
            selectionInfo.height,
            0,
            0,
        ]
        html_manip.autoFillInWidth(width)
        html_manip.autoFillInHeight(height)
    }
}
//REFACTOR: rename to newSelectionEventHandler and move to session.js
const eventHandler = async (event, descriptor) => {
    try {
        console.log(event, descriptor)

        const isSelectionActive = await psapi.checkIfSelectionAreaIsActive()
        if (isSelectionActive) {
            const current_selection = isSelectionActive // Note: don't use checkIfSelectionAreaIsActive to return the selection object, change this.

            await calcWidthHeightFromSelection()

            // console.log(` (${final_width}* ${final_height})/(${current_selection.width} * ${current_selection.height})`)
            // console.log("detail density: ",(final_width* final_height)/(current_selection.width * current_selection.height))

            // const new_selection = await psapi.getSelectionInfoExe()

            if (
                await hasSelectionChanged(
                    current_selection,
                    g_generation_session.selectionInfo
                ) //new selection
            ) {
                // endSessionUI //red color
                // if selection has changed : change the color and text generate btn  "Generate" color "red"
                // g_ui.endSessionUI()
                // const selected_mode = html_manip.getMode()
                const selected_mode = getCurrentGenerationModeByValue(g_sd_mode)
                g_ui.generateModeUI(selected_mode)
            } else {
                // it's the same selection and the session is active

                //indicate that the session will continue. only if the session we are in the same mode as the session's mode
                // startSessionUI// green color
                const current_mode = html_manip.getMode()
                if (
                    g_generation_session.isActive() && // the session is active
                    g_generation_session.isSameMode(current_mode) //same mode
                ) {
                    // g_ui.startSessionUI()
                    g_ui.generateMoreUI()
                }
            }
        }
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to generation_settings.js
function getCurrentGenerationModeByValue(value) {
    for (let key in generationMode) {
        if (
            generationMode.hasOwnProperty(key) &&
            generationMode[key] === value
        ) {
            return key
        }
    }
    return undefined
}

require('photoshop').action.addNotificationListener(
    ['set', 'move'],
    eventHandler
)
//REFACTOR: move to document.js
async function getUniqueDocumentId() {
    console.warn(
        'getUniqueDocumentId is deprecated, instead use the methods in IOFolder'
    )
    try {
        let uniqueDocumentId = await psapi.readUniqueDocumentIdExe()

        console.log(
            'getUniqueDocumentId():  uniqueDocumentId: ',
            uniqueDocumentId
        )

        // Regular expression to check if string is a valid UUID
        const regexExp =
            /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi

        // String with valid UUID separated by dash
        // const str = 'a24a6ea4-ce75-4665-a070-57453082c256'

        const isValidId = regexExp.test(uniqueDocumentId) // true
        console.log('isValidId: ', isValidId)
        if (isValidId == false) {
            let uuid = self.crypto.randomUUID()
            console.log(uuid) // for example "36b8f84d-df4e-4d49-b662-bcde71a8764f"
            await psapi.saveUniqueDocumentIdExe(uuid)
            uniqueDocumentId = uuid
        }
        return uniqueDocumentId
    } catch (e) {
        console.warn('warning Document Id may not be valid', e)
    }
}

// document
//   .getElementById('btnLinkCurrentDocument')
//   .addEventListener('click', async () => {
//     await getUniqueDocumentId()
//   })

// attach event listeners for tabs
//REFACTOR: move to html_manip.js (?) - if there is no business logic here and it's only for UI.
Array.from(document.querySelectorAll('.sp-tab')).forEach((theTab) => {
    theTab.onclick = () => {
        try {
            // localStorage.setItem("currentTab", theTab.getAttribute("id"));
            Array.from(document.querySelectorAll('.sp-tab')).forEach((aTab) => {
                if (aTab.getAttribute('id') === theTab.getAttribute('id')) {
                    aTab.classList.add('selected')
                } else {
                    aTab.classList.remove('selected')
                }
            })
            Array.from(document.querySelectorAll('.sp-tab-page')).forEach(
                (tabPage) => {
                    if (
                        tabPage
                            .getAttribute('id')
                            .startsWith(theTab.getAttribute('id'))
                    ) {
                        tabPage.classList.add('visible-hack')
                    } else {
                        tabPage.classList.remove('visible-hack')
                    }
                }
            )
        } catch (e) {
            console.warn(e)
        }
    }
})
//REFACTOR: move to events.js
document.getElementById('sp-viewer-tab').addEventListener('click', async () => {
    if (
        g_generation_session.isActive() &&
        g_generation_session.mode === 'upscale'
    ) {
        g_sd_mode = 'upscale'
    } else {
        g_sd_mode = html_manip.getMode()
    }
})
//REFACTOR: move to events.js
document.getElementById('sp-viewer-tab').addEventListener('click', async () => {
    moveElementToAnotherTab('batchNumberUi', 'batchNumberViewerTabContainer')
    await displayUpdate()
})
//REFACTOR: move to events.js
document
    .getElementById('sp-stable-diffusion-ui-tab')
    .addEventListener('click', () => {
        moveElementToAnotherTab('batchNumberUi', 'batchNumber-steps-container')
    })
// entrypoints.setup({

//   panels:{
//     vanilla: ()=>{
//       console.log("you are in the vanilla panel")
//     },
//     experimental_1: ()=>{
//       console.log("you are in the experimental_1 panel")

//     }
//   }
// }
//   )
// just a number that shouldn't unique enough that we will use when save files.
// each session will get a number from 1 to 1000000
//REFACTOR: move to session.js
const random_session_id = Math.floor(Math.random() * 1000000 + 1)
//REFACTOR: move to helpers.js (or other utility file)
function getSelectedText() {
    // JavaScript
    //     // Obtain the object reference for the <textarea>
    // const txtarea = document.getElementById("taPrompt");
    const promptTextarea = document.querySelector('#taPrompt')
    console.log('promptTextarea: ', promptTextarea.value)
    //     // Obtain the index of the first selected character
    var start = promptTextarea.selectionStart
    console.log('start: ', start)
    //     // Obtain the index of the last selected character
    //     var finish = txtarea.selectionEnd;
    //     console.log("finish: ",finish)

    //     // Obtain the selected text
    //     var sel = txtarea.value.substring(start, finish);
    //     console.log("selected textarea: ", sel)

    // Do something with the selected content
}
//REFACTOR: move to helpers.js
// setInterval(getSelectedText,2000)
function getCommentedString() {
    // const text = document.getElementById("taPrompt").value
    // let text = `Visit /*W3Schools
    // cute, girl, painterly
    // *\\ any text
    // and prompt`;
    // let text = `cute cat /*by greg

    // and artgerm

    //  */ and famous artist`
    let text = `Visit /*W3Schools 
  cute, girl, painterly   
  */ any text
  and prompt




 cute cat  /*by greg 

  and artgerm 
  
   */ and famous artist`
    console.log('getCommentedString: text: ', text)

    // let pattern = /(\/)(\*)(\s|\S)*\*\\/g;
    let pattern = /(\/)(\*)(\s|\S)*?(\*\/)/g

    let result = text.match(pattern)
    console.log('getCommentedString: ', result)
}

//REFACTOR: move to helpers.js
function tempDisableElement(element, time) {
    element.classList.add('disableBtn')
    element.disabled = true
    // element.style.opacity = '0.65'
    // element.style.cursor = 'not-allowed'
    setTimeout(function () {
        element.disabled = false
        element.classList.remove('disableBtn')
        // element.style.opacity = '1.0'
        // element.style.cursor = 'default'
    }, time)
}

//REFACTOR: move to the notfication.js
async function displayNotification(automatic_status) {
    if (automatic_status === Enum.AutomaticStatusEnum['RunningWithApi']) {
        //do nothing
    } else if (
        g_automatic_status === Enum.AutomaticStatusEnum['RunningNoApi']
    ) {
        await note.Notification.webuiAPIMissing()
    } else if (g_automatic_status === Enum.AutomaticStatusEnum['Offline']) {
        await note.Notification.webuiIsOffline()
    }
}
//REFACTOR: move to sdapi.js
async function checkAutoStatus() {
    try {
        const options = await g_sd_options_obj.getOptions()
        if (options) {
            //means both automatic1111 and proxy server are online
            html_manip.setAutomaticStatus('connected', 'disconnected')
            g_automatic_status = Enum.AutomaticStatusEnum['RunningWithApi']
            // html_manip.setProxyServerStatus('connected','disconnected')
        } else {
            html_manip.setAutomaticStatus('disconnected', 'connected')
            if (await sdapi.isWebuiRunning()) {
                //running with no api
                g_automatic_status = Enum.AutomaticStatusEnum['RunningNoApi']
                // await note.Notification.webuiAPIMissing()
            } else {
                //not running and of course no api
                g_automatic_status = Enum.AutomaticStatusEnum['Offline']
                // await note.Notification.webuiIsOffline()
            }

            return g_automatic_status
        }
    } catch (e) {
        console.warn(e)
    }
    return g_automatic_status
}

//REFACTOR: move to ui.js
async function refreshUI() {
    try {
        const b_proxy_server_status = await updateVersionUI()
        if (b_proxy_server_status) {
            html_manip.setProxyServerStatus('connected', 'disconnected')
            // g_automatic_status = Enum.AutomaticStatusEnum['RunningWithApi']
        } else {
            html_manip.setProxyServerStatus('disconnected', 'connected')
        }

        g_automatic_status = await checkAutoStatus()
        await displayNotification(g_automatic_status)

        const bSamplersStatus = await initSamplers()

        g_models_status = await refreshModels()
        await refreshExtraUpscalers()

        await sdapi.setInpaintMaskWeight(1.0) //set the inpaint conditional mask to 1 when the on plugin start

        //get the latest options

        await g_sd_options_obj.getOptions()
        //get the selected model
        const current_model_title = g_sd_options_obj.getCurrentModel()
        //update the ui with that model title
        const current_model_hash =
            html_manip.getModelHashByTitle(current_model_title)
        html_manip.autoFillInModel(current_model_hash)

        //fetch the inpaint mask weight from sd webui and update the slider with it.
        const inpainting_mask_weight =
            await g_sd_options_obj.getInpaintingMaskWeight()
        console.log('inpainting_mask_weight: ', inpainting_mask_weight)
        html_manip.autoFillInInpaintMaskWeight(inpainting_mask_weight)

        await g_sd_config_obj.getConfig()
        //init ControlNet Tab
        // g_hi_res_upscaler_models = temp_config.getUpscalerModels()
        g_controlnet_max_models = g_sd_config_obj.getControlNetMaxModelsNum()
        await control_net.initializeControlNetTab(g_controlnet_max_models)
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to generation_settings.js
async function refreshModels() {
    let b_result = false
    try {
        g_models = await sdapi.requestGetModels()
        if (g_models.length > 0) {
            b_result = true
        }

        // const models_menu_element = document.getElementById('mModelsMenu')
        // models_menu_element.value = ""
        document.getElementById('mModelsMenu').innerHTML = ''

        for (let model of g_models) {
            // console.log(model.title)//Log
            const menu_item_element = document.createElement('sp-menu-item')
            menu_item_element.className = 'mModelMenuItem'
            menu_item_element.innerHTML = model.title
            menu_item_element.dataset.model_hash = model.hash
            menu_item_element.dataset.model_title = model.title
            document
                .getElementById('mModelsMenu')
                .appendChild(menu_item_element)
        }
    } catch (e) {
        b_result = false
        console.warn(e)
    }
    return b_result
}
//REFACTOR: move to generation_settings.js
async function refreshExtraUpscalers() {
    try {
        //cycle through hrModelsMenuClass and reset innerHTML
        var hrModelsMenuClass = document.getElementsByClassName(
            'hrExtrasUpscaleModelsMenuClass'
        )
        for (let i = 0; i < hrModelsMenuClass.length; i++) {
            hrModelsMenuClass[i].innerHTML = ''
        }
        g_extra_upscalers = await sdapi.requestGetUpscalers()

        for (let model of g_extra_upscalers) {
            var hrModelsMenuClass = document.getElementsByClassName(
                'hrExtrasUpscaleModelsMenuClass'
            )
            for (let i = 0; i < hrModelsMenuClass.length; i++) {
                const menu_item_element = document.createElement('sp-menu-item')
                menu_item_element.className = 'hrExtrasUpscaleModelsMenuItem'
                menu_item_element.innerHTML = model.name
                hrModelsMenuClass[i].appendChild(menu_item_element)
                // console.log(model + ' added to ' + hrModelsMenuClass[i].id)//Log
            }
        }
    } catch (e) {
        console.warn(e)
    }
}

//REFACTOR: move to ui.js
async function updateVersionUI() {
    let bStatus = false
    try {
        version = await sdapi.getVersionRequest()
        document.getElementById('lVersionNumber').textContent = version
        if (version !== 'v0.0.0') {
            bStatus = true
        }
    } catch (e) {
        console.warn(e)
        document.getElementById('lVersionNumber').textContent = 'v0.0.0'
        bStatus = false
    }
    return bStatus
}
//REFACTOR: move to generation_settings.js
async function initSamplers() {
    let bStatus = false
    try {
        let sampler_group = document.getElementById('sampler_group')
        sampler_group.innerHTML = ''

        let samplers = await sdapi.requestGetSamplers()
        if (!samplers) {
            //if we failed to get the sampler list from auto1111, use the list stored in sampler.js

            samplers = sampler_data.samplers
        }

        for (let sampler of samplers) {
            // console.log(sampler)//Log
            // sampler.name
            // <sp-radio class="rbSampler" value="Euler">Euler</sp-radio>
            const rbSampler = document.createElement('sp-radio')

            rbSampler.innerHTML = sampler.name
            rbSampler.setAttribute('class', 'rbSampler')
            rbSampler.setAttribute('value', sampler.name)

            sampler_group.appendChild(rbSampler)
            //add click event on radio button for Sampler radio button, so that when a button is clicked it change g_sd_sampler globally

            //we could delete the click() event
            rbSampler.addEventListener('click', (evt) => {
                g_sd_sampler = evt.target.value
                console.log(`You clicked: ${g_sd_sampler}`)
            })
        }
        document
            .getElementsByClassName('rbSampler')[0]
            .setAttribute('checked', '')
        if (samplers.length > 0) {
            bStatus = true
        }
    } catch (e) {
        console.warn(e)
    }
    return bStatus
}
//REFACTOR: move to helper.js
function promptShortcutExample() {
    let prompt_shortcut_example = {
        game_like:
            'Unreal Engine, Octane Render, arcane card game ui, hearthstone art style, epic fantasy style art',
        large_building_1: 'castle, huge building, large building',
        painterly_style_1:
            'A full portrait of a beautiful post apocalyptic offworld arctic explorer, intricate, elegant, highly detailed, digital painting, artstation, concept art, smooth, sharp focus, illustration',
        ugly: ' ((((ugly)))), (((duplicate))), ((morbid)), ((mutilated)), out of frame, extra fingers, mutated hands, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), (((deformed))), ((ugly)), blurry, ((bad anatomy)), (((bad proportions))), ((extra limbs)), cloned face, (((disfigured))), out of frame, ugly, extra limbs, (bad anatomy), gross proportions, (malformed limbs), ((missing arms)), ((missing legs)), (((extra arms))), (((extra legs))), mutated hands, (fused fingers), (too many fingers), (((long neck)))',
    }
    var JSONInPrettyFormat = JSON.stringify(
        prompt_shortcut_example,
        undefined,
        7
    )
    document.getElementById('taPromptShortcut').value = JSONInPrettyFormat
    return prompt_shortcut_example
}

//**********Start: global variables
let prompt_dir_name = ''
let gImage_paths = []
let g_image_path_to_layer = {}
let g_init_images_dir = './server/python_server/init_images'
//REFACTOR: move to generationSettings.js
gCurrentImagePath = ''
//REFACTOR: move to generationSettings.js
let g_init_image_name = ''
// let g_init_mask_layer;
//REFACTOR: move to generationSettings.js
let g_init_image_mask_name = ''
// let g_mask_related_layers = {}
// let g_init_image_related_layers = {}
//REFACTOR: move to generationSettings.js, Note: numberOfImages deprecated global variable
// let numberOfImages = document.querySelector('#tiNumberOfImages').value
//REFACTOR: move to generationSettings.js
let g_sd_mode = 'txt2img'
// let g_sd_mode_last = g_sd_mode
//REFACTOR: move to generationSettings.js
let g_sd_mode_last = g_sd_mode
//REFACTOR: move to generationSettings.js
let g_sd_sampler = 'Euler a'
//REFACTOR: move to generationSettings.js
let g_denoising_strength = 0.7
//REFACTOR: move to generationSettings.js
let g_use_mask_image = false
let g_models = []
// let g_models_horde = []
let g_model_title = ''
// let gWidth = 512
// let gHeight = 512
//REFACTOR: move to generationSettings.js
let hWidth = 512
//REFACTOR: move to generationSettings.js
let hHeight = 512
//REFACTOR: move to generationSettings.js
let h_denoising_strength = 0.7
// let g_inpainting_fill = 0
// let g_last_outpaint_layers = []
// let g_last_inpaint_layers = []
// let g_last_snap_and_fill_layers = []

//REFACTOR: move to generationSettings.js
let g_metadatas = []
let g_last_seed = '-1'
//REFACTOR: move to generationSettings.js
let g_can_request_progress = true
let g_saved_active_layers = []
let g_saved_active_selection = {}
let g_is_active_layers_stored = false

let g_number_generation_per_session = 0
let g_isViewerMenuDisabled = false // disable the viewer menu and viewerImage when we're importing images into the current document
let g_b_mask_layer_exist = false // true if inpaint mask layer exist, false otherwise.
let g_inpaint_mask_layer
let g_inpaint_mask_layer_history_id //store the history state id when creating a new inpaint mask layer

// let g_selection = {}
//REFACTOR: move to session.js
let g_selection = {}
let g_b_use_smart_object = true // true to keep layer as smart objects, false to rasterize them
let g_sd_options_obj = new sd_options.SdOptions()

g_sd_options_obj.getOptions()
// let g_sd_config_obj = new sd_config.SdConfig()
// g_sd_config_obj.getConfig();

// let g_width_slider = new ui.UIElement()
// g_width_slider.getValue = html_manip.getWidth
// ui_settings.uiElements.push =
let g_old_slider_width = 512
let g_old_slider_height = 512
let g_sd_config_obj
let g_hi_res_upscaler_models
let g_controlnet_max_models
;(async function () {
    let temp_config = new sd_config.SdConfig()
    g_sd_config_obj = temp_config
    await g_sd_config_obj.getConfig()
    g_hi_res_upscaler_models = g_sd_config_obj.getUpscalerModels()
    g_controlnet_max_models = g_sd_config_obj.getControlNetMaxModelsNum()

    for (let model of g_hi_res_upscaler_models) {
        //update the hi res upscaler models menu
        let hrModelsMenuClass =
            document.getElementsByClassName('hrModelsMenuClass')
        for (let i = 0; i < hrModelsMenuClass.length; i++) {
            const menu_item_element = document.createElement('sp-menu-item')
            menu_item_element.className = 'hrModelsMenuItem'
            menu_item_element.innerHTML = model
            hrModelsMenuClass[i].appendChild(menu_item_element)
            // console.log(model + ' added to ' + hrModelsMenuClass[i].id)//Log
        }
    }
})()

let g_generation_session = new session.GenerationSession(0) //session manager
g_generation_session.deactivate() //session starte as inactive
let g_ui = new ui.UI()

let g_ui_settings_object = ui.getUISettingsObject()
let g_batch_count_interrupt_status = false
const requestState = {
    Generate: 'generate',
    Interrupt: 'interrupt',
}

let g_request_status = '' //

//REFACTOR: move to Enum.js
const generationMode = {
    Txt2Img: 'txt2img',
    Img2Img: 'img2img',
    Inpaint: 'inpaint',
    Outpaint: 'outpaint',
    Upscale: 'upscale',
}
const backendTypeEnum = {
    Auto1111: 'auto1111',
    HordeNative: 'horde_native',
    Auto1111HordeExtension: 'auto1111_horde_extension',
}

g_generation_session.mode = generationMode['Txt2Img']
let g_viewer_manager = new viewer.ViewerManager()

//********** End: global variables */

//***********Start: init function calls */
//REFACTOR: keep in index.js
async function initPlugin() {
    //*) load plugin settings
    //*) load horde settings
    //*)
    //*) initialize the samplers
    //*)
    await settings_tab.loadSettings()
    await horde_native.HordeSettings.loadSettings()
    const bSamplersStatus = await initSamplers() //initialize the sampler
    await sdapi.setInpaintMaskWeight(1.0) //set the inpaint conditional mask to 1 when the on plugin start
    await refreshUI()
    await displayUpdate()
    // promptShortcutExample()
    await loadPromptShortcut()
    await refreshPromptMenue()

    await g_sd_config_obj.getConfig()
    //init ControlNet Tab
    // g_hi_res_upscaler_models = temp_config.getUpscalerModels()
    g_controlnet_max_models = g_sd_config_obj.getControlNetMaxModelsNum()
    await control_net.initializeControlNetTab(g_controlnet_max_models)
}
initPlugin()
// refreshModels() // get the models when the plugin loads
// initSamplers()
// updateVersionUI()
// refreshUI()
// displayUpdate()
// loadPromptShortcut()
// // promptShortcutExample()

//***********End: init function calls */

//add click event on radio button mode, so that when a button is clicked it change g_sd_mode globally
//REFACTOR: move to events.js
rbModeElements = document.getElementsByClassName('rbMode')
for (let rbModeElement of rbModeElements) {
    rbModeElement.addEventListener('click', async (evt) => {
        try {
            g_sd_mode = evt.target.value
            scripts.script_store.setMode(g_sd_mode)
            // console.log(`You clicked: ${g_sd_mode}`)
            await displayUpdate()
            await postModeSelection() // do things after selection
        } catch (e) {
            console.warn(e)
        }
    })
}

//swaps g_sd_mode when clicking on extras tab and swaps it back to previous value when clicking on main tab
//REFACTOR: move to events.js
document
    .getElementById('sp-extras-tab')
    .addEventListener('click', async (evt) => {
        try {
            // g_sd_mode_last = g_sd_mode
            g_sd_mode = 'upscale'
            console.log(`You clicked: ${g_sd_mode}`)
            await displayUpdate()
            await postModeSelection() // do things after selection
        } catch (e) {
            console.warn(e)
        }
    })
//REFACTOR: move to events.js
document
    .getElementById('sp-stable-diffusion-ui-tab')
    .addEventListener('click', async (evt) => {
        try {
            // g_sd_mode = g_sd_mode_last
            g_sd_mode = html_manip.getMode()
            console.log(`mode restored to: ${g_sd_mode}`)
            await displayUpdate()
            await postModeSelection() // do things after selection
        } catch (e) {
            console.warn(e)
        }
    })
//REFACTOR: move to psapi.js
async function createTempInpaintMaskLayer() {
    if (!g_b_mask_layer_exist) {
        //make new layer "Mask -- Paint White to Mask -- temporary"

        const name = 'Mask -- Paint White to Mask -- temporary'
        await psapi.unselectActiveLayersExe() // so that the mask layer get create at the top of the layer stocks
        const top_layer_doc = await app.activeDocument.layers[0]
        g_inpaint_mask_layer = await layer_util.createNewLayerExe(name, 60)
        await executeAsModal(async () => {
            await g_inpaint_mask_layer.moveAbove(top_layer_doc)
        })
        // g_inpaint_mask_layer.opacity = 50
        g_b_mask_layer_exist = true
        const index = app.activeDocument.historyStates.length - 1
        g_inpaint_mask_layer_history_id =
            app.activeDocument.historyStates[index].id
        console.log(
            'g_inpaint_mask_layer_history_id: ',
            g_inpaint_mask_layer_history_id
        )
    }
}
//REFACTOR: move to psapi.js
async function deleteTempInpaintMaskLayer() {
    console.log(
        'g_inpaint_mask_layer_history_id: ',
        g_inpaint_mask_layer_history_id
    )
    const historyBrushTools = app.activeDocument.historyStates.filter(
        (h) => h.id > g_inpaint_mask_layer_history_id && h.name === 'Brush Tool'
    )
    console.log(historyBrushTools)
    if (historyBrushTools.length === 0 && g_b_mask_layer_exist) {
        await layer_util.deleteLayers([g_inpaint_mask_layer])

        g_b_mask_layer_exist = false
    }
}
//REFACTOR: move to ui.js
async function postModeSelection() {
    //
    try {
        if (g_sd_mode === generationMode['Inpaint']) {
            //check if the we already have created a mask layer
            await createTempInpaintMaskLayer()
        } else {
            // if we switch from inpaint mode, delete the mask layer
            // Find all history states after the creation of the inpaint mask and their name brush tool
            await deleteTempInpaintMaskLayer()
        }
    } catch (e) {
        console.warn(e)
    }
}
rbMaskContentElements = document.getElementsByClassName('rbMaskContent')
//REFACTOR: move to events.js
for (let rbMaskContentElement of rbMaskContentElements) {
    rbMaskContentElement.addEventListener('click', async (evt) => {
        // g_inpainting_fill = evt.target.value
        // console.log(`You clicked: ${g_inpainting_fill}`)
    })
}

btnSquareClass = document.getElementsByClassName('btnSquare')
//REFACTOR: move to events.js
for (let btnSquareButton of btnSquareClass) {
    btnSquareButton.addEventListener('click', async (evt) => {
        // document.activeElement.blur()
        setTimeout(() => {
            try {
                evt.target.blur()
            } catch (e) {
                console.warn(e)
            }
        }, 500)
    })
}

btnRefreshModelsClass = document.getElementsByClassName('btnRefreshModels')
//REFACTOR: move to events.js
for (let btnRefreshModel of btnRefreshModelsClass) {
    btnRefreshModel.addEventListener('click', async (evt) => {
        // document.activeElement.blur()
        setTimeout(() => {
            try {
                evt.target.blur()
            } catch (e) {
                console.warn(e)
            }
        }, 500)
    })
}
//REFACTOR: move to events.js
document.addEventListener('mouseenter', async (event) => {
    try {
        //only check if the generation mode has not changed( e.g a session.mode === img2img and the current selection is "img2img"  ).
        // changing the mode will trigger it's own procedure, so doing it here again is redundant
        if (
            g_generation_session.isActive() &&
            g_generation_session.mode === g_sd_mode
        ) {
            //if the generation session is active and the selected mode is still the same as the generation mode

            console.log('hover on window')

            const new_selection = await psapi.getSelectionInfoExe() //get the current active selection if there is any

            if (
                new_selection &&
                (await hasSelectionChanged(
                    new_selection,
                    g_generation_session.selectionInfo
                ))
            ) {
                // if there is an active selection and if the selection has changed

                await calcWidthHeightFromSelection()

                if (
                    g_generation_session.state ===
                    session.SessionState['Active']
                ) {
                    //indicate that the session will end if you generate
                    //only if you move the selection while the session is active
                    // g_ui.endSessionUI()
                    const selected_mode = html_manip.getMode()
                    g_ui.generateModeUI(selected_mode)
                } else {
                    // move the selection while the session is inactive
                }
            } else {
                // sessionStartHtml(true)//generate more, green color
                //if you didn't move the selection.
                // g_ui.startSessionUI()
                g_ui.generateMoreUI()
            }
        }
    } catch (e) {
        console.warn(e)
    }
})
////add tips to element when mouse hover on an element
// function getToolTipElement(){
//   const tool_tip = document.getElementById("tool_tip")
//   return tool_tip
// }
// function moveTip(x,y){
//   var tool_tip = document.getElementById("tool_tip")

//     tool_tip.style.position =  'absolute';
//     tool_tip.style.left =  x;
//     tool_tip.style.top =  y;
// }
// document.getElementById('rbOutpaintMode').addEventListener("mouseover",(e)=>{

//   console.log("e.shiftKey:",e.shiftKey)

//   if(e.shiftKey)
//   {
//     const rect = e.target.getBoundingClientRect()
//     const tool_tip = getToolTipElement()
//     setTimeout(()=>{
//       tool_tip.style.display = "none"
//     },5000)
//     tool_tip.style.display = "inline-block"

//     tool_tip.style["z-index"] =  100;
//     console.log("Use this mode when you want to fill empty areas of the canvas")
//     // var x = e.pageX;
//     // var y = e.pageY;
//     console.log("(e.pageX,e.pageY): ",(e.pageX,e.pageY))
//     const tip_x = e.pageX - (tool_tip.offsetWidth/2)
//     // const tip_y = e.pageY + - tool_tip.offsetHeight
//     const tip_y = rect.top + - tool_tip.offsetHeight

//     moveTip(tip_x,tip_y)
//   }
//   else{// rlease the shift key
//     console.log("tip will disappear in 1 second")
//   }

// });

// document.getElementById('rbOutpaintMode').addEventListener("mouseout",(e)=>{

//   console.log("e.shiftKey:",e.shiftKey)

//   console.log("no tip, tip will disappear in 1 second")
//   // getToolTipElement().style.display = "none"

// });

// show the interface that need to be shown and hide the interface that need to be hidden
//REFACTOR: move to ui.js
async function displayUpdate() {
    try {
        sd_tab.displayImageCfgScaleSlider(g_sd_mode)
        if (g_sd_mode == 'txt2img') {
            document.getElementById('slDenoisingStrength').style.display =
                'none' // hide denoising strength slider
            // document.getElementById("image_viewer").style.display = 'none' // hide images
            document.getElementById('init_image_container').style.display =
                'none' // hide init image
            document.getElementById('init_image_mask_container').style.display =
                'none' // hide init mask
            document.getElementById('slInpainting_fill').style.display = 'none' // hide inpainting fill mode
            document.getElementById('chInpaintFullRes').style.display = 'none'

            document.getElementById('slInpaintingMaskWeight').style.display =
                'none' // hide inpainting conditional mask weight

            document.getElementById('chHiResFixs').style.display = 'flex'
            if (html_manip.getHiResFixs()) {
                document.getElementById('HiResDiv').style.display = 'block'
            }

            document.getElementById('slMaskExpansion').style.display = 'none'

            document.getElementById('slInpaintPadding').style.display = 'none'
            document.getElementById('slMaskBlur').style.display = 'none'
            // document.getElementById('slImageCfgScale').style.display = 'none'
            // document.getElementById('btnSnapAndFill').style.display = 'none'//"none" will  misaligned the table // hide snap and fill button
        }

        if (g_sd_mode == 'img2img') {
            document.getElementById('slDenoisingStrength').style.display =
                'block' // show denoising strength
            document.getElementById('slMaskExpansion').style.display = 'none'
            // document.getElementById("image_viewer").style.display = 'block'
            document.getElementById('init_image_container').style.display =
                'block' // hide init image

            document.getElementById('init_image_mask_container').style.display =
                'none' // hide mask
            document.getElementById('slInpainting_fill').style.display = 'none' // hide inpainting fill mode
            // document.getElementById('btnSnapAndFill').style.display = 'inline-flex' // hide snap and fill button mode
            document.getElementById('HiResDiv').style.display = 'none'
            document.getElementById('chInpaintFullRes').style.display = 'none'
            document.getElementById('slInpaintPadding').style.display = 'none'
            document.getElementById('slMaskBlur').style.display = 'none'
            document.getElementById('chHiResFixs').style.display = 'none'
            document.getElementById('slInpaintingMaskWeight').style.display =
                'block' // hide inpainting conditional mask weight

            // document.getElementById('slImageCfgScale').style.display = 'block'
        }

        if (g_sd_mode == 'inpaint' || g_sd_mode == 'outpaint') {
            ///fix the misalignment problem in the ui (init image is not aligned with init mask when switching from img2img to inpaint ). note: code needs refactoring
            // document.getElementById('btnSnapAndFill').style.display = 'none'//"none" will  misaligned the table // hide snap and fill button
            document.getElementById('tableInitImageContainer').style.display =
                'none' // hide the table
            document.getElementById('slMaskExpansion').style.display = 'block'
            setTimeout(() => {
                try {
                    document.getElementById(
                        'tableInitImageContainer'
                    ).style.display = 'table' // show the table after some time so it gets rendered.
                } catch (e) {
                    console.warn(e)
                }
            }, 100)

            document.getElementById('slDenoisingStrength').style.display =
                'block'
            document.getElementById('init_image_mask_container').style.display =
                'block'
            document.getElementById('slInpainting_fill').style.display = 'block'
            document.getElementById('init_image_container').style.display =
                'block' // hide init image
            document.getElementById('slInpaintingMaskWeight').style.display =
                'block' // hide inpainting conditional mask weight

            document.getElementById('HiResDiv').style.display = 'none'
            document.getElementById('chInpaintFullRes').style.display =
                'inline-flex'
            if (document.getElementById('chInpaintFullRes').checked) {
                document.getElementById('slInpaintPadding').style.display =
                    'block'
            } else {
                document.getElementById('slInpaintPadding').style.display =
                    'none'
            }
            document.getElementById('slMaskBlur').style.display = 'block'
            document.getElementById('chHiResFixs').style.display = 'none'

            // document.getElementById('btnInitOutpaint').style.display = 'inline-flex'
            // document.getElementById('btnInitInpaint').style.display = 'inline-flex'
            // document.getElementById('btnInitOutpaint').style.display = 'none'
            // document.getElementById('btnInitInpaint').style.display = 'none'
        } else {
            //txt2img or img2img
            // document.getElementById('btnInitOutpaint').style.display = 'none'
            // document.getElementById('btnInitInpaint').style.display = 'none'
        }

        if (g_generation_session.isActive()) {
            //Note: remove the "or" operation after refactoring the code
            //if the session is active

            if (g_generation_session.mode !== g_sd_mode) {
                //if a generation session is active but we changed mode. the generate button will reflect that
                //Note: add this code to the UI class
                const generate_btns = Array.from(
                    document.getElementsByClassName('btnGenerateClass')
                )
                generate_btns.forEach((element) => {
                    const selected_mode =
                        getCurrentGenerationModeByValue(g_sd_mode)
                    element.textContent = `Generate ${selected_mode}`
                })

                html_manip.setGenerateButtonsColor('generate', 'generate-more')
            } else {
                //1) and the session is active
                //2) is the same generation mode

                if (!(await hasSessionSelectionChanged())) {
                    //3a) and the selection hasn't change

                    const generate_btns = Array.from(
                        document.getElementsByClassName('btnGenerateClass')
                    )

                    // const selected_mode =
                    //     getCurrentGenerationModeByValue(g_sd_mode)
                    const generation_mode = g_generation_session.mode
                    const generation_name =
                        getCurrentGenerationModeByValue(generation_mode)
                    generate_btns.forEach((element) => {
                        element.textContent = `Generate More ${generation_name}`
                    })

                    html_manip.setGenerateButtonsColor(
                        'generate-more',
                        'generate'
                    )
                } else {
                    //3b) selection has change
                }
            }
        } else {
            //session is not active
            const selected_mode = getCurrentGenerationModeByValue(g_sd_mode)
            g_ui.setGenerateBtnText(`Generate ${selected_mode}`)
            html_manip.setGenerateButtonsColor('generate', 'generate-more')
        }
    } catch (e) {
        console.warn(e)
    }
}
// function showLayerNames () {
//   const app = window.require('photoshop').app
//   const allLayers = app.activeDocument.layers
//   const allLayerNames = allLayers.map(
//     layer => `${layer.name} (${layer.opacity} %)`
//   )

//   const sortedNames = allLayerNames.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
//   document.getElementById('layers').innerHTML = `
//         <ul>${sortedNames.map(name => `<li>${name}</li>`).join('')}</ul>`
// }
//REFACTOR: move to psapi.js
function selectTool() {
    var doc = app.activeDocument
    var activeTool = app.currentTool

    // if (activeTool !== toolName) {
    //   toolName = activeTool;
    //   doc.activeTool = toolName;
    // }
    // const util = require('util')

    // console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
    console.dir(app, { depth: null })
    console.log('hello this is Abdullah')
    document.getElementById('layers').innerHTML = `<span>
    selectTool was called, ${activeTool}
    </span>`

    //rectanglemarquee
    // await require('photoshop').core.executeAsModal(newNormalLayer);
}
//Refactor: Delete testServerPath() method
async function testServerPath() {
    // const serverPath = "https://api.github.com/users/abdullah"

    try {
        // const serverPath = 'https://api.weather.gov/points/123.4,342.5'
        // const serverPath = 'https://api.github.com/users/abdullah'
        // const serverPath = "https://api.coindesk.com/v1/bpi/currentprice.json"
        // const serverPath = "http://127.0.0.1:3000"
        // const serverPath = "http://localhost:3000"
        const serverPath = 'http://127.0.0.1:8000/txt2img/random%20prompt'
        // const serverPath = "https://3330-37-106-100-102.eu.ngrok.io"
        console.log('testServerPath function was called')

        let response = await fetch(serverPath)
        console.log('testServerPath finished fetch')

        if (!response.ok) {
            throw new Error(
                `HTTP error fetching weather station; status: ${response.status}`
            )
        }
        let stationJson = await response.json()
        console.dir(stationJson)
    } catch (err) {
        console.error('testServerPath error: ' + err.message)
    }
}

// User picks an image file
// open a explorer for user to select a image file
//REFACTOR: move to psapi.js
async function fillImage() {
    const storage = require('uxp').storage
    const fs = storage.localFileSystem
    let imageFile = await fs.getFileForOpening({
        types: storage.fileTypes.images,
    })

    // Create ImageFill for this image
    const ImageFill = require('scenegraph').ImageFill
    let fill = new ImageFill(imageFile)

    // Set fill of first selected item
    selection.items[0].fill = fill
}
// fillImage()
//REFACTOR: move to psapi.js
function pastImage2Layer() {
    const { batchPlay } = require('photoshop').action
    const { executeAsModal } = require('photoshop').core

    executeAsModal(
        () => {
            // batchPlay([command], {})
            const result = batchPlay(
                [
                    {
                        _obj: 'paste',
                        antiAlias: {
                            _enum: 'antiAliasType',
                            _value: 'antiAliasNone',
                        },
                        as: {
                            _class: 'pixel',
                        },
                        _options: {
                            dialogOptions: 'dontDisplay',
                        },
                    },
                ],
                {
                    synchronousExecution: true,
                    modalBehavior: 'fail',
                }
            )
        },
        {
            commandName: 'Create Label',
        }
    )
}
//REFACTOR: move to ui.js
function sliderToResolution(sliderValue) {
    return sliderValue * 64
}

//REFACTOR: move to events.js
document.querySelector('#hrHeight').addEventListener('input', (evt) => {
    hHeight = sliderToResolution(evt.target.value)
    document.querySelector('#hHeight').textContent = hHeight
})
//REFACTOR: move to events.js
document.querySelector('#hrWidth').addEventListener('input', (evt) => {
    hWidth = sliderToResolution(evt.target.value)
    document.querySelector('#hWidth').textContent = hWidth
})

//REFACTOR: move to events.js
document.querySelector('#slInpaintPadding').addEventListener('input', (evt) => {
    padding = evt.target.value * 4
    document.querySelector('#lInpaintPadding').textContent = padding
})

// document
//   .querySelector('#slDenoisingStrength')
//   .addEventListener('input', evt => {
//     const denoising_string_value = evt.target.value / 100.0
//     g_denoising_strength = denoising_string_value
//     // document.querySelector('#lDenoisingStrength').value= Number(denoising_string_value)
//     document.querySelector('#lDenoisingStrength').textContent =
//       denoising_string_value
//     document.getElementById(
//       'lDenoisingStrength'
//     ).innerHTML = `${denoising_string_value}`
//     // console.log(`New denoising_string_value: ${document.querySelector('#tiDenoisingStrength').value}`)
//   })
// document
//   .querySelector('#hrDenoisingStrength')
//   .addEventListener('input', evt => {
//     const denoising_string_value = evt.target.value / 100.0
//     h_denoising_strength = denoising_string_value

//     document.getElementById(
//       'hDenoisingStrength'
//     ).innerHTML = `${denoising_string_value}`
//     // console.log(`New denoising_string_value: ${document.querySelector('#tiDenoisingStrength').value}`)
//   })
// // document.getElementById('btnPopulate').addEventListener('click', showLayerNames)
//REFACTOR: move to psapi.js
async function snapAndFillHandler() {
    try {
        const isSelectionAreaValid = await psapi.checkIfSelectionAreaIsActive()
        if (isSelectionAreaValid) {
            if (g_generation_session.isFirstGeneration) {
                // clear the layers related to the last mask operation.
                // g_last_snap_and_fill_layers = await psapi.cleanLayers(
                //   g_last_snap_and_fill_layers
                // )
                // create new layers related to the current mask operation.
                await executeAsModal(
                    async () => {
                        // g_last_snap_and_fill_layers = await outpaint.snapAndFillExe(random_session_id)
                        await outpaint.snapAndFillExe(random_session_id)
                    },
                    { commandName: 'Snap And Fill' }
                )
                // console.log(
                //   'outpaint.snapAndFillExe(random_session_id):, g_last_snap_and_fill_layers: ',
                //   g_last_snap_and_fill_layers
                // )
            }
        } else {
            psapi.promptForMarqueeTool()
        }
    } catch (e) {
        console.warn(e)
    }
}

// document
//   .getElementById('btnSnapAndFill')
//   .addEventListener('click', async () => {

//   await snapAndFillHandler()
//   })
//REFACTOR: move to generation.js
async function easyModeOutpaint() {
    try {
        if (g_generation_session.isFirstGeneration) {
            // clear the layers related to the last mask operation.
            // g_last_outpaint_layers = await psapi.cleanLayers(g_last_outpaint_layers)

            // create new layers related to the current mask operation.
            // g_last_outpaint_layers = await outpaint.outpaintExe(random_session_id)
            await outpaint.outpaintExe(random_session_id)
        }
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to generation.js
async function btnInitInpaintHandler() {
    try {
        if (g_generation_session.isFirstGeneration) {
            // delete the layers of the previous mask operation
            // g_last_inpaint_layers = await psapi.cleanLayers(g_last_inpaint_layers)
            // store the layer of the current mask operation
            // g_last_inpaint_layers =  await outpaint.inpaintFasterExe(random_session_id)
            await outpaint.inpaintFasterExe(random_session_id)

            // console.log ("outpaint.inpaintFasterExe(random_session_id):, g_last_inpaint_layers: ",g_last_inpaint_layers)
        }
    } catch (e) {
        console.warn(e)
    }
}
// document
//   .getElementById('btnInitInpaint')
//   .addEventListener('click', async () => {
//  await btnInitInpaintHandler()
//   })
//REFACTOR: move to ui.js
function toggleTwoButtonsByClass(isVisible, first_class, second_class) {
    const first_class_btns = Array.from(
        document.getElementsByClassName(first_class)
    )
    const second_class_btns = Array.from(
        document.getElementsByClassName(second_class)
    )

    if (isVisible) {
        //show interrup button
        first_class_btns.forEach((element) => (element.style.display = 'none'))
        second_class_btns.forEach(
            (element) => (element.style.display = 'inline-block')
        )
        // console.log('first_class_btns: ', first_class_btns)
    } else {
        //show generate or generate more button
        first_class_btns.forEach(
            (element) => (element.style.display = 'inline-block')
        )
        if (g_generation_session.isActive()) {
            //show generate more
            // const selected_mode = getCurrentGenerationModeByValue(g_sd_mode)
            const generation_mode = g_generation_session.mode
            const generation_name =
                getCurrentGenerationModeByValue(generation_mode)
            first_class_btns.forEach(
                (element) =>
                    (element.textContent = `Generate More ${generation_name}`)
            )
        } else {
            //show generate button
            first_class_btns.forEach(
                (element) =>
                    (element.textContent = `Generate ${getCurrentGenerationModeByValue(
                        g_sd_mode
                    )}`)
            )
        }
        second_class_btns.forEach((element) => (element.style.display = 'none'))
    }
    return isVisible
}
//REFACTOR: move to session.js
async function discardAll() {
    //discard all generated images setting highlight to false
    //then call discard() to garbage collect the mask related layers
    try {
        for (const [path, viewer_image_obj] of Object.entries(
            g_viewer_manager.pathToViewerImage
        )) {
            try {
                viewer_image_obj.active(false) //deactivate the layer
                viewer_image_obj.setHighlight(false) // mark each layer as discarded
            } catch (e) {
                console.error(e)
            }
        }
        await discard() // clean viewer tab
        await layer_util.deleteLayers([g_generation_session.outputGroup]) //delete the group folder since it's empty
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to session.js
async function acceptAll() {
    //accept all generated images by highlighting them
    //then call discard() to garbage collect the mask related layers
    try {
        for (const [path, viewer_image_obj] of Object.entries(
            g_viewer_manager.pathToViewerImage
        )) {
            try {
                if (
                    viewer_image_obj.isActive() &&
                    viewer_image_obj instanceof viewer.OutputImage
                ) {
                    //check if the active viewer_image_obj is a type of OutputImage and move it to the top of the output group folder
                    //this is so when we accept all layers the canvas will look the same. otherwise the image could be cover by another generated image
                    if (
                        layer_util.Layer.doesLayerExist(viewer_image_obj.layer)
                    ) {
                        await g_generation_session.moveToTopOfOutputGroup(
                            viewer_image_obj.layer
                        )
                    }
                }
                viewer_image_obj.setHighlight(true) // mark each layer as accepted
            } catch (e) {
                console.error(e)
            }
        }
        await discard() // clean viewer tab
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to session.js
async function discardSelected() {
    //discard all generated images setting highlight to false
    //then call discard() to garbage collect the mask related layers
    try {
        for (const [path, viewer_image_obj] of Object.entries(
            g_viewer_manager.pathToViewerImage
        )) {
            try {
                if (viewer_image_obj.is_active) {
                    viewer_image_obj.active(false) //convert active to highlight
                    viewer_image_obj.setHighlight(true) //highlight the active image, since active images are not highlighted in the viewer
                }

                viewer_image_obj.toggleHighlight() // if invert the highlights on all images
            } catch (e) {
                console.error(e)
            }
        }
        await discard() // delete the images that currently highlighted
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
const discard_selected_class_btns = Array.from(
    document.getElementsByClassName('discardSelectedClass')
)
//REFACTOR: move to events.js
discard_selected_class_btns.forEach((element) =>
    element.addEventListener('click', async () => {
        try {
            await g_generation_session.endSession(
                session.GarbageCollectionState['DiscardSelected']
            ) //end session and accept only selected images
            g_ui.onEndSessionUI()
        } catch (e) {
            console.warn(e)
        }
    })
)

//REFACTOR: move to events.js
const accept_selected_class_btns = Array.from(
    document.getElementsByClassName('acceptSelectedClass')
)
//REFACTOR: move to events.js
accept_selected_class_btns.forEach((element) =>
    element.addEventListener('click', async () => {
        try {
            await g_generation_session.endSession(
                session.GarbageCollectionState['AcceptSelected']
            ) //end session and accept only selected images
            g_ui.onEndSessionUI()
        } catch (e) {
            console.warn(e)
        }
    })
)
//REFACTOR: move to events.js
const accept_class_btns = Array.from(
    document.getElementsByClassName('acceptClass')
)
//REFACTOR: move to events.js
accept_class_btns.forEach((element) =>
    element.addEventListener('click', async () => {
        try {
            await g_generation_session.endSession(
                session.GarbageCollectionState['Accept']
            ) //end session and accept all images
            g_ui.onEndSessionUI()

            // await acceptAll()
        } catch (e) {
            console.warn(e)
        }
    })
)
//REFACTOR: move to ui.js
function toggleTwoButtons(defaultVal, first_btn_id, second_btn_id) {
    if (defaultVal) {
        document.getElementById(first_btn_id).style.display = 'none' // hide generate button
        document.getElementById(second_btn_id).style.display = 'inline-block' // show interrupt button
    } else {
        document.getElementById(first_btn_id).style.display = 'inline-block' // hide generate button
        document.getElementById(second_btn_id).style.display = 'none' // show interrupt button
    }
    return defaultVal
}
//REFACTOR: move to events.js
document.getElementById('btnRandomSeed').addEventListener('click', async () => {
    document.querySelector('#tiSeed').value = '-1'
})
//REFACTOR: move to events.js
document.getElementById('btnLastSeed').addEventListener('click', async () => {
    try {
        console.log('click on Last seed')
        let seed = '-1'

        if (g_last_seed >= 0) {
            seed = g_last_seed.toString() //make sure the seed is a string
        }

        console.log('seed:', seed)
        document.querySelector('#tiSeed').value = seed
    } catch (e) {
        console.warn(e)
    }
})
//REFACTOR: move to session.js
async function discard() {
    try {
        await executeAsModal(async () => {
            await psapi.selectLayersExe([g_generation_session.outputGroup]) //must select the layer to change allLocked
            g_generation_session.outputGroup.allLocked = false //unlock the session folder on session end
        })

        // console.log(
        //   'click on btnCleanLayers,  g_last_outpaint_layers:',
        //   g_last_outpaint_layers
        // )
        // console.log(
        //   'click on btnCleanLayers,  g_last_inpaint_layers:',
        //   g_last_inpaint_layers
        // )

        // console.log(
        //   'click on btnCleanLayers,  g_last_snap_and_fill_layers:',
        //   g_last_snap_and_fill_layers
        // )

        // console.log('g_last_snap_and_fill_layers')
        // g_last_snap_and_fill_layers = await psapi.cleanLayers(
        //   g_last_snap_and_fill_layers
        // )

        // if (g_last_outpaint_layers.length > 0) {
        //   g_last_outpaint_layers = await psapi.cleanLayers(g_last_outpaint_layers)
        //   console.log('g_last_outpaint_layers has 1 layers')
        // }
        // if (g_last_inpaint_layers.length > 0) {
        //   g_last_inpaint_layers = await psapi.cleanLayers(g_last_inpaint_layers)
        //   g_b_mask_layer_exist = false

        // }
        const random_img_src = 'https://source.unsplash.com/random'
        html_manip.setInitImageSrc(random_img_src)
        html_manip.setInitImageMaskSrc(random_img_src)

        // psapi.cleanLayers(last_gen_layers)
        await deleteNoneSelected(g_viewer_manager.pathToViewerImage)
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
Array.from(document.getElementsByClassName('discardClass')).forEach(
    (element) => {
        element.addEventListener('click', async () => {
            //end session here
            await g_generation_session.endSession(
                session.GarbageCollectionState['Discard']
            ) //end session and remove all images
            g_ui.onEndSessionUI()

            // await discard()
        })
    }
)
//REFACTOR: move to events.js
Array.from(document.getElementsByClassName('btnInterruptClass')).forEach(
    (element) => {
        element.addEventListener('click', async () => {
            try {
                if (
                    g_generation_session.request_status ===
                    Enum.RequestStateEnum['Finished']
                ) {
                    toggleTwoButtonsByClass(
                        false,
                        'btnGenerateClass',
                        'btnInterruptClass'
                    )
                    g_can_request_progress = false

                    return null // cann't inturrept a finished generation
                }
                g_generation_session.request_status =
                    Enum.RequestStateEnum['Interrupted']

                g_batch_count_interrupt_status = true // interrupt batch count generations
                const backend_type = html_manip.getBackendType()

                if (backend_type === backendTypeEnum['HordeNative']) {
                    //interrupt the horde

                    await g_horde_generator.interrupt()
                } else {
                    //interrupt auto1111

                    json = await sdapi.requestInterrupt()
                }

                toggleTwoButtonsByClass(
                    false,
                    'btnGenerateClass',
                    'btnInterruptClass'
                )
                g_can_request_progress = false

                // g_can_request_progress = toggleTwoButtons(false,'btnGenerate','btnInterrupt')
            } catch (e) {
                // g_can_request_progress = toggleTwoButtons(false,'btnGenerate','btnInterrupt')
                toggleTwoButtonsByClass(
                    false,
                    'btnGenerateClass',
                    'btnInterruptClass'
                )
                g_can_request_progress = false
                console.warn(e)
            }
        })
    }
)
//REFACTOR: move to psapi.js
//store active layers only if they are not stored.
async function storeActiveLayers() {
    setTimeout(async () => {
        const layers = await app.activeDocument.activeLayers
        console.log('storeActiveLayers: ', layers.length)

        if (layers.length > 0) {
            g_saved_active_layers = layers
            await psapi.unselectActiveLayersExe()
        }
    }, 200)

    // if (g_is_active_layers_stored == false) {
    //   g_saved_active_layers = await app.activeDocument.activeLayers
    //   g_is_active_layers_stored = true
    //   await psapi.unselectActiveLayersExe()
    // } else {
    // }
}
//REFACTOR: move to psapi.js
async function restoreActiveLayers() {
    const layers = await app.activeDocument.activeLayers
    console.log('restoreActiveLayers: ', layers.length)
    if (layers.length == 0) {
        await psapi.selectLayersExe(g_saved_active_layers)
        g_saved_active_layers = []
    }
    // if (g_is_active_layers_stored == true) {
    //   // g_saved_active_layers = await app.activeDocument.activeLayers
    //   await psapi.selectLayersExe(g_saved_active_layers)
    //   g_is_active_layers_stored = false
    //   g_saved_active_layers = []
    // }
}

//store active selection only if they are not stored.
//REFACTOR: move to psapi.js
async function storeActiveSelection() {
    try {
        setTimeout(async () => {
            const layers = await app.activeDocument.activeLayers
            const current_selection = await psapi.checkIfSelectionAreaIsActive()
            console.log('storeActiveSelection: ', current_selection)

            if (current_selection) {
                g_saved_active_selection = current_selection
                await psapi.unSelectMarqueeExe()
            }
        }, 200)
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to psapi.js
async function restoreActiveSelection() {
    try {
        const current_selection = await psapi.checkIfSelectionAreaIsActive()

        console.log('restoreActiveSelection: ', current_selection)
        if (
            !current_selection &&
            psapi.isSelectionValid(g_saved_active_selection)
        ) {
            await psapi.reSelectMarqueeExe(g_saved_active_selection)
            g_saved_active_selection = {}
        }
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
document.querySelector('#taPrompt').addEventListener('focus', async () => {
    // if (!g_generation_session.isLoadingActive) {
    //     console.log('taPrompt focus')
    //     // console.log('we are in prompt textarea')
    //     // console.log("g_is_active_layers_stored: ",g_is_active_layers_stored)
    //     await storeActiveLayers()
    //     await storeActiveSelection()
    //     // await psapi.unselectActiveLayersExe()
    // }
})
//REFACTOR: move to events.js
document.querySelector('#taPrompt').addEventListener('blur', async () => {
    // console.log('taPrompt blur')
    // // console.log('we are out of prompt textarea')
    // // await psapi.unselectActiveLayersExe()
    // // console.log("g_is_active_layers_stored: ",g_is_active_layers_stored)
    // await restoreActiveLayers()
    // await restoreActiveSelection()
})
//REFACTOR: move to events.js
document
    .querySelector('#taNegativePrompt')
    .addEventListener('focus', async () => {
        // if (!g_generation_session.isLoadingActive) {
        //     console.log('taNegativePrompt focus')
        //     // console.log('we are in prompt textarea')
        //     await storeActiveLayers()
        //     await storeActiveSelection()
        //     // await psapi.unselectActiveLayersExe()
        // }
    })
//REFACTOR: move to events.js
document
    .querySelector('#taNegativePrompt')
    .addEventListener('blur', async () => {
        // console.log('taNegativePrompt blur')
        // // console.log('we are out of prompt textarea')
        // // await psapi.unselectActiveLayersExe()
        // await restoreActiveLayers()
        // await restoreActiveSelection()
    })
//REFACTOR: unused, remove?
function updateMetadata(new_metadata) {
    const metadatas = []
    try {
        for (metadata of new_metadata) {
            metadata_json = JSON.parse(metadata)
            console.log('metadata_json:', metadata_json)
            metadatas.push(metadata_json)
        }
    } catch (e) {
        console.warn(e)
    }
    return metadatas
}
//REFACTOR: move to generation_settings.js
async function getSettings() {
    let payload = {}

    try {
        const extension_type = settings_tab.getExtensionType() // get the extension type
        const selectionInfo = await psapi.getSelectionInfoExe()
        payload['selection_info'] = selectionInfo
        const numberOfBatchSize = parseInt(
            document.querySelector('#tiNumberOfBatchSize').value
        )
        const numberOfSteps = document.querySelector('#tiNumberOfSteps').value
        const prompt = html_manip.getPrompt()
        const negative_prompt = html_manip.getNegativePrompt()
        const hi_res_fix = html_manip.getHiResFixs()
        // console.log("prompt:",prompt)
        // console.log("negative_prompt:",negative_prompt)
        const model_index = document.querySelector('#mModelsMenu').selectedIndex
        const upscaler = document.querySelector('#hrModelsMenu').value
        const cfg_scale = document.querySelector('#slCfgScale').value
        //  const model_index = document.querySelector("#")

        function calculateSeed(init_seed, batch_index, batch_size) {
            if (init_seed === -1) return -1
            const seed = init_seed + batch_index * batch_size
            return seed
        }

        const init_seed = parseInt(document.querySelector('#tiSeed').value)
        const seed = calculateSeed(
            init_seed,
            g_current_batch_index,
            numberOfBatchSize
        )

        // const mask_blur = document.querySelector('#slMaskBlur').value
        const use_sharp_mask = settings_tab.getUseSharpMask()
        const mask_blur = html_manip.getMaskBlur()
        const mask_expansion = document.getElementById('slMaskExpansion').value

        const inpaint_full_res_padding =
            document.querySelector('#slInpaintPadding').value

        // console.dir(numberOfImages)
        const bUsePromptShortcut = document.getElementById(
            'chUsePromptShortcut'
        ).checked
        let prompt_shortcut_ui_dict = {}
        try {
            let prompt_shortcut_string =
                document.getElementById('taPromptShortcut').value
            prompt_shortcut_ui_dict = JSON.parse(prompt_shortcut_string)
        } catch (e) {
            console.warn(
                `warning prompt_shortcut_ui_dict is not valid Json obj: ${e}`
            )
            prompt_shortcut_ui_dict = {}
        }

        // const slider_width = document.getElementById("slWidth").value
        // gWidth = getWidthFromSlider(slider_width)
        const original_width = html_manip.getWidth()
        const original_height = html_manip.getHeight()

        const width = general.nearestMultiple(original_width, 64)
        const height = general.nearestMultiple(original_height, 64)

        const hWidth = html_manip.getSliderSdValue_Old('hrWidth', 64)
        const hHeight = html_manip.getSliderSdValue_Old('hrHeight', 64)
        const hSteps = html_manip.getSliderSdValue_Old('hrNumberOfSteps', 1)
        //const hScale = html_manip.getSliderSdValue_Old('hrScale',1)
        console.log('Check')

        const uniqueDocumentId = await getUniqueDocumentId()
        const h_denoising_strength = html_manip.getSliderSdValue_Old(
            'hrDenoisingStrength',
            0.01
        )
        console.log('Check2')

        //Note: store the sampler names in json file if auto is offline or auto api is unmounted

        const sampler_name = html_manip.getCheckedSamplerName()

        const mode = html_manip.getMode()
        const b_restore_faces =
            document.getElementById('chRestoreFaces').checked

        let denoising_strength = h_denoising_strength
        if (mode == 'inpaint' || mode == 'outpaint') {
            var g_use_mask_image = true
            payload['inpaint_full_res'] =
                document.getElementById('chInpaintFullRes').checked
            payload['inpaint_full_res_padding'] = inpaint_full_res_padding * 4

            console.log('g_use_mask_image is ', g_use_mask_image)
            console.log('g_init_image_mask_name is ', g_init_image_mask_name)
            payload['init_image_mask_name'] = g_init_image_mask_name
            payload['inpainting_fill'] = html_manip.getMaskContent()
            payload['mask_expansion'] = mask_expansion
            payload['mask'] = g_generation_session.activeBase64MaskImage

            if (use_sharp_mask === false && payload['mask']) {
                //only if mask is available and sharp_mask is off
                // use blurry and expanded mask
                const iterations = payload['mask_expansion']
                const mask = await py_re.maskExpansionRequest(
                    payload['mask'],
                    iterations
                )
                if (mask) {
                    g_generation_session.base64maskExpansionImage = mask
                    payload['mask'] = mask
                }
            }
        } else if (mode == 'img2img') {
            var g_use_mask_image = false
            delete payload['inpaint_full_res'] //  inpaint full res is not available in img2img mode
            delete payload['inpaint_full_res_padding']
            delete payload['init_image_mask_name']
            delete payload['inpainting_fill']
        }

        if (
            g_sd_mode == 'img2img' ||
            g_sd_mode == 'inpaint' ||
            g_sd_mode == 'outpaint'
        ) {
            console.log(`g_use_mask_image:? ${g_use_mask_image}`)

            denoising_strength = html_manip.getDenoisingStrength()
            payload['denoising_strength'] = denoising_strength
            payload['init_image_name'] = g_init_image_name

            payload['init_images'] = [
                g_generation_session.activeBase64InitImage,
            ]
            payload['image_cfg_scale'] = sd_tab.getImageCfgScaleSDValue() // we may need to check if model is pix2pix

            if (
                scripts.script_store.is_active &&
                scripts.script_store.selected_script_name !== 'None' &&
                scripts.script_store.is_selected_script_available
            ) {
                payload['script_args'] = scripts.script_store.orderedValues()

                payload['script_name'] =
                    scripts.script_store.selected_script_name //'Ultimate SD upscale'
            }
        } else {
            delete payload['script_args']
            delete payload['script_name']
        }

        if (hi_res_fix && width >= 512 && height >= 512) {
            const hr_scale = sd_tab.getHrScaleSliderSDValue()

            payload['enable_hr'] = hi_res_fix
            // payload['firstphase_width'] = width
            // payload['firstphase_height'] = height
            // payload['hr_resize_x'] = hWidth
            // payload['hr_resize_y'] = hHeight
            payload['hr_scale'] = hr_scale // Scale
            payload['hr_upscaler'] = upscaler // Upscaler
            payload['hr_second_pass_steps'] = hSteps // Number of Steps
        } else {
            //fix hi res bug: if we include firstphase_width or firstphase_height in the payload,
            // sd api will use them instead of using width and height variables, even when enable_hr is set to "false"
            delete payload['enable_hr']
            // delete payload['firstphase_width']
            // delete payload['firstphase_height']
        }

        //work with the hord

        // const script_args_json = {
        //   model: "Anything Diffusion",
        //   nsfw: false,
        //   shared_laion: false,
        //   seed_variation: 1,
        //   post_processing_1: "None",
        //   post_processing_2: "None",
        //   post_processing_3: "None"
        // }
        // const script_args = Object.values(script_args_json)

        const backend_type = html_manip.getBackendType()
        if (backend_type === backendTypeEnum['Auto1111HordeExtension']) {
            payload['script_name'] = script_horde.script_name
            payload['script_args'] = script_horde.getScriptArgs()
        } else if (
            payload['script_name'] === script_horde.script_name &&
            backend_type !== backendTypeEnum['Auto1111HordeExtension']
        ) {
            delete payload['script_name']
            delete payload['script_args']
        }

        if (bUsePromptShortcut) {
            //replace the prompt with the prompt shortcut equivalent
            const [new_prompt, new_negative_prompt] =
                py_re.replacePromptsWithShortcuts(
                    prompt,
                    negative_prompt,
                    prompt_shortcut_ui_dict
                )

            //used in generation
            payload['prompt'] = new_prompt
            payload['negative_prompt'] = new_negative_prompt

            //used to when resote settings from metadata
            payload['original_prompt'] = prompt
            payload['original_negative_prompt'] = negative_prompt
        } else {
            //use the same prompt as in the prompt textarea
            payload['prompt'] = prompt
            payload['negative_prompt'] = negative_prompt

            payload['original_prompt'] = prompt
            payload['original_negative_prompt'] = negative_prompt
        }

        payload = {
            ...payload,
            // prompt: prompt,
            // negative_prompt: negative_prompt,
            steps: numberOfSteps,
            // n_iter: numberOfImages,
            sampler_index: sampler_name,
            width: width,
            height: height,
            denoising_strength: denoising_strength,
            batch_size: numberOfBatchSize,
            cfg_scale: cfg_scale,
            seed: seed,
            mask_blur: mask_blur,
            use_sharp_mask: use_sharp_mask,
            use_prompt_shortcut: bUsePromptShortcut,
            prompt_shortcut_ui_dict: prompt_shortcut_ui_dict,
            uniqueDocumentId: uniqueDocumentId,
            mode: mode,
            restore_faces: b_restore_faces,
            // script_args: script_args,
            // script_name:"Run on Stable Horde"
        }
    } catch (e) {
        console.error(e)
    }
    return payload
}
//REFACTOR: move to generation_settings.js
async function getExtraSettings() {
    let payload = {}
    try {
        const html_manip = require('./utility/html_manip')
        const upscaling_resize = html_manip.getUpscaleSize()
        const gfpgan_visibility = html_manip.getGFPGANVisibility()
        const codeformer_visibility = html_manip.getCodeFormerVisibility()
        const codeformer_weight = html_manip.getCodeFormerWeight()
        const selection_info = await psapi.getSelectionInfoExe()
        const width = selection_info.width * upscaling_resize
        const height = selection_info.height * upscaling_resize
        //resize_mode = 0 means "resize to upscaling_resize"
        //resize_mode = 1 means "resize to width and height"
        payload['resize_mode'] = 0
        payload['show_extras_results'] = 0
        payload['gfpgan_visibility'] = gfpgan_visibility
        payload['codeformer_visibility'] = codeformer_visibility
        payload['codeformer_weight'] = codeformer_weight
        payload['upscaling_resize'] = upscaling_resize
        payload['upscaling_resize_w'] = width
        payload['upscaling_resize_h'] = height
        payload['upscaling_crop'] = true
        const upscaler1 = document.querySelector('#hrModelsMenuUpscale1').value
        payload['upscaler_1'] = upscaler1 === undefined ? 'None' : upscaler1
        const upscaler2 = document.querySelector('#hrModelsMenuUpscale2').value
        payload['upscaler_2'] = upscaler2 === undefined ? 'None' : upscaler2
        const extras_upscaler_2_visibility = html_manip.getUpscaler2Visibility()
        payload['extras_upscaler_2_visibility'] = extras_upscaler_2_visibility
        payload['upscale_first'] = false
        const uniqueDocumentId = await getUniqueDocumentId()
        payload['uniqueDocumentId'] = uniqueDocumentId

        // const layer = await app.activeDocument.activeLayers[0]
        const layer = await app.activeDocument.activeLayers[0]
        const old_name = layer.name

        // image_name = await app.activeDocument.activeLayers[0].name

        //convert layer name to a file name
        let image_name = psapi.layerNameToFileName(
            old_name,
            layer.id,
            random_session_id
        )
        image_name = `${image_name}.png`

        const base64_image = g_generation_session.activeBase64InitImage

        payload['image'] = base64_image
    } catch (e) {
        console.error(e)
    }
    return payload
}
//REFACTOR: move to generation_settings.js
async function getExtraSettings() {
    let payload = {}
    try {
        const html_manip = require('./utility/html_manip')
        const upscaling_resize = html_manip.getUpscaleSize()
        const gfpgan_visibility = html_manip.getGFPGANVisibility()
        const codeformer_visibility = html_manip.getCodeFormerVisibility()
        const codeformer_weight = html_manip.getCodeFormerWeight()
        const selection_info = await psapi.getSelectionInfoExe()
        const width = selection_info.width * upscaling_resize
        const height = selection_info.height * upscaling_resize
        //resize_mode = 0 means "resize to upscaling_resize"
        //resize_mode = 1 means "resize to width and height"
        payload['resize_mode'] = 0
        payload['show_extras_results'] = 0
        payload['gfpgan_visibility'] = gfpgan_visibility
        payload['codeformer_visibility'] = codeformer_visibility
        payload['codeformer_weight'] = codeformer_weight
        payload['upscaling_resize'] = upscaling_resize
        payload['upscaling_resize_w'] = width
        payload['upscaling_resize_h'] = height
        payload['upscaling_crop'] = true
        const upscaler1 = document.querySelector('#hrModelsMenuUpscale1').value
        payload['upscaler_1'] = upscaler1 === undefined ? 'None' : upscaler1
        const upscaler2 = document.querySelector('#hrModelsMenuUpscale2').value
        payload['upscaler_2'] = upscaler2 === undefined ? 'None' : upscaler2
        const extras_upscaler_2_visibility = html_manip.getUpscaler2Visibility()
        payload['extras_upscaler_2_visibility'] = extras_upscaler_2_visibility
        payload['upscale_first'] = false
        const uniqueDocumentId = await getUniqueDocumentId()
        payload['uniqueDocumentId'] = uniqueDocumentId

        // const layer = await app.activeDocument.activeLayers[0]
        const layer = await app.activeDocument.activeLayers[0]
        const old_name = layer.name

        // image_name = await app.activeDocument.activeLayers[0].name

        //convert layer name to a file name
        let image_name = psapi.layerNameToFileName(
            old_name,
            layer.id,
            random_session_id
        )
        image_name = `${image_name}.png`

        const base64_image = g_generation_session.activeBase64InitImage

        payload['image'] = base64_image
    } catch (e) {
        console.error(e)
    }
    return payload
}
//REFACTOR: move to generation.js
async function generateImg2Img(settings) {
    let json = {}
    try {
        const backend_type = html_manip.getBackendType()
        if (backend_type === backendTypeEnum['HordeNative']) {
            json = await g_horde_generator.generate()
            // json = await g_horde_generator.toGenerationFormat(images_info)
            // json = { images_info: images_info }
        } else if (
            backend_type === backendTypeEnum['Auto1111'] ||
            backend_type === backendTypeEnum['Auto1111HordeExtension']
        ) {
            //checks on index 0 as if not enabled ingores the rest
            const b_enable_control_net = control_net.isControlNetModeEnable()

            if (b_enable_control_net) {
                //use control net
                json = await sdapi.requestControlNetImg2Img(settings)
            } else {
                json = await sdapi.requestImg2Img(settings)
            }
        }
    } catch (e) {
        console.warn(e)
        json = {}
    }

    return json
}
//REFACTOR: move to generation.js
async function generateTxt2Img(settings) {
    let json = {}
    try {
        const backend_type = html_manip.getBackendType()
        if (backend_type === backendTypeEnum['HordeNative']) {
            json = await g_horde_generator.generate()
            // json = await g_horde_generator.toGenerationFormat(images_info)
            // json = { images_info: images_info }
        } else if (
            backend_type === backendTypeEnum['Auto1111'] ||
            backend_type === backendTypeEnum['Auto1111HordeExtension']
        ) {
            // const b_enable_control_net = control_net.getEnableControlNet()
            const b_enable_control_net = control_net.isControlNetModeEnable()

            if (b_enable_control_net) {
                //use control net

                json = await sdapi.requestControlNetTxt2Img(settings)
            } else {
                json = await sdapi.requestTxt2Img(settings)
            }
        }
    } catch (e) {
        console.warn(e)
        json = {}
    }

    return json
}
//REFACTOR: move to selection.js
async function hasSelectionChanged(new_selection, old_selection) {
    if (
        new_selection.left === old_selection.left &&
        new_selection.bottom === old_selection.bottom &&
        new_selection.right === old_selection.right &&
        new_selection.top === old_selection.top
    ) {
        return false
    } else {
        return true
    }
}
//REFACTOR: move to generation.js
async function easyModeGenerate(mode) {
    try {
        if (
            g_generation_session.request_status !==
            Enum.RequestStateEnum['Finished']
        ) {
            app.showAlert(
                'A generation is still active in the background. \nPlease check your Automatic1111 command line.'
            )
            return null
        }

        g_generation_session.request_status =
            Enum.RequestStateEnum['Generating']
        await executeAsModal(async (context) => {
            const document_type = await findDocumentType()

            const history_id = await context.hostControl.suspendHistory({
                documentID: app.activeDocument.id, //TODO: change this to the session document id
                name: 'Correct Background',
            })
            //store selection
            //store active layer
            const selectionInfo = await psapi.getSelectionInfoExe()
            await psapi.unSelectMarqueeExe()
            const active_layers = app.activeDocument.activeLayers

            //1)check if the documnet has a background layer

            await correctDocumentType(document_type)

            //retore selection
            //restore active layer
            await psapi.reSelectMarqueeExe(selectionInfo)
            await psapi.selectLayersExe(active_layers)
            await context.hostControl.resumeHistory(history_id)
        })

        // if (
        //     (await layer_util.hasBackgroundLayer()) === false && //doesn't have backround layer
        //     (await note.Notification.backgroundLayerIsMissing()) === false //and the user cancled the creation of background layer
        // ) {
        //     // const is_canceld  =
        //     //     await note.Notification.backgroundLayerIsMissing() //

        //     return false
        // }
        const backend_type = html_manip.getBackendType()
        if (
            backend_type === backendTypeEnum['Auto1111'] ||
            backend_type === backendTypeEnum['Auto1111HordeExtension']
        ) {
            g_automatic_status = await checkAutoStatus()
            await displayNotification(g_automatic_status)
            if (
                g_automatic_status === Enum.AutomaticStatusEnum['Offline'] ||
                g_automatic_status === Enum.AutomaticStatusEnum['RunningNoApi']
            ) {
                g_generation_session.request_status =
                    Enum.RequestStateEnum['Finished']
                return false
            }
        }

        let active_layer = await app.activeDocument.activeLayers[0] // store the active layer so we could reselected after the session end clean up
        //make sure you have selection area active on the canvas
        const isSelectionAreaValid = await psapi.checkIfSelectionAreaIsActive()
        if (
            !isSelectionAreaValid && // no selection area
            (await note.Notification.inactiveSelectionArea(
                g_generation_session.isActive()
            )) === false // means did not activate the session selection area if it's available
        ) {
            g_generation_session.request_status =
                Enum.RequestStateEnum['Finished']
            return null
        }

        console.log('easyModeGenerate mdoe: ', mode)
        if (psapi.isSelectionValid(g_generation_session.selectionInfo)) {
            // check we have an old selection stored
            const new_selection = await psapi.getSelectionInfoExe()
            if (
                await hasSelectionChanged(
                    new_selection,
                    g_generation_session.selectionInfo
                )
            ) {
                // check the new selection is difference than the old
                // end current session
                g_generation_session.selectionInfo = new_selection
                try {
                    await g_generation_session.endSession(
                        session.GarbageCollectionState['Accept']
                    ) //end session and accept all images
                    g_ui.onEndSessionUI()

                    // await acceptAll()
                } catch (e) {
                    console.warn(e)
                }
            }
        } else {
            // store selection value
            g_generation_session.selectionInfo =
                await psapi.getSelectionInfoExe()
        }

        if (g_generation_session.isActive()) {
            //active session
            //
            if (g_generation_session.mode !== mode) {
                //active session but it's a new mode

                await g_generation_session.endSession(
                    session.GarbageCollectionState['Accept']
                )
                g_ui.onEndSessionUI()
                //start new session after you ended the old one
                await g_generation_session.startSession()

                g_generation_session.mode = mode
            }
        } else {
            // new session
            g_generation_session.mode = mode
            await g_generation_session.startSession() //start the session and create a output folder
        }

        await psapi.selectLayersExe([active_layer]) //reselect the active layer since the clean up of the session sometime will change which layer is selected
        if (mode === 'txt2img') {
            //Note: keep it for clearity/ readibility
        } else if (mode === 'img2img' || mode === 'upscale') {
            await snapAndFillHandler()
        } else if (mode === 'inpaint') {
            await btnInitInpaintHandler()
        } else if (mode === 'outpaint') {
            await easyModeOutpaint()
        }

        //safe to close the previous generation_session outputfolder, since closing a folder will unselect any layer in it.
        ////and the plugin may still need those layers for inpainting mode for example.

        await g_generation_session.closePreviousOutputGroup()

        const settings =
            mode === 'upscale' ? await getExtraSettings() : await getSettings()

        g_generation_session.last_settings = settings
        // g_generation_session.is_control_net = control_net.getEnableControlNet()
        g_generation_session.is_control_net =
            control_net.isControlNetModeEnable()

        await generate(settings, mode)

        // await g_generation_session.deleteProgressLayer() // delete the old progress layer
        await g_generation_session.deleteProgressImage()
    } catch (e) {
        await g_generation_session.deleteProgressImage()
        console.warn(e)
        g_generation_session.request_status = Enum.RequestStateEnum['Finished']
    }
    toggleTwoButtonsByClass(false, 'btnGenerateClass', 'btnInterruptClass')
    g_can_request_progress = false

    g_generation_session.request_status = Enum.RequestStateEnum['Finished']

    if (g_generation_session.sudo_timer_id) {
        //disable the sudo timer at the end of the generation
        g_generation_session.sudo_timer_id = clearInterval(
            g_generation_session.sudo_timer_id
        )
    }
}

//REFACTOR: move to generation.js
async function generate(settings, mode) {
    try {
        //pre generation
        // toggleGenerateInterruptButton(true)

        // const isFirstGeneration = !(g_is_generation_session_active) // check if this is the first generation in the session
        // const isFirstGeneration = !(g_generation_session.isActive()) // check if this is the first generation in the session
        const isFirstGeneration = g_generation_session.isFirstGeneration

        // g_generation_session.startSession()
        g_generation_session.activate()

        g_ui.onStartSessionUI()
        // toggleTwoButtons(true,'btnGenerate','btnInterrupt')
        toggleTwoButtonsByClass(true, 'btnGenerateClass', 'btnInterruptClass')
        g_can_request_progress = true
        //wait 2 seconds till you check for progress

        if (
            html_manip.getBackendType() !== backendTypeEnum['HordeNative'] // anything other than horde native
        ) {
            setTimeout(async function () {
                // change this to setInterval()
                await progressRecursive()
            }, 2000)
        }

        if (
            html_manip.getBackendType() === backendTypeEnum['Auto1111'] &&
            g_generation_session.is_control_net
        ) {
            g_generation_session.sudo_timer_id = general.sudoTimer()
        }

        console.log(settings)

        g_generation_session.request_status =
            Enum.RequestStateEnum['Generating']
        let json = {}
        if (mode == 'txt2img') {
            json = await generateTxt2Img(settings)
        } else if (
            mode == 'img2img' ||
            mode == 'inpaint' ||
            mode == 'outpaint'
        ) {
            // json = await sdapi.requestImg2Img(settings)

            json = await generateImg2Img(settings)
        } else if (mode == 'upscale') {
            json = await sdapi.requestExtraSingleImage(settings)
        }

        // if (g_sd_mode == 'outpaint') {
        //     // await easyModeOutpaint()
        //     json = await sdapi.requestImg2Img(settings)

        //     // await setTimeout(async ()=> {
        //     //   json = await sdapi.requestImg2Img(settings)

        //     // },5000)
        // }
        if (
            g_generation_session.request_status ===
            Enum.RequestStateEnum['Interrupted']
        ) {
            //when generate request get interrupted. reset progress bar to 0, discard any meta data and images returned from the proxy server by returning from the function.
            html_manip.updateProgressBarsHtml(0)
            console.log(
                'before delete g_generation_session.progress_layer: ',
                g_generation_session.progress_layer
            )
            await g_generation_session.deleteProgressImage()
            console.log(
                'after delete g_generation_session.progress_layer: ',
                g_generation_session.progress_layer
            )
            //check whether request was "generate" or "generate more"
            //if it's generate discard the session
            if (isFirstGeneration) {
                await loadViewerImages()
                await g_generation_session.endSession(
                    session.GarbageCollectionState['Discard']
                ) //end session and delete all images
                g_ui.onEndSessionUI()

                // //delete all mask related layers
            }
            g_generation_session.request_status =
                Enum.RequestStateEnum['Finished']
            return null
        }

        // check if json is empty {}, {} means the proxy server didn't return a valid data
        if (Object.keys(json).length === 0) {
            if (isFirstGeneration) {
                await g_generation_session.endSession(
                    session.GarbageCollectionState['Discard']
                ) //end session and delete all images
                g_ui.onEndSessionUI()

                // //delete all mask related layers
            }
            g_generation_session.request_status =
                Enum.RequestStateEnum['Finished']
            return null
        }

        //post generation: will execute only if the generate request doesn't get interrupted
        //get the updated metadata from json response

        // g_metadatas = updateMetadata(json.images_info.auto_metadata)
        g_last_seed = json.images_info[0]?.auto_metadata?.Seed
        //finished generating, set the button back to generate

        // toggleTwoButtons(false,'btnGenerate','btnInterrupt')
        toggleTwoButtonsByClass(false, 'btnGenerateClass', 'btnInterruptClass')
        g_can_request_progress = false
        html_manip.updateProgressBarsHtml(0)

        const images_info = json?.images_info
        // gImage_paths = images_info.images_paths
        //open the generated images from disk and load them onto the canvas
        // const b_use_silent_import =
        //     document.getElementById('chUseSilentMode').checked

        if (isFirstGeneration) {
            //this is new generation session

            g_generation_session.image_paths_to_layers =
                await silentImagesToLayersExe(images_info)

            g_generation_session.base64OutputImages = {} //delete all previouse images, Note move this to session end ()
            for (const image_info of images_info) {
                const path = image_info['path']
                const base64_image = image_info['base64']
                g_generation_session.base64OutputImages[path] = base64_image
                const [document_name, image_name] = path.split('/')
                await saveFileInSubFolder(
                    base64_image,
                    document_name,
                    image_name
                ) //save the output image
                const json_file_name = `${image_name.split('.')[0]}.json`
                settings['auto_metadata'] = image_info?.auto_metadata
                await saveJsonFileInSubFolder(
                    settings,
                    document_name,
                    json_file_name
                ) //save the settings
            }

            g_number_generation_per_session = 1
            g_generation_session.isFirstGeneration = false
        } else {
            // generation session is active so we will generate more

            let last_images_paths = await silentImagesToLayersExe(images_info)

            for (const image_info of images_info) {
                const path = image_info['path']
                const base64_image = image_info['base64']
                g_generation_session.base64OutputImages[path] = base64_image
                const [document_name, image_name] = path.split('/')
                await saveFileInSubFolder(
                    base64_image,
                    document_name,
                    image_name
                )
                const json_file_name = `${image_name.split('.')[0]}.json`
                settings['auto_metadata'] = image_info?.auto_metadata
                await saveJsonFileInSubFolder(
                    settings,
                    document_name,
                    json_file_name
                ) //save the settings
            }

            g_generation_session.image_paths_to_layers = {
                ...g_generation_session.image_paths_to_layers,
                ...last_images_paths,
            }
            g_number_generation_per_session++
        }
        await psapi.reSelectMarqueeExe(g_generation_session.selectionInfo)
        //update the viewer
        await loadViewerImages()

        //esnures that progress bars are set to 0 (as last progress request call might have returned less than 100%)
        updateProgressBarsHtml(0)
    } catch (e) {
        console.error(`btnGenerate.click(): `, e)
        g_generation_session.request_status = Enum.RequestStateEnum['Finished']
    }
    g_generation_session.request_status = Enum.RequestStateEnum['Finished']
}
//REFACTOR: move to events.js
Array.from(document.getElementsByClassName('btnGenerateClass')).forEach(
    (btn) => {
        btn.addEventListener('click', async (evt) => {
            tempDisableElement(evt.target, 5000)
            const numberOfBatchCount = parseInt(
                document.querySelector('#tiNumberOfBatchCount').value
            )
            for (let i = 0; i < numberOfBatchCount; i++) {
                if (g_batch_count_interrupt_status === true) {
                    break
                }
                g_current_batch_index = i
                await easyModeGenerate(g_sd_mode)
            }
            g_batch_count_interrupt_status = false // reset for next generation
            g_current_batch_index = 0 // reset curent_batch_number
        })
    }
) //REFACTOR: move to events.js

document
    .getElementById('btnRefreshModels')
    .addEventListener('click', async (e) => {
        await refreshUI()
        await sd_tab.refreshSDTab()
        tempDisableElement(e.target, 3000)
    })
//REFACTOR: move to events.js
document.querySelector('#mModelsMenu').addEventListener('change', (evt) => {
    const model_index = evt.target.selectedIndex
    console.log(`Selected item: ${evt.target.selectedIndex}`)
    let model = g_models[0]
    if (model_index < g_models.length) {
        model = g_models[model_index]
    }
    // g_model_name = `${model.model_name}.ckpt`
    g_model_title = model.title
    console.log('g_model_title: ', g_model_title)
    sdapi.requestSwapModel(g_model_title)
})
//REFACTOR: move to events.js
document
    .getElementById('btnLayerToSelection')
    .addEventListener('click', async () => {
        try {
            const isSelectionAreaValid =
                await psapi.checkIfSelectionAreaIsActive()
            if (isSelectionAreaValid) {
                const validSelection = isSelectionAreaValid
                await psapi.layerToSelection(validSelection)
            } else {
                await psapi.promptForMarqueeTool()
            }
        } catch (e) {
            console.warn(e)
        }
    })
//REFACTOR: move to events.js
document
    .getElementById('btnSetInitImageViewer')
    .addEventListener('click', async () => {
        //set init image event listener, use when session is active
        const layer = await app.activeDocument.activeLayers[0]
        const image_info = await psapi.silentSetInitImage(
            layer,
            random_session_id
        )
        const image_name = image_info['name']
        const path = `./server/python_server/init_images/${image_name}`
        g_viewer_manager.addInitImageLayers(layer, path, false)
        await g_viewer_manager.loadInitImageViewerObject(path)
        // await loadInitImageViewerObject(
        //     group,
        //     snapshot,
        //     solid_background,
        //     path,
        //     auto_delete,
        //     base64_image
        // )
    })
//REFACTOR: move to psapi.js
async function setMaskViewer() {
    try {
        await executeAsModal(async () => {
            if (g_viewer_manager.mask_solid_background) {
                g_viewer_manager.mask_solid_background.visible = true
            }
        })
        const layer = g_viewer_manager.maskGroup
        // const layer = await app.activeDocument.activeLayers[0]
        const mask_info = await psapi.silentSetInitImageMask(
            layer,
            random_session_id
        )
        const image_name = mask_info['name']
        const path = `./server/python_server/init_images/${image_name}`
        g_viewer_manager.addMaskLayers(layer, path, false, mask_info['base64']) //can be autodeleted?
        await psapi.unselectActiveLayersExe()
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
document
    .getElementById('btnSetMaskViewer')
    .addEventListener('click', async () => {
        await setMaskViewer()
    })

//REFACTOR: move to psapi.js
function moveElementToAnotherTab(elementId, newParentId) {
    const element = document.getElementById(elementId)
    document.getElementById(newParentId).appendChild(element)
}

// moveElementToAnotherTab("batchNumberUi","batchNumberViewerTabContainer")
//REFACTOR: move to ui.js
function updateProgressBarsHtml(new_value) {
    document.querySelectorAll('.pProgressBars').forEach((el) => {
        // id = el.getAttribute("id")
        // console.log("progressbar id:", id)
        el.setAttribute('value', new_value)
    })
    document.querySelectorAll('.lProgressLabel').forEach((el) => {
        console.log('updateProgressBarsHtml: ', new_value)
        if (new_value > 0) el.innerHTML = 'In progress...'
        else el.innerHTML = 'No work in progress'
    })
    // document.querySelector('#pProgressBar').value
}
//REFACTOR: move to ui.js
async function updateProgressImage(progress_base64) {
    try {
        await executeAsModal(async (context) => {
            const history_id = await context.hostControl.suspendHistory({
                documentID: app.activeDocument.id, //TODO: change this to the session document id
                name: 'Progress Image',
            })
            await g_generation_session.deleteProgressLayer() // delete the old progress layer

            //update the progress image
            const selection_info = await g_generation_session.selectionInfo
            const b_exsit = layer_util.Layer.doesLayerExist(
                g_generation_session.progress_layer
            )
            if (!b_exsit) {
                const layer = await io.IO.base64ToLayer(
                    progress_base64,
                    'temp_progress_image.png',
                    selection_info.left,
                    selection_info.top,
                    selection_info.width,
                    selection_info.height
                )
                g_generation_session.progress_layer = layer // sotre the new progress layer// TODO: make sure you delete the progress layer when the geneeration request end
            } else {
                // if ,somehow, the layer still exsit
                await layer_util.deleteLayers([
                    g_generation_session.progress_layer,
                ]) // delete the old progress layer
            }
            await context.hostControl.resumeHistory(history_id)
        })
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to ui.js
async function progressRecursive() {
    try {
        let json = await sdapi.requestProgress()
        // document.querySelector('#pProgressBar').value = json.progress * 100
        const progress_value = json.progress * 100
        if (g_generation_session.sudo_timer_id) {
            //for sudo timer update
            //for controlnet only: disable the sudo timer when the real timer start
            // debugger
            if (progress_value > 1) {
                //disable the sudo timer at the end of the generation
                g_generation_session.sudo_timer_id = clearInterval(
                    g_generation_session.sudo_timer_id
                )
            }
        } else {
            //for normal progress bar

            html_manip.updateProgressBarsHtml(progress_value)
        }

        if (
            json?.current_image &&
            g_generation_session.request_status ===
                Enum.RequestStateEnum['Generating']
        ) {
            const base64_url = general.base64ToBase64Url(json.current_image)

            const progress_image_html = document.getElementById('progressImage')
            const container_width = document.querySelector(
                '#divProgressImageViewerContainer'
            ).offsetWidth
            //*) find the parent container width
            //*) set the width of the image to auto
            //*) scale to closest while keeping the ratio, the hieght should not be larger than the width of the container

            // height: 10000px;
            // width: auto;
            // background-size: contain;

            // progress_image_html.style.backgroundSize = 'contain'
            // progress_image_html.style.height = '10000px'

            // document.getElementById(
            //     'divProgressImageViewerContainer'
            // ).style.backgroundImage = `url('${base64_url}')`

            html_manip.setProgressImageSrc(base64_url)

            // if (progress_image_html.style.width !== 'auto') {
            //     progress_image_html.style.width = 'auto'
            // }
            // if ((progress_image_html.style.height = 'auto' !== 'auto')) {
            //     progress_image_html.style.height = 'auto'
            // }

            // progress_image_html = new_height
            // progress_image_html.style.width = progress_image_html.naturalWidth
            // progress_image_html.style.height = progress_image_html.naturalHeight

            if (
                g_generation_session.last_settings.batch_size === 1 &&
                settings_tab.getUseLiveProgressImage()
            ) {
                //only update the canvas if the number of images are one
                //don't update the canvas with multiple images.
                await updateProgressImage(json.current_image)
            }
        }
        if (g_generation_session.isActive() && g_can_request_progress == true) {
            //refactor this code
            setTimeout(async () => {
                await progressRecursive()
            }, 1000)
        }
    } catch (e) {
        if (
            g_generation_session.isActive() &&
            g_can_request_progress === true
        ) {
            setTimeout(async () => {
                await progressRecursive()
            }, 1000)
        }
    }
}
//REFACTOR: move to ui.js
function changeImage() {
    let img = document.getElementById('img1')
    img.src = 'https://source.unsplash.com/random'
}

// document.getElementById('btnChangeImage').addEventListener('click', changeImage)
//REFACTOR: move to psapi.js
async function imageToSmartObject() {
    const { batchPlay } = require('photoshop').action
    const { executeAsModal } = require('photoshop').core

    try {
        // const file = await fs.getFileForOpening()
        // token = await fs.getEntryForPersistentToken(file);
        // const entry = await fs.getEntryForPersistentToken(token);
        // const session_token = await fs.createSessionToken(entry);
        // // let token = await fs.createSessionToken(entry)
        await executeAsModal(
            async () => {
                console.log('imageToSmartObject():')
                const storage = require('uxp').storage
                const fs = storage.localFileSystem
                let pluginFolder = await fs.getPluginFolder()
                let img = await pluginFolder.getEntry(
                    'output- 1672730735.1670313.png'
                )
                const result = await batchPlay(
                    [
                        {
                            _obj: 'placeEvent',
                            ID: 95,
                            null: {
                                _path: img,
                                _kind: 'local',
                            },
                            freeTransformCenterState: {
                                _enum: 'quadCenterState',
                                _value: 'QCSAverage',
                            },
                            offset: {
                                _obj: 'offset',
                                horizontal: {
                                    _unit: 'pixelsUnit',
                                    _value: 0,
                                },
                                vertical: {
                                    _unit: 'pixelsUnit',
                                    _value: 0,
                                },
                            },
                            replaceLayer: {
                                _obj: 'placeEvent',
                                from: {
                                    _ref: 'layer',
                                    _id: 56,
                                },
                                to: {
                                    _ref: 'layer',
                                    _id: 70,
                                },
                            },
                            _options: {
                                dialogOptions: 'dontDisplay',
                            },
                        },
                    ],
                    {
                        synchronousExecution: true,
                        modalBehavior: 'execute',
                    }
                )
            },
            {
                commandName: 'Create Label',
            }
        )
    } catch (e) {
        console.log('imageToSmartObject() => error: ')
        console.warn(e)
    }
}

// document.getElementById('btnNewLayer').addEventListener('click', imageToSmartObject )
//REFACTOR: move to psapi.js
async function placeEmbedded(image_name, dir_entery) {
    //silent importer

    try {
        // console.log('placeEmbedded(): image_path: ', image_path)

        const formats = require('uxp').storage.formats
        const storage = require('uxp').storage
        const fs = storage.localFileSystem
        // const names = image_path.split('/')
        // const length = names.length
        // const image_name = names[length - 1]
        // const project_name = names[length - 2]
        let image_dir = dir_entery
        // const image_dir = `./server/python_server/output/${project_name}`
        // image_path = "output/f027258e-71b8-430a-9396-0a19425f2b44/output- 1674323725.126322.png"

        // let img_dir = await .getEntry(image_dir)
        // const file = await img_dir.createFile('output- 1674298902.0571606.png', {overwrite: true});

        const file = await image_dir.createFile(image_name, { overwrite: true })

        const img = await file.read({ format: formats.binary })
        const token = await storage.localFileSystem.createSessionToken(file)
        let place_event_result
        await executeAsModal(async () => {
            const result = await batchPlay(
                [
                    {
                        _obj: 'placeEvent',
                        ID: 6,
                        null: {
                            _path: token,
                            _kind: 'local',
                        },
                        freeTransformCenterState: {
                            _enum: 'quadCenterState',
                            _value: 'QCSAverage',
                        },
                        offset: {
                            _obj: 'offset',
                            horizontal: {
                                _unit: 'pixelsUnit',
                                _value: 0,
                            },
                            vertical: {
                                _unit: 'pixelsUnit',
                                _value: 0,
                            },
                        },
                        _isCommand: true,
                        _options: {
                            dialogOptions: 'dontDisplay',
                        },
                    },
                ],
                {
                    synchronousExecution: true,
                    modalBehavior: 'execute',
                }
            )
            console.log('placeEmbedd batchPlay result: ', result)

            place_event_result = result[0]
        })

        return place_event_result
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to psapi.js
function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64)
    var len = binary_string.length
    var bytes = new Uint8Array(len)
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i)
    }
    return bytes.buffer
}
//REFACTOR: move to psapi.js
function _arrayBufferToBase64(buffer) {
    var binary = ''
    var bytes = new Uint8Array(buffer)
    var len = bytes.byteLength
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i])
    }
    return window.btoa(binary)
}

//REFACTOR: move to io.js
async function getDocFolder(doc_uuid) {
    try {
        // const uuid = await getUniqueDocumentId()
        const data_folder = await storage.localFileSystem.getDataFolder()

        let doc_folder
        try {
            doc_folder = await data_folder.getEntry(doc_uuid)
        } catch (e) {
            console.warn(e)
            //create document folder
            doc_folder = await data_folder.createFolder(doc_uuid)
        }

        return doc_folder
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to document.js
async function getCurrentDocFolder() {
    //move to a global utililty lib
    const uuid = await getUniqueDocumentId()

    let doc_folder = await getDocFolder(uuid)
    return doc_folder
}
//REFACTOR: move to document.js
async function getInitImagesDir() {
    const uuid = await getUniqueDocumentId()

    let doc_folder = await getDocFolder(uuid)
    let init_folder
    try {
        init_folder = await doc_folder.getEntry('init_images')
    } catch (e) {
        console.warn(e)
        //create document folder
        init_folder = await doc_folder.createFolder('init_images')
    }
    return init_folder
}
//REFACTOR: move to document.js
async function saveFileInSubFolder(b64Image, sub_folder_name, file_name) {
    // const b64Image =
    //     'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMO0TAAD//2Anhf4QtqobAAAAAElFTkSuQmCC'

    const img = _base64ToArrayBuffer(b64Image)

    // const img_name = 'temp_output_image.png'
    const img_name = file_name
    const folder = await storage.localFileSystem.getDataFolder()
    const documentFolderName = sub_folder_name
    let documentFolder
    try {
        documentFolder = await folder.getEntry(documentFolderName)
    } catch (e) {
        console.warn(e)
        //create document folder
        documentFolder = await folder.createFolder(documentFolderName)
    }

    console.log('documentFolder.nativePath: ', documentFolder.nativePath)
    const file = await documentFolder.createFile(img_name, { overwrite: true })

    await file.write(img, { format: storage.formats.binary })

    const token = await storage.localFileSystem.createSessionToken(file) // batchPlay requires a token on _path
}
//REFACTOR: move to document.js
async function saveJsonFileInSubFolder(json, sub_folder_name, file_name) {
    // const b64Image =
    //     'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMO0TAAD//2Anhf4QtqobAAAAAElFTkSuQmCC'

    // const img_name = 'temp_output_image.png'

    const json_file_name = file_name

    const folder = await storage.localFileSystem.getDataFolder()
    const documentFolderName = sub_folder_name
    let documentFolder
    try {
        documentFolder = await folder.getEntry(documentFolderName)
    } catch (e) {
        console.warn(e)
        //create document folder
        documentFolder = await folder.createFolder(documentFolderName)
    }

    console.log('documentFolder.nativePath: ', documentFolder.nativePath)
    const file = await documentFolder.createFile(json_file_name, {
        type: storage.types.file,
        overwrite: true,
    })

    const JSONInPrettyFormat = JSON.stringify(json, undefined, 4)
    await file.write(JSONInPrettyFormat, {
        format: storage.formats.utf8,
        append: false,
    })

    const token = await storage.localFileSystem.createSessionToken(file) // batchPlay requires a token on _path
}
//REFACTOR: move to document.js
async function base64ToFile(b64Image, image_name = 'output_image.png') {
    // const b64Image =
    //     'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMO0TAAD//2Anhf4QtqobAAAAAElFTkSuQmCC'
    try {
        const img = _base64ToArrayBuffer(b64Image)

        const img_name = image_name

        const folder = await storage.localFileSystem.getTemporaryFolder()
        const file = await folder.createFile(img_name, { overwrite: true })

        await file.write(img, { format: storage.formats.binary })

        const token = await storage.localFileSystem.createSessionToken(file) // batchPlay requires a token on _path

        let place_event_result
        let imported_layer
        await executeAsModal(async () => {
            const result = await batchPlay(
                [
                    {
                        _obj: 'placeEvent',
                        // ID: 6,
                        null: {
                            _path: token,
                            _kind: 'local',
                        },
                        freeTransformCenterState: {
                            _enum: 'quadCenterState',
                            _value: 'QCSAverage',
                        },
                        offset: {
                            _obj: 'offset',
                            horizontal: {
                                _unit: 'pixelsUnit',
                                _value: 0,
                            },
                            vertical: {
                                _unit: 'pixelsUnit',
                                _value: 0,
                            },
                        },
                        _isCommand: true,
                        _options: {
                            dialogOptions: 'dontDisplay',
                        },
                    },
                ],
                {
                    synchronousExecution: true,
                    modalBehavior: 'execute',
                }
            )
            console.log('placeEmbedd batchPlay result: ', result)

            place_event_result = result[0]
            imported_layer = await app.activeDocument.activeLayers[0]
        })
        return imported_layer
    } catch (e) {
        console.warn(e)
    }

    // return place_event_result
}
//REFACTOR: move to psapi.js
async function placeImageB64ToLayer(image_path, entery) {
    //silent importer

    try {
        console.log('placeEmbedded(): image_path: ', image_path)

        const formats = require('uxp').storage.formats
        const storage = require('uxp').storage
        const fs = storage.localFileSystem

        const names = image_path.split('/')
        const length = names.length
        const image_name = names[length - 1]
        const project_name = names[length - 2]
        let pluginFolder = await fs.getPluginFolder()

        const image_dir = `./server/python_server/output/${project_name}`
        // image_path = "output/f027258e-71b8-430a-9396-0a19425f2b44/output- 1674323725.126322.png"

        let img_dir = await pluginFolder.getEntry(image_dir)
        // const file = await img_dir.createFile('output- 1674298902.0571606.png', {overwrite: true});

        const file = await img_dir.createFile(image_name, { overwrite: true })

        const img = await file.read({ format: formats.binary })
        const token = await storage.localFileSystem.createSessionToken(file)
        let place_event_result
        await executeAsModal(async () => {
            const result = await batchPlay(
                [
                    {
                        _obj: 'placeEvent',
                        ID: 6,
                        null: {
                            _path: token,
                            _kind: 'local',
                        },
                        freeTransformCenterState: {
                            _enum: 'quadCenterState',
                            _value: 'QCSAverage',
                        },
                        offset: {
                            _obj: 'offset',
                            horizontal: {
                                _unit: 'pixelsUnit',
                                _value: 0,
                            },
                            vertical: {
                                _unit: 'pixelsUnit',
                                _value: 0,
                            },
                        },
                        _isCommand: true,
                        _options: {
                            dialogOptions: 'dontDisplay',
                        },
                    },
                ],
                {
                    synchronousExecution: true,
                    modalBehavior: 'execute',
                }
            )
            console.log('placeEmbedd batchPlay result: ', result)

            place_event_result = result[0]
        })

        return place_event_result
    } catch (e) {
        console.warn(e)
    }
}

// document.getElementById('btnImageFileToLayer').addEventListener('click', placeEmbedded)

// open an image in the plugin folder as new document
//REFACTOR: move to document.js
async function openImageAction() {
    const storage = require('uxp').storage
    const fs = storage.localFileSystem
    try {
        let pluginFolder = await fs.getPluginFolder()
        // let theTemplate = await pluginFolder.getEntry("/image1.png");
        //directory where all image's request folders are. one folder for each request
        const relative_dir_path = `./server/python_server/`

        const image_path = `${relative_dir_path}/${gCurrentImagePath}`
        // 'C:/Users/abdul/Desktop/photoshop_plugins/my_plugin_1/server/python_server/output- 1670544300.95411.png'
        let theTemplate = await pluginFolder.getEntry(image_path)

        await app.open(theTemplate)
    } catch (e) {
        console.warn("couldn't open image ", e)
    }
}
//REFACTOR: move to psapi.js
async function openImageExe() {
    await require('photoshop').core.executeAsModal(openImageAction)
}
// document.getElementById('btnImagesToLayers').addEventListener('click',openImageExe)

// convert a layer to a smart object
async function convertToSmartObjectAction() {
    const batchPlay = require('photoshop').action.batchPlay
    const result = await batchPlay(
        [
            {
                _obj: 'newPlacedLayer',
                _isCommand: true,
                _options: {
                    dialogOptions: 'dontDisplay',
                },
            },
        ],
        {}
    )
}
//REFACTOR: move to psapi.js
async function convertToSmartObjectExe() {
    await require('photoshop').core.executeAsModal(convertToSmartObjectAction)
}

async function ImagesToLayersExe(images_paths) {
    g_generation_session.isLoadingActive = true

    await psapi.reSelectMarqueeExe(g_generation_session.selectionInfo)
    image_path_to_layer = {}
    console.log('ImagesToLayersExe: images_paths: ', images_paths)
    for (image_path of images_paths) {
        gCurrentImagePath = image_path
        console.log(gCurrentImagePath)
        await openImageExe() //local image to new document
        await convertToSmartObjectExe() //convert the current image to smart object
        if (g_b_use_smart_object === false) {
            await executeAsModal(async () => {
                await app.activeDocument.activeLayers[0].rasterize() //rastrize the active layer
            })
        }
        await stackLayers() // move the smart object to the original/old document
        await psapi.layerToSelection(g_generation_session.selectionInfo) //transform the new smart object layer to fit selection area
        layer = await app.activeDocument.activeLayers[0]
        image_path_to_layer[image_path] = layer
        // await reselect(selectionInfo)
    }
    return image_path_to_layer
}
//REFACTOR: unused, remove?
async function silentImagesToLayersExe_old(images_info) {
    try {
        g_generation_session.isLoadingActive = true

        await psapi.reSelectMarqueeExe(g_generation_session.selectionInfo)
        image_path_to_layer = {}
        console.log(
            'silentImagesToLayersExe: images_info.images_paths: ',
            images_info.images_paths
        )
        // Returns a Promise that resolves after "ms" Milliseconds
        const timer = (ms) => new Promise((res) => setTimeout(res, ms))

        for (image_info of images_info) {
            console.log(gCurrentImagePath)
            //unselect all layers so that the imported layer get place at the top of the document
            await psapi.unselectActiveLayersExe()

            let placeEventResult
            // if (base64_images) {
            //     placeEventResult = await base64ToFile(base64_images) //silent import into the document
            // } else {
            //     placeEventResult = await placeEmbedded(image_path) //silent import into the document
            // }
            placeEventResult = await base64ToFile(image_info.base64) //silent import into the document

            let layer = await app.activeDocument.layers.filter(
                (l) => l.id === placeEventResult?.ID
            )[0]
            // await openImageExe() //local image to new document
            // await convertToSmartObjectExe() //convert the current image to smart object
            let timer_count = 0

            // let layer = await app.activeDocument.activeLayers[0]
            console.log('loaded layer: ', layer)
            console.log('placeEventResult?.ID: ', placeEventResult?.ID)

            while (!layer && timer_count <= 10000) {
                await timer(100) // then the created Promise can be awaited
                timer_count += 100
                // layer = await app.activeDocument.activeLayers[0]
                layer = await app.activeDocument.layers.filter(
                    (l) => l.id === placeEventResult?.ID
                )[0]
                const active_layer = await app.activeDocument.activeLayers[0]
                console.log('active_layer.id: ', active_layer.id)
                if (active_layer.id === placeEventResult?.ID) {
                    layer = active_layer
                }

                console.log('timer_count: ', timer_count)
                console.log('loaded layer: ', layer)
                console.log('placeEventResult?.ID: ', placeEventResult?.ID)
            }

            if (g_b_use_smart_object === false) {
                await executeAsModal(async () => {
                    await layer.rasterize() //rastrize the active layer
                })
            }

            await psapi.selectLayersExe([layer])
            await psapi.layerToSelection(g_generation_session.selectionInfo)

            // await stackLayers() // move the smart object to the original/old document
            // await psapi.layerToSelection(g_generation_session.selectionInfo) //transform the new smart object layer to fit selection area
            // layer = await app.activeDocument.activeLayers[0]
            await g_generation_session.moveToTopOfOutputGroup(layer)
            // const output_group_id = await g_generation_session.outputGroup.id
            // let group_index = await psapi.getLayerIndex(output_group_id)
            // const indexOffset = 1 //1 for background, 0 if no background exist
            // await executeAsModal(async ()=>{
            //   await psapi.moveToGroupCommand(group_index - indexOffset, layer.id)

            // })

            image_path_to_layer[image_info.path] = layer
            // await reselect(selectionInfo)
        }
        return image_path_to_layer
    } catch (e) {
        console.warn(e)
    }
    g_generation_session.isLoadingActive = false
}
//REFACTOR: move to psapi.js
async function silentImagesToLayersExe(images_info) {
    //use active layer instead of placeEventResult
    try {
        g_generation_session.isLoadingActive = true

        await psapi.reSelectMarqueeExe(g_generation_session.selectionInfo) //why do we reselect the session selection area
        image_path_to_layer = {}
        console.log(
            'silentImagesToLayersExe: images_info.images_paths: ',
            images_info.images_paths
        )
        // Returns a Promise that resolves after "ms" Milliseconds
        // const timer = (ms) => new Promise((res) => setTimeout(res, ms)) //Todo: move this line to it's own utilit function

        for (image_info of images_info) {
            console.log(gCurrentImagePath)
            //unselect all layers so that the imported layer get place at the top of the document
            await psapi.unselectActiveLayersExe()

            let imported_layer
            // if (base64_images) {
            //     placeEventResult = await base64ToFile(base64_images) //silent import into the document
            // } else {
            //     placeEventResult = await placeEmbedded(image_path) //silent import into the document
            // }
            // imported_layer = await base64ToFile(image_info.base64) //silent import into the document
            const selection_info = await g_generation_session.selectionInfo

            imported_layer = await io.IO.base64ToLayer(
                image_info.base64,
                'output_image.png',
                selection_info.left,
                selection_info.top,
                selection_info.width,
                selection_info.height
            )
            if (!layer_util.Layer.doesLayerExist(imported_layer)) {
                continue //skip if the import vailed
            }
            // let layer = await app.activeDocument.layers.filter(
            //     (l) => l.id === placeEventResult?.ID
            // )[0]

            let timer_count = 0

            // let layer = await app.activeDocument.activeLayers[0]
            console.log('imported_layer: ', imported_layer)

            // while (timer_count <= 10000) {
            //     await timer(100) // then the created Promise can be awaited
            //     timer_count += 100
            //     // layer = await app.activeDocument.activeLayers[0]

            //     console.log('timer_count: ', timer_count)
            //     console.log('loaded layer: ', imported_layer)
            // }

            if (g_b_use_smart_object === false) {
                await executeAsModal(async () => {
                    await imported_layer.rasterize() //rastrize the active layer
                })
            }

            // await psapi.selectLayersExe([imported_layer])
            // await psapi.layerToSelection(g_generation_session.selectionInfo)// not needed

            await g_generation_session.moveToTopOfOutputGroup(imported_layer)
            await psapi.setVisibleExe(imported_layer, false) // turn off the visibility for the layer
            image_path_to_layer[image_info.path] = imported_layer
            // await reselect(selectionInfo)
        }
        return image_path_to_layer
    } catch (e) {
        console.warn(e)
    }
    g_generation_session.isLoadingActive = false
}

// document.getElementById('btnLoadImages').addEventListener('click',ImagesToLayersExe)

//stack layer to original document
//REFACTOR: move to psapi.js
async function stackLayers() {
    //workingDoc is the project you are using stable diffusion in
    const workingDoc = app.documents[0]
    //you should not open two multiple projects this script assume there is only one project opened
    const docsToStack = app.documents.filter(
        (doc) => doc._id !== workingDoc._id
    )
    let docCounter = 0

    // execute as modal is required for functions that change the state of Photoshop or documents
    // think of it as a function that 'wraps' yours and tells Photoshop to go into a modal state and not allow anything to interrupt it from doing whatever is contained in the executeAsModal
    // we also call it with the await keyword to tell JS that we want to wait for it to complete before moving on to later code (in this case there isn't any though)
    await require('photoshop').core.executeAsModal(async () => {
        // increment counter
        docCounter++

        // loop through other open docs
        for (const doc of docsToStack) {
            // flatten
            // doc.flatten();

            // rename layer with counter
            doc.layers[0].name = `Layer ${docCounter}`

            // increment counter
            docCounter++

            // duplicate layer to docZero
            doc.layers[0].duplicate(workingDoc)

            // close doc
            await doc.closeWithoutSaving()
        }
    })
}
//REFACTOR: move to events.js
document.getElementById('collapsible').addEventListener('click', function () {
    this.classList.toggle('active')
    var content = this.nextElementSibling
    console.log('content:', content)
    if (content.style.display === 'block') {
        content.style.display = 'none'
        this.textContent = 'Show Samplers'
    } else {
        content.style.display = 'block'
        this.textContent = 'Hide Samplers'
    }
})

function removeInitImageFromViewer() {}
function removeMaskFromViewer() {}
//REFACTOR: move to viewer.js
async function viewerThumbnailclickHandler(e, viewer_obj_owner) {
    if (g_isViewerMenuDisabled) {
        return g_isViewerMenuDisabled
    }

    let click_type = Enum.clickTypeEnum['Click']

    if (e.shiftKey) {
        click_type = Enum.clickTypeEnum['ShiftClick']
    } else if (e.altKey) {
        click_type = Enum.clickTypeEnum['AltClick']
    }

    if (
        viewer_obj_owner.isActive() &&
        click_type === Enum.clickTypeEnum['Click']
    ) {
        //convert consecutive clicks to AltClick
        click_type = Enum.clickTypeEnum['SecondClick']
        console.log('converted click_type: ', click_type)
    }

    await executeAsModal(async () => {
        //get type of click

        await viewer_obj_owner.click(click_type)
    })
}
// async function NewViewerImageClickHandler(img, viewer_obj_owner) {
//     try {

//     } catch (e) {
//         console.warn(e)
//     }
// }
//REFACTOR: move to viewer.js
function createViewerImgHtml(output_dir_relative, image_path, base64_image) {
    const img = document.createElement('img')
    // img.src = `${output_dir_relative}/${image_path}`
    img.src = base64ToSrc(base64_image)
    img.className = 'viewer-image'
    console.log('image_path: ', image_path)
    // img.dataset.image_id = layer_id
    // img.dataset.image_path = image_path // image_path is not the same as src
    return img
}

//REFACTOR: move to psapi.js
function toggleLayerVisibility(layer, b_on) {
    try {
        layer.visible = b_on
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to psapi.js
async function turnMaskVisible(
    b_mask_group_on,
    b_white_mask_on,
    b_solid_black_mask_on
) {
    //will turn a mask group, white layer mask, and the solid black layer on and off
    try {
        await executeAsModal(() => {
            toggleLayerVisibility(g_mask_group, b_mask_group_on)
            toggleLayerVisibility(g_white_mask, b_white_mask_on)
            toggleLayerVisibility(g_solid_black_mask, b_solid_black_mask_on)
        })
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to viewer.js
async function loadInitImageViewerObject(
    group,
    snapshot,
    solid_background,
    path,
    auto_delete,
    base64_image
) {
    const initImage = g_viewer_manager.addInitImage(
        group,
        snapshot,
        solid_background,
        path,
        auto_delete
    )

    const init_img_html = createViewerImgHtml(
        './server/python_server/init_images/',
        path,
        base64_image
    )
    initImage.createThumbnailNew(init_img_html)
    g_viewer_manager.init_image_container.appendChild(
        initImage.thumbnail_container
    )
    initImage.setImgHtml(init_img_html)

    init_img_html.addEventListener('click', async (e) => {
        await viewerThumbnailclickHandler(e, initImage)
    })
}
//REFACTOR: move to viewer.js
async function loadViewerImages() {
    try {
        //get the images path
        console.log(
            'g_generation_session.image_paths_to_layers:',
            g_generation_session.image_paths_to_layers
        )

        const output_dir_relative = './server/python_server/'
        // const init_image_container = document.getElementById(
        //     'divInitImageViewerContainer'
        // )
        const mask_container = document.getElementById(
            'divInitMaskViewerContainer'
        )
        const output_image_container = document.getElementById(
            'divViewerImagesContainer'
        )

        // while(container.firstChild){
        // container.removeChild(container.firstChild);
        // }
        image_paths = Object.keys(g_generation_session.image_paths_to_layers)
        console.log('image_paths: ', image_paths)
        let i = 0

        // const viewer_layers = []

        // if(g_viewer_manager.g_init_image_related_layers.hasOwnProperty('init_image_group') )
        if (g_viewer_manager.initGroup) {
            //it means we are in an img2img related mode

            const paths = Object.keys(g_viewer_manager.initImageLayersJson)
            for (const path of paths) {
                if (!g_viewer_manager.hasViewerImage(path)) {
                    // const group =
                    //     g_viewer_manager.initImageLayersJson[path].group
                    // const snapshot =
                    //     g_viewer_manager.initImageLayersJson[path].snapshot
                    // const solid_background =
                    //     g_viewer_manager.initImageLayersJson[path]
                    //         .solid_background
                    // const auto_delete =
                    //     g_viewer_manager.initImageLayersJson[path].autoDelete
                    // const base64_image =
                    //     g_generation_session.base64initImages[path]
                    // await loadInitImageViewerObject(
                    //     group,
                    //     snapshot,
                    //     solid_background,
                    //     path,
                    //     auto_delete,
                    //     base64_image
                    // )
                    await g_viewer_manager.loadInitImageViewerObject(path)

                    // await NewViewerImageClickHandler(init_img_html, initImage) // create click handler for each images
                }
            }
        }

        // if (g_mask_related_layers.hasOwnProperty('mask_group')) {
        if (g_viewer_manager.maskGroup) {
            const path = `./server/python_server/init_images/${g_init_image_mask_name}`
            if (!g_viewer_manager.hasViewerImage(path)) {
                // const group = g_mask_related_layers['mask_group']
                // const white_mark = g_mask_related_layers['white_mark']
                // const solid_background = g_mask_related_layers['solid_black']

                const group = g_viewer_manager.maskLayersJson[path].group
                const white_mark =
                    g_viewer_manager.maskLayersJson[path].white_mark
                const solid_background =
                    g_viewer_manager.maskLayersJson[path].solid_background
                const mask_obj = g_viewer_manager.addMask(
                    group,
                    white_mark,
                    solid_background,
                    path
                )

                const mask_img_html = createViewerImgHtml(
                    './server/python_server/init_images/',
                    g_init_image_mask_name,
                    g_generation_session.base64maskImage[path]
                )

                mask_obj.createThumbnailNew(mask_img_html)
                mask_container.appendChild(mask_obj.thumbnail_container)
                mask_obj.setImgHtml(mask_img_html)

                // await NewViewerImageClickHandler(mask_img_html, mask_obj) // create click handler for each images ,viewer_layers)// create click handler for each images

                mask_img_html.addEventListener('click', async (e) => {
                    await viewerThumbnailclickHandler(e, mask_obj)
                })

                // await viewerImageClickHandler(mask_img_html,viewer_layers)// create click handler for each images
            }
        }

        console.log('image_paths: ', image_paths)
        let lastOutputImage
        for (const path of image_paths) {
            // const path = image_path
            //check if viewer obj already exist by using the path on hard drive
            if (!g_viewer_manager.hasViewerImage(path)) {
                //create viewer object if it doesn't exist

                //create an html image element and attach it container, and link it to the viewer obj

                const layer = g_generation_session.image_paths_to_layers[path]
                const img = createViewerImgHtml(
                    output_dir_relative,
                    path,
                    g_generation_session.base64OutputImages[path]
                )
                const output_image_obj = g_viewer_manager.addOutputImage(
                    layer,
                    path
                )
                lastOutputImage = output_image_obj
                const b_button_visible =
                    g_generation_session.mode !== generationMode['Txt2Img']
                        ? true
                        : false

                output_image_obj.createThumbnailNew(img, b_button_visible)
                // output_image_obj.setImgHtml(img)
                // if (g_generation_session.mode !== generationMode['Txt2Img']) {
                //     //we don't need a button in txt2img mode
                //     // output_image_obj.addButtonHtml()
                // }
                output_image_container.appendChild(
                    output_image_obj.thumbnail_container
                )
                //add on click event handler to the html img
                // await NewViewerImageClickHandler(img, output_image_obj)
                img.addEventListener('click', async (e) => {
                    await viewerThumbnailclickHandler(e, output_image_obj)
                })
            }

            // i++
        }

        const thumbnail_size_slider = document.getElementById('slThumbnailSize')
        scaleThumbnailsEvenHandler(
            thumbnail_size_slider.value,
            thumbnail_size_slider.max,
            thumbnail_size_slider.min
        )
        if (lastOutputImage) {
            //select the last generate/output image
            // lastOutputImage.img_html.click()
            await executeAsModal(async () => {
                await lastOutputImage.click(Enum.clickTypeEnum['Click'])
            })
        }
    } catch (e) {
        console.error(`loadViewer images: `, e)
    }
}
//REFACTOR: move to session.js
async function deleteNoneSelected(viewer_objects) {
    try {
        // visible layer
        //delete all hidden layers

        await executeAsModal(async () => {
            for (const [path, viewer_object] of Object.entries(
                viewer_objects
            )) {
                try {
                    // if (viewer_object.getHighlight() || viewer_object.is_active){//keep it if it's highlighted
                    // const path = viewer_object.path

                    viewer_object.visible(true) //make them visiable on the canvas

                    await viewer_object.delete() //delete the layer from layers stack

                    //   if(viewer_object.state ===  viewer.ViewerObjState['Unlink']){
                    //   viewer_object.unlink() // just delete the html image but keep the layer in the layers stack
                    //   viewer_object.visible(true)//make them visiable on the canvas
                    // }else if(viewer_object.state === viewer.ViewerObjState['Delete']){// delete it if it isn't  highlighted
                    //   await viewer_object.delete()//delete the layer from layers stack

                    // }
                    delete g_generation_session.image_paths_to_layers[path]
                } catch (e) {
                    console.warn(e)
                }
            }

            //Refactor: move to viewerManager.onSessionEnd()
            g_viewer_manager.pathToViewerImage = {}
            g_viewer_manager.initImageLayersJson = {}
            g_viewer_manager.outputImages = []
            //

            g_generation_session.image_paths_to_layers = {}
        })
    } catch (e) {
        console.warn(e)
    }
}

// document.getElementById('btnLoadViewer').addEventListener('click', loadViewerImages)

//REFACTOR: move to document.js
async function moveHistoryImageToLayer(img) {
    let image_path = img.dataset.path
    const image_path_escape = image_path.replace(/\o/g, '/o') //escape string "\o" in "\output"

    // load the image from "data:image/png;base64," base64_str
    const base64_image = img.src.replace('data:image/png;base64,', '')
    // await base64ToFile(base64_image)
    const metadata_json = JSON.parse(img.dataset.metadata_json_string)
    const to_x = metadata_json['selection_info']?.left
    const to_y = metadata_json['selection_info']?.top
    const width = metadata_json['selection_info']?.width
    const height = metadata_json['selection_info']?.height
    await io.IO.base64ToLayer(
        base64_image,
        'History Image',
        to_x,
        to_y,
        width,
        height
    )
}

//REFACTOR: move to document.js
async function loadPromptShortcut() {
    try {
        let prompt_shortcut = await sdapi.loadPromptShortcut()
        if (!prompt_shortcut || prompt_shortcut === {}) {
            prompt_shortcut = promptShortcutExample()
        }

        // var JSONInPrettyFormat = JSON.stringify(prompt_shortcut, undefined, 4);
        // document.getElementById('taPromptShortcut').value = JSONInPrettyFormat
        html_manip.setPromptShortcut(prompt_shortcut) // fill the prompt shortcut textarea
        await refreshPromptMenue() //refresh the prompt menue
    } catch (e) {
        console.warn(`loadPromptShortcut warning: ${e}`)
    }
}
//REFACTOR: move to events.js
document
    .getElementById('btnLoadPromptShortcut')
    .addEventListener('click', async function () {
        await loadPromptShortcut()
    })
//REFACTOR: move to events.js
document
    .getElementById('btnUpdatePromptShortcut')
    .addEventListener('click', async function () {
        try {
            // prompt_shortcut = await sdapi.loadPromptShortcut()
            const prompt_shortcut_string =
                document.getElementById('taPromptShortcut').value
            const prompt_shortcut = JSON.parse(prompt_shortcut_string)
            var newKey = document.getElementById('KeyPromptShortcut').value
            var newValue = document.getElementById('ValuePromptShortcut').value
            console.log(newKey)
            console.log(newValue)
            prompt_shortcut[newKey] = newValue
            var JSONInPrettyFormat = JSON.stringify(
                prompt_shortcut,
                undefined,
                4
            )
            console.log(JSONInPrettyFormat)
            document.getElementById('taPromptShortcut').value =
                JSONInPrettyFormat
            await refreshPromptMenue()
        } catch (e) {
            console.warn(`loadPromptShortcut warning: ${e}`)
        }
    })
//REFACTOR: move to events.js
document
    .getElementById('btnSavePromptShortcut')
    .addEventListener('click', async function () {
        try {
            const r1 = await dialog_box.prompt(
                'Are you sure you want to save prompt shortcut?',
                "This will override your old prompt shortcut file, you can't undo this operation",
                ['Cancel', 'Save']
            )
            if ((r1 || 'Save') !== 'Save') {
                /* cancelled or No */
                console.log('cancel')
            } else {
                /* Yes */
                console.log('Save')

                prompt_shortcut_string =
                    document.getElementById('taPromptShortcut').value
                let prompt_shortcut = JSON.parse(prompt_shortcut_string)

                prompt_shortcut = await sdapi.savePromptShortcut(
                    prompt_shortcut
                )
                // var JSONInPrettyFormat = JSON.stringify(prompt_shortcut, undefined, 4);
                console.log('prompt_shortcut was saved: ', prompt_shortcut)
            }
        } catch (e) {
            console.warn(`savePromptShortcut warning: ${e}`)
        }
    })

// Hi res fix stuff

// var hr_models = [
//     'Latent',
//     'Latent (antialiased)',
//     'Latent (bicubic)',
//     'Latent (bicubic antialiased)',
//     'Latent (nearest)',
//     'Latent (nearest-exact)',
//     'None',
//     'Lanczos',
//     'Nearest',
//     'ESRGAN_4x',
//     'R-ESRGAN 4x+',
//     'R-ESRGAN 4x+ Anime6B',
//     'LDSR',
//     'SwinIR 4x',
// ]

var chHiResFixs = document.getElementById('chHiResFixs')
var div = document.getElementById('HiResDiv')
//REFACTOR: move to events.js
chHiResFixs.addEventListener('change', function () {
    if (chHiResFixs.checked) {
        div.style.display = 'block'
    } else {
        div.style.display = 'none'
    }
})
//REFACTOR: move to ui.js
async function refreshPromptMenue() {
    try {
        //get the prompt_shortcut_json
        //iterate over the each entery
        const prompt_shortcut = html_manip.getPromptShortcut()
        const prompt_shortcut_menu = document.getElementById(
            'mPromptShortcutMenu'
        )
        prompt_shortcut_menu.innerHTML = ''

        for (const [key, value] of Object.entries(prompt_shortcut)) {
            if (value.trim() === '') {
                //skip empty spaces
                continue
            }
            const menu_item_element = document.createElement('sp-menu-item')

            menu_item_element.innerHTML = key
            prompt_shortcut_menu.appendChild(menu_item_element)
        }
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
document
    .getElementById('mPromptShortcutMenu')
    .addEventListener('change', (evt) => {
        const prompt_shortcut = html_manip.getPromptShortcut()
        const key = evt.target.value
        console.log('key:', key)
        changePromptShortcutKey(key)
        changePromptShortcutValue(prompt_shortcut[key])
    })
//REFACTOR: move to events.js
document
    .getElementById('btnRefreshPromptShortcutMenu')
    .addEventListener('click', async () => {
        await refreshPromptMenue()
    })
//REFACTOR: move to ui.js
function changePromptShortcutKey(new_key) {
    document.getElementById('KeyPromptShortcut').value = new_key
}
//REFACTOR: move to ui.js
function changePromptShortcutValue(new_value) {
    document.getElementById('ValuePromptShortcut').value = new_value
}

// adding a listner here for the inpaint_mask_strengh to be able to use api calls, allowing to dynamicly change the value
// a set button could be added to the ui to reduce the number of api calls in case of a slow connection
//REFACTOR: move to events.js
document
    .querySelector('#slInpaintingMaskWeight')
    .addEventListener('input', async (evt) => {
        const label_value = evt.target.value / 100
        document.getElementById(
            'lInpaintingMaskWeight'
        ).innerHTML = `${label_value}`
        // await sdapi.setInpaintMaskWeight(label_value)
    })
//REFACTOR: move to events.js
document
    .querySelector('#slInpaintingMaskWeight')
    .addEventListener('change', async (evt) => {
        try {
            const label_value = evt.target.value / 100
            document.getElementById(
                'lInpaintingMaskWeight'
            ).innerHTML = `${label_value}`
            await sdapi.setInpaintMaskWeight(label_value)

            // //get the inpaint mask weight from the webui sd
            // await g_sd_options_obj.getOptions()
            // const inpainting_mask_weight =
            //     await g_sd_options_obj.getInpaintingMaskWeight()

            // console.log('inpainting_mask_weight: ', inpainting_mask_weight)
            // html_manip.autoFillInInpaintMaskWeight(inpainting_mask_weight)
        } catch (e) {
            console.warn(e)
        }
    })
//REFACTOR: move to document.js
async function downloadIt(link, writeable_entry, image_file_name) {
    const image = await fetch(link)
    console.log(link)
    const storage = require('uxp').storage
    const fs = storage.localFileSystem

    try {
        const img = await image.arrayBuffer()
        // const file = await fs.getFileForSaving("image.png");
        // const folder = await storage.localFileSystem.getTemporaryFolder()
        const file = await writeable_entry.createFile(image_file_name, {
            overwrite: true,
        })
        // const file = await fs.getTempFolder()

        await file.write(img)
        const currentDocument = app.activeDocument
        let newDocument
        let new_layer
        try {
            newDocument = await app.open(file)
            if (currentDocument) {
                new_layer = await newDocument.activeLayers[0].duplicate(
                    currentDocument
                )
                await newDocument.closeWithoutSaving()
            }
        } catch (e) {
            console.warn(e)
        }

        if (!file) {
            return
        }
        return new_layer
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to document.js
async function downloadItExe(link, writeable_entry, image_file_name) {
    let new_layer
    await executeAsModal(async () => {
        try {
            new_layer = await downloadIt(link, writeable_entry, image_file_name)
        } catch (e) {
            console.warn(e)
        }
    })
    return new_layer
}

//REFACTOR: move to session.js or selection.js
async function activateSessionSelectionArea() {
    try {
        if (psapi.isSelectionValid(g_generation_session.selectionInfo)) {
            await psapi.reSelectMarqueeExe(g_generation_session.selectionInfo)
            await eventHandler()
        }
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
document
    .getElementById('btnSelectionArea')
    .addEventListener('click', async () => {
        // try {
        //     if (psapi.isSelectionValid(g_generation_session.selectionInfo)) {
        //         await psapi.reSelectMarqueeExe(
        //             g_generation_session.selectionInfo
        //         )
        //         await eventHandler()
        //     }
        // } catch (e) {
        //     console.warn(e)
        // }
        await activateSessionSelectionArea()
    })

//REFACTOR: move to psapi.js
function base64ToSrc(base64_image) {
    const image_src = `data:image/png;base64, ${base64_image}`
    return image_src
}

const py_re = require('./utility/sdapi/python_replacement')

function getDimensions(image) {
    return new Promise((resolve, reject) => {
        var img = new Image()
        img.src = image

        img.addEventListener('load', function () {
            // image.width × image.height
            console.log('image loaded:', img.width, img.height)
            resolve({ width: img.width, height: img.height })
        })

        // img.onload = () => {

        //     resolve({ width: img.width, height: img.height })
        // }
    })
}
//REFACTOR: move to ui.js
function scaleThumbnailsEvenHandler(scale_index, max_index, min_index) {
    const slider_max = max_index
    const slider_min = min_index
    const scaler_value = general.mapRange(scale_index, 0, slider_max, 0, 2)
    g_viewer_manager.thumbnail_scaler = scaler_value

    try {
        g_viewer_manager.scaleThumbnails(
            0,
            0,
            0,
            0,
            g_viewer_manager.thumbnail_scaler
        )
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to events.js
document.getElementById('slThumbnailSize').addEventListener('input', (evt) => {
    scaleThumbnailsEvenHandler(evt.target.value, evt.target.max, evt.target.min)
})
//REFACTOR: move to events.js
document.getElementById('linkWidthHeight').addEventListener('click', (evt) => {
    evt.target.classList.toggle('blackChain')
    const b_state = !evt.target.classList.contains('blackChain') //if doesn't has blackChain means => it's white => b_state == true
    html_manip.setLinkWidthHeightState(b_state)
})
//REFACTOR: move to events.js
document
    .getElementById('chSquareThumbnail')
    .addEventListener('click', (evt) => {
        if (evt.target.checked) {
            g_viewer_manager.isSquareThumbnail = true
        } else {
            g_viewer_manager.isSquareThumbnail = false
        }
        const thumbnail_size_slider = document.getElementById('slThumbnailSize')
        scaleThumbnailsEvenHandler(
            thumbnail_size_slider.value,
            thumbnail_size_slider.max,
            thumbnail_size_slider.min
        )
    })
//REFACTOR: move to events.js

function switchMenu(rb) {
    const tab_button_name = rb.dataset['tab-name']
    const tab_page_name = `${tab_button_name}-page`

    try {
        const contianer_class = rb.parentElement.dataset['container-class']
        const radio_group = rb.parentElement
        document
            .getElementById(tab_button_name)
            .addEventListener('click', () => {
                document.getElementById(tab_button_name)
                const option_container = document
                    .getElementById(tab_page_name)
                    .querySelector(`.${contianer_class}`)
                // .querySelector('.subTabOptionsContainer')
                // const radio_group = document.getElementById('rgSubTab')
                rb.checked = true
                option_container.appendChild(radio_group)
            })

        rb.onclick = () => {
            document.getElementById(tab_button_name).click()
        }
    } catch (e) {
        console.warn(e)
    }
}

//REFACTOR: move to ui.js
async function updateResDifferenceLabel() {
    const ratio = await selection.Selection.getImageToSelectionDifference()
    const arrow = ratio >= 1 ? '↑' : '↓'
    let final_ratio = ratio // this ratio will always be >= 1
    if (ratio >= 1) {
        // percentage = percentage >= 1 ? percentage : 1 / percentage

        // const percentage_str = `${arrow}X${percentage.toFixed(2)}`

        // console.log('scale_info_str: ', scale_info_str)
        // console.log('percentage_str: ', percentage_str)
        document
            .getElementById('res-difference')
            .classList.remove('res-decrease')
    } else {
        final_ratio = 1 / ratio
        document.getElementById('res-difference').classList.add('res-decrease')
    }
    const ratio_str = `${arrow}x${final_ratio.toFixed(2)}`
    document.getElementById('res-difference').innerText = ratio_str
}
//REFACTOR: move to events.js
document
    .getElementById('btnSaveHordeSettings')
    .addEventListener('click', async () => {
        await horde_native.HordeSettings.saveSettings()
    })
//REFACTOR: move to psapi.js
async function getColor(X, Y) {
    // const background_layer_id = await app.activeDocument.backgroundLayer.id

    const batchPlay = require('photoshop').action.batchPlay
    try {
        const result = await batchPlay(
            [
                {
                    _obj: 'colorSampler',
                    _target: {
                        _ref: 'document',
                        _enum: 'ordinal',
                        _value: 'targetEnum',
                    },
                    samplePoint: {
                        horizontal: X,
                        vertical: Y,
                    },
                },
            ],
            {}
        )

        const red = result[0].colorSampler.red
        const green = result[0].colorSampler.grain
        const blue = result[0].colorSampler.blue

        return [red, green, blue]
    } catch (e) {
        console.warn(e)
    }
}
//REFACTOR: move to document.js
async function findDocumentType() {
    //check if the background layer exsit
    //if it doesn't return false
    //if it does:
    //duplicate the background layer and place it on the top of the document.
    //sampler 10 random pixles
    //and check if all the pixels has the same values.
    //if it doesn't duplicate the background layer and place it above the background layer.
    // make a white background layer.
    //return true

    let document_type
    const background_layer = await app.activeDocument.backgroundLayer
    const artboards = Array.from(await app.activeDocument.artboards)
    if (artboards.length > 0) {
        document_type = Enum.DocumentTypeEnum['ArtBoard']
    } else if (layer_util.Layer.doesLayerExist(background_layer)) {
        //assume it's solid white background if correctHistory > 1 || layers.length > 5
        const b_correct_background = await isCorrectBackground() // check the history for correct operation
        if (b_correct_background) {
            document_type = Enum.DocumentTypeEnum['SolidBackground']
        } else {
            //else

            //background layer does exist
            //check if it's solid color background or an image background
            //sampler 10 random pixels
            let width = app.activeDocument.width
            let height = app.activeDocument.height
            let old_rgb
            let same_color = true

            await executeAsModal(async () => {
                await layer_util.toggleBackgroundLayerExe() // hide all layers except the background layer
                for (let i = 0; i < 10; ++i) {
                    let x = Math.floor(Math.random() * width)
                    let y = Math.floor(Math.random() * height)

                    const rgb = await getColor(x, y)
                    if (old_rgb) {
                        if (
                            Math.round(old_rgb[0]) === Math.round(rgb[0]) &&
                            Math.round(old_rgb[1]) === Math.round(rgb[1]) &&
                            Math.round(old_rgb[2]) === Math.round(rgb[2])
                        ) {
                        } else {
                            same_color = false //it's an image background
                            break
                        }
                    }
                    old_rgb = rgb
                }
                await layer_util.toggleBackgroundLayerExe() // undo the toggle operation
            })

            document_type = same_color
                ? Enum.DocumentTypeEnum['SolidBackground']
                : Enum.DocumentTypeEnum['ImageBackground']
        }
    } else {
        //create the background layer since it doesn't exsit
        document_type = Enum.DocumentTypeEnum['NoBackground']
    }

    return document_type
}
//REFACTOR: move to document.js
async function correctDocumentType(documentType) {
    if (documentType === Enum.DocumentTypeEnum['SolidBackground']) {
        //do nothing
    } else if (documentType === Enum.DocumentTypeEnum['ImageBackground']) {
        //duplicate the layer
        await executeAsModal(async () => {
            const image_layer =
                await app.activeDocument.backgroundLayer.duplicate() //
            image_layer.name = 'Image'
            await app.activeDocument.backgroundLayer.delete()
            await layer_util.createBackgroundLayer(255, 255, 255)
        })
    } else if (documentType === Enum.DocumentTypeEnum['ArtBoard']) {
        //duplicate the layer
        await app.showAlert(
            "the plugin doesn't work with artboards, create normal document with no artboard to use the plugin"
        )
        throw "the plugin doesn't work with artboards, create normal document with no artboard to use the plugin"
    } else if (documentType === Enum.DocumentTypeEnum['NoBackground']) {
        await layer_util.createBackgroundLayer(255, 255, 255)
    }
}

async function isCorrectBackground() {
    const historylist = app.activeDocument.historyStates.filter(
        (h) => h.name === 'Correct Background'
    )
    console.log('historylist:', historylist)
    const is_correct_background = historylist.length > 0 ? true : false
    return is_correct_background
}

document
    .getElementById('btnSaveHordeSettings')
    .addEventListener('click', async () => {
        await horde_native.HordeSettings.saveSettings()
    })

async function getColor(X, Y) {
    // const background_layer_id = await app.activeDocument.backgroundLayer.id

    const batchPlay = require('photoshop').action.batchPlay
    try {
        const result = await batchPlay(
            [
                {
                    _obj: 'colorSampler',
                    _target: {
                        _ref: 'document',
                        _enum: 'ordinal',
                        _value: 'targetEnum',
                    },
                    samplePoint: {
                        horizontal: X,
                        vertical: Y,
                    },
                },
            ],
            {}
        )

        const red = result[0].colorSampler.red
        const green = result[0].colorSampler.grain
        const blue = result[0].colorSampler.blue

        return [red, green, blue]
    } catch (e) {
        console.warn(e)
    }
}

// async function findDocumentType() {
//     //check if the background layer exsit
//     //if it doesn't return false
//     //if it does:
//     //duplicate the background layer and place it on the top of the document.
//     //sampler 10 random pixles
//     //and check if all the pixels has the same values.
//     //if it doesn't duplicate the background layer and place it above the background layer.
//     // make a white background layer.
//     //return true

//     let document_type
//     const background_layer = await app.activeDocument.backgroundLayer
//     const artboards = Array.from(await app.activeDocument.artboards)
//     if (artboards.length > 0) {
//         document_type = Enum.DocumentTypeEnum['ArtBoard']
//     } else if (layer_util.Layer.doesLayerExist(background_layer)) {
//         //assume it's solid white background if correctHistory > 1 || layers.length > 5
//         const b_correct_background = await isCorrectBackground()
//         if (b_correct_background) {
//             document_type = Enum.DocumentTypeEnum['SolidBackground']
//         } else {
//             //else

//             //background layer does exist
//             //check if it's solid color background or an image background
//             //sampler 10 random pixels
//             let width = app.activeDocument.width
//             let height = app.activeDocument.height
//             let old_rgb
//             let same_color = true
//             await executeAsModal(async () => {
//                 for (let i = 0; i < 10; ++i) {
//                     let x = Math.floor(Math.random() * width)
//                     let y = Math.floor(Math.random() * height)

//                     const rgb = await getColor(x, y)
//                     if (old_rgb) {
//                         if (
//                             Math.round(old_rgb[0]) === Math.round(rgb[0]) &&
//                             Math.round(old_rgb[1]) === Math.round(rgb[1]) &&
//                             Math.round(old_rgb[2]) === Math.round(rgb[2])
//                         ) {
//                         } else {
//                             same_color = false //it's an image background
//                             break
//                         }
//                     }
//                     old_rgb = rgb
//                 }
//             })

//             document_type = same_color
//                 ? Enum.DocumentTypeEnum['SolidBackground']
//                 : Enum.DocumentTypeEnum['ImageBackground']
//         }
//     } else {
//         //create the background layer since it doesn't exsit
//         document_type = Enum.DocumentTypeEnum['NoBackground']
//     }

//     return document_type
// }

async function correctDocumentType(documentType) {
    if (documentType === Enum.DocumentTypeEnum['SolidBackground']) {
        //do nothing
    } else if (documentType === Enum.DocumentTypeEnum['ImageBackground']) {
        //duplicate the layer
        await executeAsModal(async () => {
            const image_layer =
                await app.activeDocument.backgroundLayer.duplicate() //
            image_layer.name = 'Image'
            await app.activeDocument.backgroundLayer.delete()
            await layer_util.createBackgroundLayer(255, 255, 255)
        })
    } else if (documentType === Enum.DocumentTypeEnum['ArtBoard']) {
        //duplicate the layer
        await app.showAlert(
            "the plugin doesn't work with artboards, create normal document with no artboard to use the plugin"
        )
        throw "the plugin doesn't work with artboards, create normal document with no artboard to use the plugin"
    } else if (documentType === Enum.DocumentTypeEnum['NoBackground']) {
        await layer_util.createBackgroundLayer(255, 255, 255)
    }
}

async function isCorrectBackground() {
    const historylist = app.activeDocument.historyStates.filter(
        (h) => h.name === 'Correct Background'
    )
    console.log('historylist:', historylist)
    const is_correct_background = historylist.length > 0 ? true : false
    return is_correct_background
}

let g_viewer_sub_menu_list = []

const submenu = {
    viewer: {
        value: 'viewer',
        Label: 'Viewer',
        'data-tab-name': 'sp-viewer-tab',
    },
    prompts_library: {
        value: 'prompts-library',
        Label: 'Prompts Library',
        'data-tab-name': 'sp-prompts-library-tab',
    },
    history: {
        value: 'history',
        Label: 'History',
        'data-tab-name': 'sp-history-tab',
    },
    lexica: {
        value: 'lexica',
        Label: 'Lexica',
        'data-tab-name': 'sp-lexica-tab',
    },
    image_search: {
        value: 'image_search',
        Label: 'Image Search',
        'data-tab-name': 'sp-image_search-tab',
    },
}

{
    /* <li>
                                <input
                                    type="radio"
                                    id="option1"
                                    name="options"
                                    checked
                                    class="sub-menu-tab-class"
                                />
                                <label for="option1">Option 1</label>
                            </li> */
}

const viewer_sub_menu_html = document.getElementById('viewer-sub-menu')
// const li_elm = document.createElement('li')
// const input_option = document.createElement('input')
// const label_option = document.createElement('label')

// li_elm.appendChild(input_option)
// li_elm.appendChild(label_option)
// viewer_sub_menu_html.appendChild(li_elm)

for (const [option_id, option_data] of Object.entries(submenu)) {
    const li = document.createElement('li')

    li.innerHTML = `
    <input
        type="radio"
        id="${option_id}"
        name="options"
        checked
        class="sub-menu-tab-class"
        data-tab-name='${option_data['data-tab-name']}'
        
    />
    <label for="${option_id}">${option_data.Label}</label>
`

    viewer_sub_menu_html.appendChild(li)
}

function switchMenu_new(rb) {
    const tab_button_name = rb.dataset['tab-name']
    const tab_page_name = `${tab_button_name}-page`

    try {
        const contianer_class =
            rb.parentElement.parentElement.parentElement.dataset[
                'container-class'
            ] //input_option.li.ul.div.dataset['container-class']
        const radio_group = rb.parentElement.parentElement.parentElement //radio_group in this case is ul
        document
            .getElementById(tab_button_name)
            .addEventListener('click', () => {
                document.getElementById(tab_button_name)
                const option_container = document
                    .getElementById(tab_page_name)
                    .querySelector(`.${contianer_class}`)
                // .querySelector('.subTabOptionsContainer')
                // const radio_group = document.getElementById('rgSubTab')
                rb.checked = true
                option_container.appendChild(radio_group)
            })

        rb.parentElement.onclick = () => {
            document.getElementById(tab_button_name).click()
        }
    } catch (e) {
        console.warn(e)
    }
}

document.getElementsByClassName('sub-menu-tab-class').forEach((element) => {
    switchMenu_new(element)

    // const li_element = element.parentElement
    // li_element.addEventListener('click', (event) => {
    //     //doesn't get trigger don't know why
    //     console.log('sub menu clicked')
    //     element.checked = true
    // })
    // switchMenu_new(element)
})
Array.from(document.querySelectorAll('.rbSubTab')).forEach((rb) => {
    switchMenu(rb)
})

// class CustomElement extends HTMLElement {
//     constructor() {
//         super()
//         this.attachShadow({ mode: 'open' })
//         this.shadowRoot.innerHTML = '<h1>Hello World!</h1>'
//     }
// }
// customElements.define('custom-element', CustomElement)