tauri-plugin-network-manager 2.1.1

A Tauri plugin to manage network connections using networkmanager and systemd-networkd.
Documentation
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
use std::collections::HashMap;
use std::sync::mpsc;
use tauri::{plugin::PluginApi, AppHandle, Runtime};
use uuid::Uuid;
use zbus::names::InterfaceName;
use zbus::zvariant::Value;

use crate::error::Result;
use crate::models::*;
use crate::nm_helpers::NetworkManagerHelpers;

impl<R: Runtime> VSKNetworkManager<'static, R> {
    fn vpn_type_from_service_type(service_type: &str) -> VpnType {
        match service_type {
            "org.freedesktop.NetworkManager.openvpn" => VpnType::OpenVpn,
            "org.freedesktop.NetworkManager.wireguard" => VpnType::WireGuard,
            "org.freedesktop.NetworkManager.l2tp" => VpnType::L2tp,
            "org.freedesktop.NetworkManager.pptp" => VpnType::Pptp,
            "org.freedesktop.NetworkManager.sstp" => VpnType::Sstp,
            "org.freedesktop.NetworkManager.strongswan" => VpnType::Ikev2,
            "org.freedesktop.NetworkManager.fortisslvpn" => VpnType::Fortisslvpn,
            "org.freedesktop.NetworkManager.openconnect" => VpnType::OpenConnect,
            _ => VpnType::Generic,
        }
    }

    fn service_type_from_vpn_type(vpn_type: &VpnType) -> &'static str {
        match vpn_type {
            VpnType::OpenVpn => "org.freedesktop.NetworkManager.openvpn",
            VpnType::WireGuard => "org.freedesktop.NetworkManager.wireguard",
            VpnType::L2tp => "org.freedesktop.NetworkManager.l2tp",
            VpnType::Pptp => "org.freedesktop.NetworkManager.pptp",
            VpnType::Sstp => "org.freedesktop.NetworkManager.sstp",
            VpnType::Ikev2 => "org.freedesktop.NetworkManager.strongswan",
            VpnType::Fortisslvpn => "org.freedesktop.NetworkManager.fortisslvpn",
            VpnType::OpenConnect => "org.freedesktop.NetworkManager.openconnect",
            VpnType::Generic => "org.freedesktop.NetworkManager.vpnc",
        }
    }

    fn vpn_state_from_active_state(state: u32) -> VpnConnectionState {
        match state {
            1 => VpnConnectionState::Connecting,
            2 => VpnConnectionState::Connected,
            3 => VpnConnectionState::Disconnecting,
            4 => VpnConnectionState::Disconnected,
            _ => VpnConnectionState::Unknown,
        }
    }

    fn extract_string_from_dict(
        dict: &HashMap<String, zbus::zvariant::OwnedValue>,
        key: &str,
    ) -> Option<String> {
        let value = dict.get(key)?.to_owned();
        <zbus::zvariant::Value<'_> as Clone>::clone(&value)
            .downcast::<String>()
    }

    fn extract_bool_from_dict(
        dict: &HashMap<String, zbus::zvariant::OwnedValue>,
        key: &str,
    ) -> Option<bool> {
        let value = dict.get(key)?.to_owned();
        <zbus::zvariant::Value<'_> as Clone>::clone(&value)
            .downcast::<bool>()
    }

    fn string_map_from_section(
        settings: &HashMap<String, zbus::zvariant::OwnedValue>,
        section_name: &str,
    ) -> HashMap<String, String> {
        let mut out = HashMap::new();
        let section = match settings.get(section_name) {
            Some(v) => v.to_owned(),
            None => return out,
        };
        let dict = match <zbus::zvariant::Value<'_> as Clone>::clone(&section)
            .downcast::<HashMap<String, zbus::zvariant::OwnedValue>>()
        {
            Some(d) => d,
            None => return out,
        };

        for (k, v) in dict {
            let value = <zbus::zvariant::Value<'_> as Clone>::clone(&v);
            if let Some(s) = value.downcast::<String>() {
                out.insert(k, s);
            }
        }
        out
    }

    fn list_connection_paths(&self) -> Result<Vec<zbus::zvariant::OwnedObjectPath>> {
        let settings_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager/Settings",
            "org.freedesktop.NetworkManager.Settings",
        )?;

        let connections: Vec<zbus::zvariant::OwnedObjectPath> =
            settings_proxy.call("ListConnections", &())?;
        Ok(connections)
    }

    fn get_connection_settings(
        &self,
        conn_path: &zbus::zvariant::OwnedObjectPath,
    ) -> Result<HashMap<String, zbus::zvariant::OwnedValue>> {
        let conn_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            conn_path.as_str(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )?;

        let settings: HashMap<String, zbus::zvariant::OwnedValue> =
            conn_proxy.call("GetSettings", &())?;
        Ok(settings)
    }

    fn find_connection_path_by_uuid(
        &self,
        uuid: &str,
    ) -> Result<zbus::zvariant::OwnedObjectPath> {
        let connections = self.list_connection_paths()?;

        for conn_path in connections {
            let settings = self.get_connection_settings(&conn_path)?;
            let connection_section = match settings.get("connection") {
                Some(v) => v.to_owned(),
                None => continue,
            };
            let dict = match <zbus::zvariant::Value<'_> as Clone>::clone(&connection_section)
                .downcast::<HashMap<String, zbus::zvariant::OwnedValue>>()
            {
                Some(d) => d,
                None => continue,
            };

            if let Some(conn_uuid) = Self::extract_string_from_dict(&dict, "uuid") {
                if conn_uuid == uuid {
                    return Ok(conn_path);
                }
            }
        }

        Err(crate::error::NetworkError::VpnProfileNotFound(uuid.to_string()))
    }

    fn vpn_profile_from_settings(
        &self,
        settings: &HashMap<String, zbus::zvariant::OwnedValue>,
    ) -> Option<VpnProfile> {
        let connection_section = settings.get("connection")?.to_owned();
        let connection_dict = <zbus::zvariant::Value<'_> as Clone>::clone(&connection_section)
            .downcast::<HashMap<String, zbus::zvariant::OwnedValue>>()?;

        let conn_type = Self::extract_string_from_dict(&connection_dict, "type")?;
        if conn_type != "vpn" {
            return None;
        }

        let uuid = Self::extract_string_from_dict(&connection_dict, "uuid")?;
        let id = Self::extract_string_from_dict(&connection_dict, "id")
            .unwrap_or_else(|| uuid.clone());
        let interface_name = Self::extract_string_from_dict(&connection_dict, "interface-name");
        let autoconnect = Self::extract_bool_from_dict(&connection_dict, "autoconnect")
            .unwrap_or(false);

        let vpn_settings = Self::string_map_from_section(settings, "vpn");
        let service_type = vpn_settings
            .get("service-type")
            .map(|s| s.as_str())
            .unwrap_or("unknown");

        Some(VpnProfile {
            id,
            uuid,
            vpn_type: Self::vpn_type_from_service_type(service_type),
            interface_name,
            autoconnect,
            editable: true,
            last_error: None,
        })
    }

    /// Get WiFi icon based on signal strength
    fn get_wifi_icon(strength: u8) -> String {
        match strength {
            0..=25 => "network-wireless-signal-weak-symbolic".to_string(),
            26..=50 => "network-wireless-signal-ok-symbolic".to_string(),
            51..=75 => "network-wireless-signal-good-symbolic".to_string(),
            76..=100 => "network-wireless-signal-excellent-symbolic".to_string(),
            _ => "network-wireless-signal-none-symbolic".to_string(),
        }
    }

    fn get_wired_icon(is_connected: bool) -> String {
        if is_connected {
            "network-wired-symbolic".to_string()
        } else {
            "network-offline-symbolic".to_string()
        }
    }

    /// Create a new VSKNetworkManager instance
    pub async fn new(app: AppHandle<R>) -> Result<Self> {
        let connection = zbus::blocking::Connection::system()?;
        let proxy = zbus::blocking::fdo::PropertiesProxy::builder(&connection)
            .destination("org.freedesktop.NetworkManager")?
            .path("/org/freedesktop/NetworkManager")?
            .build()?;

        Ok(Self {
            connection,
            proxy,
            app,
        })
    }

    pub fn get_current_network_state(&self) -> Result<NetworkInfo> {
        // Get active connections
        let active_connections_variant = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "ActiveConnections",
        )?;

        // If no active connections, return default
        match active_connections_variant.downcast_ref() {
            Some(Value::Array(arr)) if !arr.is_empty() => {
                // Get the first active connection path
                match arr[0] {
                    zbus::zvariant::Value::ObjectPath(ref path) => {
                        // Get devices for this connection
                        // Crear un proxy de propiedades para obtener las propiedades
                        let properties_proxy =
                            zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                                .destination("org.freedesktop.NetworkManager")?
                                .path(path)?
                                .build()?;

                        let devices_variant = properties_proxy.get(
                            InterfaceName::from_static_str_unchecked(
                                "org.freedesktop.NetworkManager.Connection.Active",
                            ),
                            "Devices",
                        )?;

                        // Get the first device (if available)
                        let device_path = match devices_variant.downcast_ref() {
                            Some(Value::Array(device_arr)) if !device_arr.is_empty() => {
                                match device_arr[0] {
                                    zbus::zvariant::Value::ObjectPath(ref dev_path) => {
                                        dev_path.clone()
                                    }
                                    _ => return Ok(NetworkInfo::default()),
                                }
                            }
                            _ => return Ok(NetworkInfo::default()),
                        };

                        // Retrieve connection details
                        // Crear un proxy de propiedades para el dispositivo
                        let device_properties_proxy =
                            zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                                .destination("org.freedesktop.NetworkManager")?
                                .path(&device_path)?
                                .build()?;

                        let connection_type = device_properties_proxy.get(
                            InterfaceName::from_static_str_unchecked(
                                "org.freedesktop.NetworkManager.Device",
                            ),
                            "DeviceType",
                        )?;

                        let state_variant = properties_proxy.get(
                            InterfaceName::from_static_str_unchecked(
                                "org.freedesktop.NetworkManager.Connection.Active",
                            ),
                            "State",
                        )?;

                        let is_connected = match state_variant.downcast_ref() {
                            Some(zbus::zvariant::Value::U32(state)) => *state == 2, // 2 = ACTIVATED
                            _ => false,
                        };

                        // Determine connection type
                        let connection_type_str = match connection_type.downcast_ref() {
                            Some(zbus::zvariant::Value::U32(device_type)) => match device_type {
                                1 => "Ethernet".to_string(),
                                2 => "WiFi".to_string(),
                                _ => "Unknown".to_string(),
                            },
                            _ => "Unknown".to_string(),
                        };

                        // Default network info
                        let mut network_info = NetworkInfo {
                            name: "Unknown".to_string(),
                            ssid: "Unknown".to_string(),
                            connection_type: connection_type_str.clone(),
                            icon: "network-offline-symbolic".to_string(),
                            ip_address: "0.0.0.0".to_string(),
                            mac_address: "00:00:00:00:00:00".to_string(),
                            signal_strength: 0,
                            security_type: WiFiSecurityType::None,
                            is_connected: is_connected && NetworkManagerHelpers::has_internet_connectivity(&self.proxy)?,
                        };

                        let hw_address_variant = device_properties_proxy.get(
                            InterfaceName::from_static_str_unchecked(
                                "org.freedesktop.NetworkManager.Device",
                            ),
                            "HwAddress",
                        )?;

                        network_info.mac_address = match hw_address_variant.downcast_ref() {
                            Some(zbus::zvariant::Value::Str(s)) => s.to_string(),
                            _ => "00:00:00:00:00:00".to_string(),
                        };

                        // For WiFi networks, get additional details
                        if connection_type_str == "WiFi" {
                            // Get active access point
                            // Crear un proxy de propiedades para el dispositivo inalámbrico
                            let wireless_properties_proxy =
                                zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                                    .destination("org.freedesktop.NetworkManager")?
                                    .path(&device_path)?
                                    .build()?;

                            let active_ap_path = wireless_properties_proxy.get(
                                InterfaceName::from_static_str_unchecked(
                                    "org.freedesktop.NetworkManager.Device.Wireless",
                                ),
                                "ActiveAccessPoint",
                            )?;

                            if let Some(zbus::zvariant::Value::ObjectPath(ap_path)) =
                                active_ap_path.downcast_ref()
                            {
                                let _ap_proxy = zbus::blocking::Proxy::new(
                                    &self.connection,
                                    "org.freedesktop.NetworkManager",
                                    ap_path,
                                    "org.freedesktop.NetworkManager.AccessPoint",
                                )?;

                                // Get SSID
                                // Crear un proxy de propiedades para el punto de acceso
                                let ap_properties_proxy =
                                    zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                                        .destination("org.freedesktop.NetworkManager")?
                                        .path(ap_path)?
                                        .build()?;

                                let ssid_variant = ap_properties_proxy.get(
                                    InterfaceName::from_static_str_unchecked(
                                        "org.freedesktop.NetworkManager.AccessPoint",
                                    ),
                                    "Ssid",
                                )?;

                                network_info.ssid = match ssid_variant.downcast_ref() {
                                    Some(zbus::zvariant::Value::Array(ssid_bytes)) => {
                                        // Convertir el array de bytes a una cadena UTF-8
                                        let bytes: Vec<u8> = ssid_bytes
                                            .iter()
                                            .filter_map(|v| {
                                                if let zbus::zvariant::Value::U8(b) = v {
                                                    Some(*b)
                                                } else {
                                                    None
                                                }
                                            })
                                            .collect();

                                        String::from_utf8_lossy(&bytes).to_string()
                                    }
                                    _ => "Unknown".to_string(),
                                };
                                network_info.name = network_info.ssid.clone();

                                // Get signal strength
                                let strength_variant = ap_properties_proxy.get(
                                    InterfaceName::from_static_str_unchecked(
                                        "org.freedesktop.NetworkManager.AccessPoint",
                                    ),
                                    "Strength",
                                )?;

                                network_info.signal_strength = match strength_variant.downcast_ref()
                                {
                                    Some(zbus::zvariant::Value::U8(s)) => *s,
                                    _ => 0,
                                };

                                // Update icon based on signal strength
                                network_info.icon =
                                    Self::get_wifi_icon(network_info.signal_strength);

                                // Determine security type using helper
                                network_info.security_type = NetworkManagerHelpers::detect_security_type(&ap_properties_proxy)?;
                            }
                        } else {
                            // This is a wired connection
                            network_info.icon = Self::get_wired_icon(network_info.is_connected);
                        }
                        // Get IP configuration
                        let ip4_config_path = device_properties_proxy.get(
                            InterfaceName::from_static_str_unchecked(
                                "org.freedesktop.NetworkManager.Device",
                            ),
                            "Ip4Config",
                        )?;

                        // Retrieve IP address if available
                        if let Some(zbus::zvariant::Value::ObjectPath(config_path)) =
                            ip4_config_path.downcast_ref()
                        {
                            // Crear un proxy de propiedades para la configuración IP
                            let ip_config_properties_proxy =
                                zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                                    .destination("org.freedesktop.NetworkManager")?
                                    .path(config_path)?
                                    .build()?;

                            let addresses_variant = ip_config_properties_proxy.get(
                                InterfaceName::from_static_str_unchecked(
                                    "org.freedesktop.NetworkManager.IP4Config",
                                ),
                                "Addresses",
                            )?;

                            if let Some(Value::Array(addr_arr)) = addresses_variant.downcast_ref() {
                                if let Some(Value::Array(ip_tuple)) = addr_arr.first() {
                                    if ip_tuple.len() >= 1 {
                                        if let Value::U32(ip_int) = &ip_tuple[0] {
                                            use std::net::Ipv4Addr;
                                            network_info.ip_address =
                                                Ipv4Addr::from((*ip_int).to_be()).to_string();
                                        }
                                    }
                                }
                            }
                        }

                        Ok(network_info)
                    }
                    _ => Ok(NetworkInfo::default()),
                }
            }
            _ => Ok(NetworkInfo::default()),
        }
    }

    /// List available WiFi networks
    pub fn list_wifi_networks(&self) -> Result<Vec<NetworkInfo>> {
        // Get all devices
        let devices_variant = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "Devices",
        )?;

        let mut networks = Vec::new();
        let current_network = self.get_current_network_state()?;

        if let Some(zbus::zvariant::Value::Array(devices)) = devices_variant.downcast_ref() {
            // Iterate over devices in the array
            let device_values = devices.get();
            for device in device_values {
                if let zbus::zvariant::Value::ObjectPath(ref device_path) = device {
                    // Create a device proxy
                    let device_props =
                        zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                            .destination("org.freedesktop.NetworkManager")?
                            .path(device_path)?
                            .build()?;

                    // Check if this is a wireless device
                    let device_type_variant = device_props.get(
                        InterfaceName::from_static_str_unchecked(
                            "org.freedesktop.NetworkManager.Device",
                        ),
                        "DeviceType",
                    )?;

                    // DeviceType 2 is WiFi
                    if let Some(zbus::zvariant::Value::U32(device_type)) =
                        device_type_variant.downcast_ref()
                    {
                        if device_type == &2u32 {
                            let mac_address = match device_props
                                .get(
                                    InterfaceName::from_static_str_unchecked(
                                        "org.freedesktop.NetworkManager.Device",
                                    ),
                                    "HwAddress",
                                )?
                                .downcast_ref()
                            {
                                Some(zbus::zvariant::Value::Str(s)) => s.to_string(),
                                _ => "00:00:00:00:00:00".to_string(),
                            };

                            // This is a WiFi device, get its access points
                            let wireless_props =
                                zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                                    .destination("org.freedesktop.NetworkManager")?
                                    .path(device_path)?
                                    .build()?;

                            let access_points_variant = wireless_props.get(
                                InterfaceName::from_static_str_unchecked(
                                    "org.freedesktop.NetworkManager.Device.Wireless",
                                ),
                                "AccessPoints",
                            )?;

                            if let Some(zbus::zvariant::Value::Array(aps)) =
                                access_points_variant.downcast_ref()
                            {
                                // Iterate over access points
                                let ap_values = aps.get();
                                for ap in ap_values {
                                    if let zbus::zvariant::Value::ObjectPath(ref ap_path) = ap {
                                        let ap_props = zbus::blocking::fdo::PropertiesProxy::builder(
                                            &self.connection,
                                        )
                                        .destination("org.freedesktop.NetworkManager")?
                                        .path(ap_path)?
                                        .build()?;

                                        // Obtener SSID
                                        let ssid_variant = ap_props.get(
                                            InterfaceName::from_static_str_unchecked(
                                                "org.freedesktop.NetworkManager.AccessPoint",
                                            ),
                                            "Ssid",
                                        )?;

                                        let ssid = match ssid_variant.downcast_ref() {
                                            Some(zbus::zvariant::Value::Array(ssid_bytes)) => {
                                                // Convertir el array de bytes a una cadena UTF-8
                                                let bytes: Vec<u8> = ssid_bytes
                                                    .iter()
                                                    .filter_map(|v| {
                                                        if let zbus::zvariant::Value::U8(b) = v {
                                                            Some(*b)
                                                        } else {
                                                            None
                                                        }
                                                    })
                                                    .collect();

                                                String::from_utf8_lossy(&bytes).to_string()
                                            }
                                            _ => "Unknown".to_string(),
                                        };

                                        // Obtener fuerza de señal
                                        let strength_variant = ap_props.get(
                                            InterfaceName::from_static_str_unchecked(
                                                "org.freedesktop.NetworkManager.AccessPoint",
                                            ),
                                            "Strength",
                                        )?;

                                        let strength = match strength_variant.downcast_ref() {
                                            Some(zbus::zvariant::Value::U8(s)) => *s,
                                            _ => 0,
                                        };

                                        // Determine security type using helper
                                        let security_type = NetworkManagerHelpers::detect_security_type(&ap_props)?;

                                        let is_connected = current_network.ssid == ssid;

                                        let network_info = NetworkInfo {
                                            name: ssid.clone(),
                                            ssid,
                                            connection_type: "wifi".to_string(),
                                            icon: Self::get_wifi_icon(strength),
                                            ip_address: if is_connected {
                                                current_network.ip_address.clone()
                                            } else {
                                                "0.0.0.0".to_string()
                                            },
                                            mac_address: mac_address.clone(),
                                            signal_strength: strength,
                                            security_type,
                                            is_connected,
                                        };

                                        if !networks.iter().any(|n: &NetworkInfo| n.ssid == network_info.ssid) {
                                            networks.push(network_info);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Sort networks by signal strength (descending)
        networks.sort_by(|a, b| b.signal_strength.cmp(&a.signal_strength));

        Ok(networks)
    }

    /// Request an explicit WiFi scan through NetworkManager and return a fresh list.
    pub fn rescan_wifi(&self) -> Result<Vec<NetworkInfo>> {
        let devices_variant = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "Devices",
        )?;

        let mut wifi_device_found = false;
        let mut requested_scan = false;

        if let Some(zbus::zvariant::Value::Array(devices)) = devices_variant.downcast_ref() {
            for device in devices.get() {
                if let zbus::zvariant::Value::ObjectPath(ref device_path) = device {
                    let device_props = zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                        .destination("org.freedesktop.NetworkManager")?
                        .path(device_path)?
                        .build()?;

                    let device_type_variant = device_props.get(
                        InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager.Device"),
                        "DeviceType",
                    )?;

                    if let Some(zbus::zvariant::Value::U32(device_type)) = device_type_variant.downcast_ref() {
                        if *device_type == 2 {
                            wifi_device_found = true;

                            let wireless_proxy = zbus::blocking::Proxy::new(
                                &self.connection,
                                "org.freedesktop.NetworkManager",
                                device_path.as_str(),
                                "org.freedesktop.NetworkManager.Device.Wireless",
                            )?;

                            let options: HashMap<String, zbus::zvariant::OwnedValue> = HashMap::new();
                            if wireless_proxy.call::<_, _, ()>("RequestScan", &(options,)).is_ok() {
                                requested_scan = true;
                            }
                        }
                    }
                }
            }
        }

        if !wifi_device_found {
            return Err(crate::error::NetworkError::OperationError(
                "No wireless device available for scanning".to_string(),
            ));
        }

        if !requested_scan {
            return Err(crate::error::NetworkError::OperationError(
                "Failed to request WiFi scan on available wireless devices".to_string(),
            ));
        }

        self.list_wifi_networks()
    }

    /// Connect to a WiFi network
    pub fn connect_to_wifi(&self, config: WiFiConnectionConfig) -> Result<()> {
        // Log connection attempt
        log::debug!("connect_to_wifi called: ssid='{}' security={:?} username={:?}",
                  config.ssid, config.security_type, config.username);

        // Create connection settings
        let mut connection_settings = HashMap::new();
        let mut wifi_settings = HashMap::new();
        let mut security_settings = HashMap::new();

        // Set connection name and type
        let mut connection = HashMap::new();
        connection.insert("id".to_string(), Value::from(config.ssid.clone()));
        connection.insert("type".to_string(), Value::from("802-11-wireless"));
        connection_settings.insert("connection".to_string(), connection);

        // Set WiFi settings
        wifi_settings.insert("ssid".to_string(), Value::from(config.ssid.clone()));
        wifi_settings.insert("mode".to_string(), Value::from("infrastructure"));

        // Set security settings based on security type
        match config.security_type {
            WiFiSecurityType::None => {
                // No security settings needed
            }
            WiFiSecurityType::Wep => {
                security_settings.insert("key-mgmt".to_string(), Value::from("none"));
                if let Some(password) = config.password.clone() {
                    security_settings.insert("wep-key0".to_string(), Value::from(password));
                }
            }
            WiFiSecurityType::WpaPsk => {
                security_settings.insert("key-mgmt".to_string(), Value::from("wpa-psk"));
                if let Some(password) = config.password.clone() {
                    security_settings.insert("psk".to_string(), Value::from(password));
                }
            }
            WiFiSecurityType::WpaEap => {
                security_settings.insert("key-mgmt".to_string(), Value::from("wpa-eap"));
                if let Some(password) = config.password.clone() {
                    security_settings.insert("password".to_string(), Value::from(password));
                }
                if let Some(username) = config.username.clone() {
                    security_settings.insert("identity".to_string(), Value::from(username));
                }
            }
            WiFiSecurityType::Wpa2Psk => {
                security_settings.insert("key-mgmt".to_string(), Value::from("wpa-psk"));
                security_settings.insert("proto".to_string(), Value::from("rsn"));
                if let Some(password) = config.password.clone() {
                    security_settings.insert("psk".to_string(), Value::from(password));
                }
            }
            WiFiSecurityType::Wpa3Psk => {
                security_settings.insert("key-mgmt".to_string(), Value::from("sae"));
                if let Some(password) = config.password.clone() {
                    security_settings.insert("psk".to_string(), Value::from(password));
                }
            }
        }

        connection_settings.insert("802-11-wireless".to_string(), wifi_settings);
        connection_settings.insert("802-11-wireless-security".to_string(), security_settings);

        // Log constructed settings for debugging
        log::trace!("connection_settings: {:#?}", connection_settings);

        // Crear un proxy para NetworkManager
        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;

        // Llamar al método AddAndActivateConnection (trace result)
        let call_result: zbus::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedObjectPath)> = nm_proxy.call("AddAndActivateConnection", &(connection_settings, "/", "/"));

        match call_result {
            Ok((conn_path, active_path)) => {
                log::info!(
                    "AddAndActivateConnection succeeded for ssid='{}' conn='{}' active='{}'",
                    config.ssid,
                    conn_path.as_str(),
                    active_path.as_str()
                );
            }
            Err(e) => {
                log::error!(
                    "AddAndActivateConnection failed for ssid='{}': {:?}",
                    config.ssid,
                    e
                );
                return Err(e.into());
            }
        }

        log::debug!("connect_to_wifi finished for ssid='{}'", config.ssid);

        Ok(())
    }

    /// Toggle network state
    pub fn toggle_network_state(&self, enabled: bool) -> Result<bool> {
        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;

        nm_proxy.set_property("NetworkingEnabled", enabled)?;

        let current_state: bool = nm_proxy.get_property("NetworkingEnabled")?;
        Ok(current_state)
    }

    /// Get wireless enabled state
    pub fn get_wireless_enabled(&self) -> Result<bool> {
        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;
        Ok(nm_proxy.get_property("WirelessEnabled")?)
    }

    /// Set wireless enabled state
    pub fn set_wireless_enabled(&self, enabled: bool) -> Result<()> {
        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;
        nm_proxy.set_property("WirelessEnabled", enabled)?;
        Ok(())
    }

    /// Check if wireless device is available
    pub fn is_wireless_available(&self) -> Result<bool> {
         // Get all devices
        let devices_variant = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "Devices",
        )?;

        if let Some(zbus::zvariant::Value::Array(devices)) = devices_variant.downcast_ref() {
            let device_values = devices.get();
            for device in device_values {
                if let zbus::zvariant::Value::ObjectPath(ref device_path) = device {
                     let device_props = zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                            .destination("org.freedesktop.NetworkManager")?
                            .path(device_path)?
                            .build()?;
                    
                    let device_type_variant = device_props.get(
                        InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager.Device"),
                        "DeviceType",
                    )?;
                    
                    if let Some(zbus::zvariant::Value::U32(device_type)) = device_type_variant.downcast_ref() {
                        if device_type == &2u32 { // 2 = WiFi
                            return Ok(true);
                        }
                    }
                }
            }
        }
        Ok(false)
    }

    /// Listen for network changes
    pub fn listen_network_changes(&self) -> Result<mpsc::Receiver<NetworkInfo>> {
        let (tx, rx) = mpsc::channel();
        let connection_clone = self.connection.clone();
        let app_handle = self.app.clone();

        // Crear un hilo para escuchar los cambios de red
        std::thread::spawn(move || {
            match zbus::blocking::Connection::system() {
                Ok(conn) => {
                    // Proxy para el objeto raíz, interfaz DBus.Properties
                    if let Ok(proxy) = zbus::blocking::Proxy::new(
                        &conn,
                        "org.freedesktop.NetworkManager",
                        "/org/freedesktop/NetworkManager",
                        "org.freedesktop.NetworkManager",
                    ) {
                        if let Ok(mut signal) = proxy.receive_signal("StateChanged") {
                            while let Some(_msg) = signal.next() {
                                let network_manager = VSKNetworkManager {
                                    connection: connection_clone.clone(),
                                    proxy: zbus::blocking::fdo::PropertiesProxy::builder(
                                        &connection_clone,
                                    )
                                    .destination("org.freedesktop.NetworkManager")
                                    .unwrap()
                                    .path("/org/freedesktop/NetworkManager")
                                    .unwrap()
                                    .build()
                                    .unwrap(),
                                    app: app_handle.clone(),
                                };

                                if let Ok(network_info) =
                                    network_manager.get_current_network_state()
                                {
                                    if tx.send(network_info).is_err() {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!(
                        "Error al conectar con D-Bus para escuchar cambios de red: {:?}",
                        e
                    );
                }
            }
        });

        Ok(rx)
    }

    /// Disconnect from the current WiFi network
    pub fn disconnect_from_wifi(&self) -> Result<()> {
        // Obtener el estado actual de la red para identificar la conexión activa
        let _current_state = self.get_current_network_state()?;

        // Crear un proxy para NetworkManager
        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;

        // Obtener las conexiones activas
        let active_connections_variant: zbus::zvariant::OwnedValue = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "ActiveConnections",
        )?;

        // Convertir el valor a un vector de ObjectPath
        let active_connections = match active_connections_variant.downcast_ref() {
            Some(zbus::zvariant::Value::Array(arr)) => arr
                .iter()
                .filter_map(|v| match v {
                    zbus::zvariant::Value::ObjectPath(path) => {
                        Some(zbus::zvariant::OwnedObjectPath::from(path.to_owned()))
                    }
                    _ => None,
                })
                .collect::<Vec<zbus::zvariant::OwnedObjectPath>>(),
            _ => Vec::new(),
        };

        if !active_connections.is_empty() {
            nm_proxy.call::<_, _, ()>("DeactivateConnection", &(active_connections[0].as_str()))?;
            Ok(())
        } else {
            Ok(())
        }
    }

    /// Get the list of saved WiFi networks
    pub fn get_saved_wifi_networks(&self) -> Result<Vec<NetworkInfo>> {
        // Crear un proxy para el servicio de configuración de NetworkManager
        let settings_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager/Settings",
            "org.freedesktop.NetworkManager.Settings",
        )?;

        // Obtener todas las conexiones guardadas
        let connections: Vec<zbus::zvariant::OwnedObjectPath> =
            settings_proxy.call("ListConnections", &())?;
        let mut saved_networks = Vec::new();

        // Procesar cada conexión guardada
        for conn_path in connections {
            // Crear un proxy para cada conexión
            let conn_proxy = zbus::blocking::Proxy::new(
                &self.connection,
                "org.freedesktop.NetworkManager",
                conn_path.as_str(),
                "org.freedesktop.NetworkManager.Settings.Connection",
            )?;

            // Obtener la configuración de la conexión como un HashMap
            let settings: std::collections::HashMap<String, zbus::zvariant::OwnedValue> =
                conn_proxy.call("GetSettings", &())?;

            // Verificar si es una conexión WiFi
            if let Some(connection) = settings.get("connection") {
                let connection_value = connection.to_owned();
                let connection_dict =
                    match <zbus::zvariant::Value<'_> as Clone>::clone(&connection_value)
                        .downcast::<std::collections::HashMap<String, zbus::zvariant::OwnedValue>>(
                    ) {
                        Some(dict) => dict,
                        _ => continue,
                    };

                // Verificar el tipo de conexión
                if let Some(conn_type) = connection_dict.get("type") {
                    let conn_type_value = conn_type.to_owned();
                    let conn_type_str =
                        match <zbus::zvariant::Value<'_> as Clone>::clone(&conn_type_value)
                            .downcast::<String>()
                        {
                            Some(s) => s,
                            _ => continue,
                        };

                    // Si es una conexión WiFi, extraer la información
                    if conn_type_str == "802-11-wireless" {
                        let mut network_info = NetworkInfo::default();
                        network_info.connection_type = "wifi".to_string();

                        // Obtener el nombre de la conexión
                        if let Some(id) = connection_dict.get("id") {
                            let id_value = id.to_owned();
                            if let Some(name) =
                                <zbus::zvariant::Value<'_> as Clone>::clone(&id_value)
                                    .downcast::<String>()
                            {
                                network_info.name = name;
                            }
                        }

                        // Obtener el SSID
                        if let Some(wireless) = settings.get("802-11-wireless") {
                            let wireless_value = wireless.to_owned();
                            let wireless_dict = match <zbus::zvariant::Value<'_> as Clone>::clone(&wireless_value).downcast::<std::collections::HashMap<String, zbus::zvariant::OwnedValue>>() {
                                Some(dict) => dict,
                                _ => continue,
                            };

                            if let Some(ssid) = wireless_dict.get("ssid") {
                                let ssid_value = ssid.to_owned();
                                if let Some(ssid_bytes) =
                                    <zbus::zvariant::Value<'_> as Clone>::clone(&ssid_value)
                                        .downcast::<Vec<u8>>()
                                {
                                    if let Ok(ssid_str) = String::from_utf8(ssid_bytes) {
                                        network_info.ssid = ssid_str;
                                    }
                                }
                            }
                        }

                        // Determinar el tipo de seguridad
                        if let Some(security) = settings.get("802-11-wireless-security") {
                            let security_value = security.to_owned();
                            let security_dict = match <zbus::zvariant::Value<'_> as Clone>::clone(&security_value).downcast::<std::collections::HashMap<String, zbus::zvariant::OwnedValue>>() {
                                Some(dict) => dict,
                                _ => {
                                    network_info.security_type = WiFiSecurityType::None;
                                    saved_networks.push(network_info);
                                    continue;
                                },
                            };

                            if let Some(key_mgmt) = security_dict.get("key-mgmt") {
                                let key_mgmt_value = key_mgmt.to_owned();
                                if let Some(key_mgmt_str) =
                                    <zbus::zvariant::Value<'_> as Clone>::clone(&key_mgmt_value)
                                        .downcast::<String>()
                                {
                                    match key_mgmt_str.as_str() {
                                        "none" => {
                                            network_info.security_type = WiFiSecurityType::None
                                        }
                                        "wpa-psk" => {
                                            network_info.security_type = WiFiSecurityType::WpaPsk
                                        }
                                        "wpa-eap" => {
                                            network_info.security_type = WiFiSecurityType::WpaEap
                                        }
                                        _ => network_info.security_type = WiFiSecurityType::None,
                                    }
                                }
                            }
                        } else {
                            network_info.security_type = WiFiSecurityType::None;
                        }

                        // Agregar a la lista de redes guardadas
                        saved_networks.push(network_info);
                    }
                }
            }
        }

        Ok(saved_networks)
    }

    /// Delete a saved WiFi connection by SSID
    pub fn delete_wifi_connection(&self, ssid: &str) -> Result<bool> {
        // Crear un proxy para el servicio de configuración de NetworkManager
        let settings_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager/Settings",
            "org.freedesktop.NetworkManager.Settings",
        )?;

        // Obtener todas las conexiones guardadas
        let connections: Vec<zbus::zvariant::OwnedObjectPath> =
            settings_proxy.call("ListConnections", &())?;

        // Procesar cada conexión guardada
        for conn_path in connections {
            // Crear un proxy para cada conexión
            let conn_proxy = zbus::blocking::Proxy::new(
                &self.connection,
                "org.freedesktop.NetworkManager",
                conn_path.as_str(),
                "org.freedesktop.NetworkManager.Settings.Connection",
            )?;

            // Obtener la configuración de la conexión como un HashMap
            let settings: std::collections::HashMap<String, zbus::zvariant::OwnedValue> =
                conn_proxy.call("GetSettings", &())?;

            // Verificar si es una conexión WiFi
            if let Some(connection) = settings.get("connection") {
                let connection_value = connection.to_owned();
                let connection_dict =
                    match <zbus::zvariant::Value<'_> as Clone>::clone(&connection_value)
                        .downcast::<std::collections::HashMap<String, zbus::zvariant::OwnedValue>>(
                    ) {
                        Some(dict) => dict,
                        _ => continue,
                    };

                // Verificar el tipo de conexión
                if let Some(conn_type) = connection_dict.get("type") {
                    let conn_type_value = conn_type.to_owned();
                    let conn_type_str =
                        match <zbus::zvariant::Value<'_> as Clone>::clone(&conn_type_value)
                            .downcast::<String>()
                        {
                            Some(s) => s,
                            _ => continue,
                        };

                    // Si es una conexión WiFi, verificar el SSID
                    if conn_type_str == "802-11-wireless" {
                        if let Some(wireless) = settings.get("802-11-wireless") {
                            let wireless_value = wireless.to_owned();
                            let wireless_dict = match <zbus::zvariant::Value<'_> as Clone>::clone(&wireless_value).downcast::<std::collections::HashMap<String, zbus::zvariant::OwnedValue>>() {
                                Some(dict) => dict,
                                _ => continue,
                            };

                            if let Some(ssid_value) = wireless_dict.get("ssid") {
                                let ssid_owned = ssid_value.to_owned();
                                if let Some(ssid_bytes) =
                                    <zbus::zvariant::Value<'_> as Clone>::clone(&ssid_owned)
                                        .downcast::<Vec<u8>>()
                                {
                                    if let Ok(conn_ssid_str) = String::from_utf8(ssid_bytes) {
                                        // Si el SSID coincide, eliminar la conexión
                                        if conn_ssid_str == ssid {
                                            conn_proxy.call::<_, _, ()>("Delete", &())?;
                                            return Ok(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // No se encontró ninguna conexión con el SSID especificado
        Ok(false)
    }

    /// List saved VPN profiles from NetworkManager settings.
    pub fn list_vpn_profiles(&self) -> Result<Vec<VpnProfile>> {
        let connections = self.list_connection_paths()?;
        let mut profiles = Vec::new();

        for conn_path in connections {
            let settings = self.get_connection_settings(&conn_path)?;
            if let Some(profile) = self.vpn_profile_from_settings(&settings) {
                profiles.push(profile);
            }
        }

        profiles.sort_by(|a, b| a.id.cmp(&b.id));
        Ok(profiles)
    }

    /// Get current VPN status from active connections.
    pub fn get_vpn_status(&self) -> Result<VpnStatus> {
        let active_connections_variant = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "ActiveConnections",
        )?;

        let mut status = VpnStatus::default();

        if let Some(zbus::zvariant::Value::Array(arr)) = active_connections_variant.downcast_ref() {
            for value in arr.iter() {
                let active_path = match value {
                    zbus::zvariant::Value::ObjectPath(path) => path,
                    _ => continue,
                };

                let active_props = zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                    .destination("org.freedesktop.NetworkManager")?
                    .path(active_path)?
                    .build()?;

                let conn_type_variant = active_props.get(
                    InterfaceName::from_static_str_unchecked(
                        "org.freedesktop.NetworkManager.Connection.Active",
                    ),
                    "Type",
                )?;

                let conn_type = match conn_type_variant.downcast_ref() {
                    Some(zbus::zvariant::Value::Str(v)) => v.to_string(),
                    _ => continue,
                };

                if conn_type != "vpn" {
                    continue;
                }

                let state_variant = active_props.get(
                    InterfaceName::from_static_str_unchecked(
                        "org.freedesktop.NetworkManager.Connection.Active",
                    ),
                    "State",
                )?;
                let state = match state_variant.downcast_ref() {
                    Some(zbus::zvariant::Value::U32(v)) => *v,
                    _ => 0,
                };

                let id_variant = active_props.get(
                    InterfaceName::from_static_str_unchecked(
                        "org.freedesktop.NetworkManager.Connection.Active",
                    ),
                    "Id",
                )?;
                let uuid_variant = active_props.get(
                    InterfaceName::from_static_str_unchecked(
                        "org.freedesktop.NetworkManager.Connection.Active",
                    ),
                    "Uuid",
                )?;

                status.state = Self::vpn_state_from_active_state(state);
                status.active_profile_name = match id_variant.downcast_ref() {
                    Some(zbus::zvariant::Value::Str(v)) => Some(v.to_string()),
                    _ => None,
                };
                status.active_profile_id = status.active_profile_name.clone();
                status.active_profile_uuid = match uuid_variant.downcast_ref() {
                    Some(zbus::zvariant::Value::Str(v)) => Some(v.to_string()),
                    _ => None,
                };

                let ip4_config_variant = active_props.get(
                    InterfaceName::from_static_str_unchecked(
                        "org.freedesktop.NetworkManager.Connection.Active",
                    ),
                    "Ip4Config",
                )?;

                if let Some(zbus::zvariant::Value::ObjectPath(ip4_path)) =
                    ip4_config_variant.downcast_ref()
                {
                    if ip4_path.as_str() != "/" {
                        let ip4_props = zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                            .destination("org.freedesktop.NetworkManager")?
                            .path(ip4_path)?
                            .build()?;

                        if let Ok(gateway_variant) = ip4_props.get(
                            InterfaceName::from_static_str_unchecked(
                                "org.freedesktop.NetworkManager.IP4Config",
                            ),
                            "Gateway",
                        ) {
                            status.gateway = match gateway_variant.downcast_ref() {
                                Some(zbus::zvariant::Value::Str(v)) => Some(v.to_string()),
                                _ => None,
                            };
                        }
                    }
                }

                return Ok(status);
            }
        }

        Ok(status)
    }

    /// Connect a VPN profile by UUID.
    pub fn connect_vpn(&self, uuid: String) -> Result<()> {
        let current_status = self.get_vpn_status()?;
        if current_status.state == VpnConnectionState::Connected
            && current_status.active_profile_uuid.as_deref() == Some(uuid.as_str())
        {
            return Err(crate::error::NetworkError::VpnAlreadyConnected(uuid));
        }

        let conn_path = self.find_connection_path_by_uuid(&uuid)?;

        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;

        let activate_result: zbus::Result<zbus::zvariant::OwnedObjectPath> =
            nm_proxy.call("ActivateConnection", &(conn_path.as_str(), "/", "/"));

        match activate_result {
            Ok(_) => Ok(()),
            Err(e) => {
                let msg = e.to_string().to_lowercase();
                if msg.contains("secret") || msg.contains("authentication") {
                    Err(crate::error::NetworkError::VpnAuthFailed(e.to_string()))
                } else {
                    Err(crate::error::NetworkError::VpnActivationFailed(e.to_string()))
                }
            }
        }
    }

    /// Disconnect VPN by UUID or disconnect active VPN if UUID is not provided.
    pub fn disconnect_vpn(&self, uuid: Option<String>) -> Result<()> {
        let active_connections_variant = self.proxy.get(
            InterfaceName::from_static_str_unchecked("org.freedesktop.NetworkManager"),
            "ActiveConnections",
        )?;

        let mut target_active_connection: Option<zbus::zvariant::OwnedObjectPath> = None;

        if let Some(zbus::zvariant::Value::Array(arr)) = active_connections_variant.downcast_ref() {
            for value in arr.iter() {
                let active_path = match value {
                    zbus::zvariant::Value::ObjectPath(path) => {
                        zbus::zvariant::OwnedObjectPath::from(path.to_owned())
                    }
                    _ => continue,
                };

                let active_props = zbus::blocking::fdo::PropertiesProxy::builder(&self.connection)
                    .destination("org.freedesktop.NetworkManager")?
                    .path(active_path.as_str())?
                    .build()?;

                let conn_type_variant = active_props.get(
                    InterfaceName::from_static_str_unchecked(
                        "org.freedesktop.NetworkManager.Connection.Active",
                    ),
                    "Type",
                )?;
                let conn_type = match conn_type_variant.downcast_ref() {
                    Some(zbus::zvariant::Value::Str(v)) => v.to_string(),
                    _ => continue,
                };

                if conn_type != "vpn" {
                    continue;
                }

                if let Some(target_uuid) = uuid.as_deref() {
                    let uuid_variant = active_props.get(
                        InterfaceName::from_static_str_unchecked(
                            "org.freedesktop.NetworkManager.Connection.Active",
                        ),
                        "Uuid",
                    )?;
                    let active_uuid = match uuid_variant.downcast_ref() {
                        Some(zbus::zvariant::Value::Str(v)) => v.to_string(),
                        _ => continue,
                    };

                    if active_uuid == target_uuid {
                        target_active_connection = Some(active_path.clone());
                        break;
                    }
                } else {
                    target_active_connection = Some(active_path.clone());
                    break;
                }
            }
        }

        let target_active_connection = match target_active_connection {
            Some(path) => path,
            None => {
                if let Some(target_uuid) = uuid {
                    return Err(crate::error::NetworkError::VpnProfileNotFound(target_uuid));
                }
                return Err(crate::error::NetworkError::VpnNotActive);
            }
        };

        let nm_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager",
            "org.freedesktop.NetworkManager",
        )?;

        nm_proxy.call::<_, _, ()>(
            "DeactivateConnection",
            &(target_active_connection.as_str(),),
        )?;
        Ok(())
    }

    /// Create a new VPN profile in NetworkManager settings.
    pub fn create_vpn_profile(&self, config: VpnCreateConfig) -> Result<VpnProfile> {
        if config.id.trim().is_empty() {
            return Err(crate::error::NetworkError::VpnInvalidConfig(
                "id is required".to_string(),
            ));
        }

        let uuid = Uuid::new_v4().to_string();
        let mut connection_section = HashMap::new();
        connection_section.insert("id".to_string(), Value::from(config.id.clone()));
        connection_section.insert("uuid".to_string(), Value::from(uuid.clone()));
        connection_section.insert("type".to_string(), Value::from("vpn"));
        connection_section.insert(
            "autoconnect".to_string(),
            Value::from(config.autoconnect.unwrap_or(false)),
        );

        let mut vpn_section = HashMap::new();
        vpn_section.insert(
            "service-type".to_string(),
            Value::from(Self::service_type_from_vpn_type(&config.vpn_type)),
        );

        if let Some(username) = config.username {
            vpn_section.insert("user-name".to_string(), Value::from(username));
        }
        if let Some(gateway) = config.gateway {
            vpn_section.insert("remote".to_string(), Value::from(gateway));
        }
        if let Some(ca_cert_path) = config.ca_cert_path {
            vpn_section.insert("ca".to_string(), Value::from(ca_cert_path));
        }
        if let Some(user_cert_path) = config.user_cert_path {
            vpn_section.insert("cert".to_string(), Value::from(user_cert_path));
        }
        if let Some(private_key_path) = config.private_key_path {
            vpn_section.insert("key".to_string(), Value::from(private_key_path));
        }
        if let Some(private_key_password) = config.private_key_password {
            vpn_section.insert("key-password".to_string(), Value::from(private_key_password));
        }
        if let Some(custom_settings) = config.settings {
            for (k, v) in custom_settings {
                vpn_section.insert(k, Value::from(v));
            }
        }

        let mut vpn_secrets_section = HashMap::new();
        if let Some(password) = config.password {
            vpn_secrets_section.insert("password".to_string(), Value::from(password));
        }
        if let Some(custom_secrets) = config.secrets {
            for (k, v) in custom_secrets {
                vpn_secrets_section.insert(k, Value::from(v));
            }
        }

        let mut settings: HashMap<String, HashMap<String, Value>> = HashMap::new();
        settings.insert("connection".to_string(), connection_section);
        settings.insert("vpn".to_string(), vpn_section);
        if !vpn_secrets_section.is_empty() {
            settings.insert("vpn-secrets".to_string(), vpn_secrets_section);
        }

        let settings_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            "/org/freedesktop/NetworkManager/Settings",
            "org.freedesktop.NetworkManager.Settings",
        )?;

        let _created_path: zbus::zvariant::OwnedObjectPath =
            settings_proxy.call("AddConnection", &(settings,))?;

        Ok(VpnProfile {
            id: config.id,
            uuid,
            vpn_type: config.vpn_type,
            interface_name: None,
            autoconnect: config.autoconnect.unwrap_or(false),
            editable: true,
            last_error: None,
        })
    }

    /// Update an existing VPN profile by UUID.
    pub fn update_vpn_profile(&self, config: VpnUpdateConfig) -> Result<VpnProfile> {
        let conn_path = self.find_connection_path_by_uuid(&config.uuid)?;
        let existing_settings = self.get_connection_settings(&conn_path)?;

        let existing_profile = self
            .vpn_profile_from_settings(&existing_settings)
            .ok_or_else(|| crate::error::NetworkError::VpnProfileNotFound(config.uuid.clone()))?;

        let existing_vpn_settings = Self::string_map_from_section(&existing_settings, "vpn");
        let existing_vpn_secrets = Self::string_map_from_section(&existing_settings, "vpn-secrets");

        // Start from the full current settings map to preserve unrelated sections
        // (IPv4/IPv6, routes, DNS, permissions, proxy, etc.).
        let mut settings: HashMap<String, HashMap<String, Value>> = HashMap::new();
        for (section_name, section_value) in &existing_settings {
            let raw_value = section_value.to_owned();
            let dict = match <zbus::zvariant::Value<'_> as Clone>::clone(&raw_value)
                .downcast::<HashMap<String, zbus::zvariant::OwnedValue>>()
            {
                Some(d) => d,
                None => continue,
            };

            let mut section_map: HashMap<String, Value> = HashMap::new();
            for (k, v) in dict {
                section_map.insert(k, <zbus::zvariant::Value<'_> as Clone>::clone(&v));
            }
            settings.insert(section_name.clone(), section_map);
        }

        let connection_section = settings
            .entry("connection".to_string())
            .or_insert_with(HashMap::new);
        connection_section.insert(
            "id".to_string(),
            Value::from(config.id.clone().unwrap_or(existing_profile.id.clone())),
        );
        connection_section.insert("uuid".to_string(), Value::from(config.uuid.clone()));
        connection_section.insert("type".to_string(), Value::from("vpn"));
        connection_section.insert(
            "autoconnect".to_string(),
            Value::from(config.autoconnect.unwrap_or(existing_profile.autoconnect)),
        );

        let service_type = existing_vpn_settings
            .get("service-type")
            .cloned()
            .unwrap_or_else(|| {
                Self::service_type_from_vpn_type(&existing_profile.vpn_type).to_string()
            });

        let vpn_section = settings
            .entry("vpn".to_string())
            .or_insert_with(HashMap::new);
        vpn_section.insert("service-type".to_string(), Value::from(service_type));

        let mut merged_settings = existing_vpn_settings;
        if let Some(username) = config.username {
            merged_settings.insert("user-name".to_string(), username);
        }
        if let Some(gateway) = config.gateway {
            merged_settings.insert("remote".to_string(), gateway);
        }
        if let Some(ca_cert_path) = config.ca_cert_path {
            merged_settings.insert("ca".to_string(), ca_cert_path);
        }
        if let Some(user_cert_path) = config.user_cert_path {
            merged_settings.insert("cert".to_string(), user_cert_path);
        }
        if let Some(private_key_path) = config.private_key_path {
            merged_settings.insert("key".to_string(), private_key_path);
        }
        if let Some(private_key_password) = config.private_key_password {
            merged_settings.insert("key-password".to_string(), private_key_password);
        }
        if let Some(custom_settings) = config.settings {
            for (k, v) in custom_settings {
                merged_settings.insert(k, v);
            }
        }

        for (k, v) in merged_settings {
            vpn_section.insert(k, Value::from(v));
        }

        let mut merged_secrets = existing_vpn_secrets;
        if let Some(password) = config.password {
            merged_secrets.insert("password".to_string(), password);
        }
        if let Some(custom_secrets) = config.secrets {
            for (k, v) in custom_secrets {
                merged_secrets.insert(k, v);
            }
        }

        if merged_secrets.is_empty() {
            settings.remove("vpn-secrets");
        } else {
            let vpn_secrets_section = settings
                .entry("vpn-secrets".to_string())
                .or_insert_with(HashMap::new);
            vpn_secrets_section.clear();
            for (k, v) in merged_secrets {
                vpn_secrets_section.insert(k, Value::from(v));
            }
        }

        let conn_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            conn_path.as_str(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )?;
        conn_proxy.call::<_, _, ()>("Update", &(settings,))?;

        let updated_settings = self.get_connection_settings(&conn_path)?;
        self.vpn_profile_from_settings(&updated_settings)
            .ok_or_else(|| crate::error::NetworkError::VpnProfileNotFound(config.uuid))
    }

    /// Delete a VPN profile by UUID.
    pub fn delete_vpn_profile(&self, uuid: String) -> Result<()> {
        let conn_path = self.find_connection_path_by_uuid(&uuid)?;

        let conn_proxy = zbus::blocking::Proxy::new(
            &self.connection,
            "org.freedesktop.NetworkManager",
            conn_path.as_str(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )?;

        conn_proxy.call::<_, _, ()>("Delete", &())?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn vpn_state_deactivated_maps_to_disconnected() {
        assert_eq!(
            VSKNetworkManager::<tauri::Wry>::vpn_state_from_active_state(4),
            VpnConnectionState::Disconnected
        );
    }
}

/// Initialize the network manager plugin
pub async fn init(
    app: &AppHandle<tauri::Wry>,
    _api: PluginApi<tauri::Wry, ()>,
) -> Result<VSKNetworkManager<'static, tauri::Wry>> {
    Ok(VSKNetworkManager::new(app.clone()).await?)
}