use ashpd::desktop::{
    screencast::{CursorMode, Screencast, SourceType},
    PersistMode,
};
use godot::prelude::*;
use godot_tokio::AsyncRuntime;
use std::thread;

#[derive(GodotClass)]
#[class(base=RefCounted)]
struct ScreencastResult {
    base: Base<RefCounted>,
}

#[godot_api]
impl IRefCounted for ScreencastResult {
    fn init(base: Base<RefCounted>) -> Self {
        let mut result = Self { base };
        //thread::spawn(|| result.capture_runner());

        result
    }
}

#[godot_api]
impl ScreencastResult {
    fn capture_runner(&mut self) {
        AsyncRuntime::block_on(async {
            let proxy = Screencast::new().await.expect("Screencast proxy failed");
            let session = match proxy.create_session().await {
                Ok(x) => x,
                Err(err) => {
                    godot_warn!("Failed to create session: {}", err);
                    return;
                }
            };
            match proxy
                .select_sources(
                    &session,
                    CursorMode::Metadata,
                    SourceType::Monitor | SourceType::Window,
                    true,
                    None,
                    PersistMode::DoNot,
                )
                .await
            {
                Ok(_) => {}
                Err(err) => {
                    godot_warn!("Err while selecting source: {}", err);
                    return;
                }
            }

            let starter = match proxy.start(&session, None).await {
                Ok(x) => x,
                Err(err) => {
                    godot_warn!("Error while starting: {}", err);
                    return;
                }
            };
            let result = match starter.response() {
                Ok(x) => x,
                Err(err) => {
                    godot_warn!("Err for response: {}", err);
                    return;
                }
            };
            godot_print!("Got response");
            result.streams().iter().for_each(|stream| {
                godot_print!("node id: {}", stream.pipe_wire_node_id());
                godot_print!("size: {:?}", stream.size());
                godot_print!("position: {:?}", stream.position());
                self.base_mut().emit_signal(
                    "screencast_sucess",
                    &[stream.pipe_wire_node_id().to_variant()],
                );
            });
        });
    }
}

unsafe impl Send for ScreencastResult {}
unsafe impl Sync for ScreencastResult {}
