From 97d9222a39cdc1ac1ce457f5de05b56bc75bd951 Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Wed, 24 Apr 2024 01:49:02 +0200
Subject: [PATCH] Add function to update schedules for relays WsAction

---
 emgauwa-controller/src/ws/mod.rs | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)

diff --git a/emgauwa-controller/src/ws/mod.rs b/emgauwa-controller/src/ws/mod.rs
index 50f105e..09ade3e 100644
--- a/emgauwa-controller/src/ws/mod.rs
+++ b/emgauwa-controller/src/ws/mod.rs
@@ -1,6 +1,6 @@
 use actix::Addr;
 use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT;
-use emgauwa_lib::db::{DbController, DbRelay, DbSchedule};
+use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
 use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
 use emgauwa_lib::models::{Controller, Relay};
 use emgauwa_lib::types::{ControllerWsAction, ScheduleUid};
@@ -192,13 +192,24 @@ async fn handle_relays(
 				"Controller UID mismatch during relay update",
 			)));
 		}
-		DbRelay::get_by_controller_and_num(conn, &this.c, relay.r.number)
+		let db_relay = DbRelay::get_by_controller_and_num(conn, &this.c, relay.r.number)
 			.await?
-			.ok_or(DatabaseError::NotFound)?
-			.update(conn, relay.r.name.as_str())
-			.await?;
+			.ok_or(DatabaseError::NotFound)?;
 
-		handle_schedules(conn, app_state, relay.schedules).await?;
+		db_relay.update(conn, relay.r.name.as_str()).await?;
+
+		handle_schedules(conn, app_state, relay.schedules.clone()).await?;
+
+		let mut schedules = Vec::new(); // We need to get the schedules from the database to have the right IDs
+		for schedule in relay.schedules {
+			schedules.push(
+				DbSchedule::get_by_uid(conn, &schedule.uid)
+					.await?
+					.ok_or(DatabaseError::NotFound)?,
+			);
+		}
+
+		DbJunctionRelaySchedule::set_schedules(conn, &db_relay, schedules.iter().collect()).await?;
 	}
 
 	app_state.send(app_state::Reload {}).await??;