use std::sync::mpsc;

use egui::Id;
use rand::{Rng, rng};

pub fn random_id() -> Id {
    Id::new(rng().random::<u64>())
}

/// An [mpsc::Sender] where the receiver is the GUI.
#[derive(Clone)]
pub struct GuiSender<T> {
    tx: mpsc::Sender<T>,
    ctx: egui::Context,
}

impl<T> GuiSender<T> {
    pub fn new(tx: mpsc::Sender<T>, ctx: &egui::Context) -> Self {
        Self {
            tx,
            ctx: ctx.clone(),
        }
    }

    pub fn send(&self, t: T) -> Result<(), mpsc::SendError<T>> {
        self.tx.send(t)?;
        self.ctx.request_repaint();
        Ok(())
    }
}
