import '../../../about/internal/application/ServerProfile.dart'; import '../../../about/internal/application/ServiceConfig.dart'; import '../../parent/ParentViewModel.dart'; import 'ConnectServerDetail.dart'; class ViewServerDetail extends ParentViewModel { ConnectServerDetail connection; ViewServerDetail(super.context, this.connection); /// Re-reads this server from storage along with the deployment history, so /// the screen always reflects what was actually persisted. void loadServer(String serverId) async { try { final servers = await getDataManager().getServers(); final history = await getDataManager().getDeployments(); final stored = servers.where((s) => s.id == serverId).firstOrNull; if (stored == null) { connection.onServerDeleted(); return; } connection.onServerLoaded(stored, history); } catch (error) { handleError(error, () => loadServer(serverId), () {}, "Retry"); } } /// Persists [server] — used after editing the connection, or after adding, /// editing or removing one of its services. void saveServer(ServerProfile server) async { try { final servers = await getDataManager().getServers(); final index = servers.indexWhere((s) => s.id == server.id); if (index >= 0) { servers[index] = server; } else { servers.add(server); } await getDataManager().setServers(servers); loadServer(server.id); } catch (error) { handleError(error, () => saveServer(server), () {}, "Retry"); } } /// Adds [service] to [server] and persists. void addService(ServerProfile server, ServiceConfig service) { server.services.add(service); saveServer(server); } /// Replaces the stored copy of [service] on [server]. void updateService(ServerProfile server, ServiceConfig service) { final index = server.services.indexWhere((s) => s.id == service.id); if (index >= 0) { server.services[index] = service; } else { server.services.add(service); } saveServer(server); } void removeService(ServerProfile server, ServiceConfig service) { server.services.removeWhere((s) => s.id == service.id); saveServer(server); } /// Saves the order services are deployed in during a batch run. void saveDeployOrder(ServerProfile server, List ids) { server.deployOrder = ids; saveServer(server); } void deleteServer(ServerProfile server) async { showLoading("Removing ${server.name} …"); try { final servers = await getDataManager().getServers(); servers.removeWhere((s) => s.id == server.id); await getDataManager().setServers(servers); await getDataManager().deleteServerSecret(server.id); closeLoading(); connection.onServerDeleted(); } catch (error) { handleError(error, () => deleteServer(server), () {}, "Retry"); } } }