use godot::{classes::Engine, prelude::*};

mod runtime;

mod player;

struct MyExtension;

#[gdextension]
unsafe impl ExtensionLibrary for MyExtension {
  fn on_level_init(level: InitLevel) {
    if level == InitLevel::Scene {
      let mut engine = Engine::singleton();

      // This is where we register our async runtime singleton.
      engine.register_singleton(
        crate::runtime::tokio::AsyncRuntime::SINGLETON,
        &crate::runtime::tokio::AsyncRuntime::new_alloc(),
      );
    }
  }

  fn on_level_deinit(level: InitLevel) {
    if level == InitLevel::Scene {
      let mut engine = Engine::singleton();

      // Here is where we free our async runtime singleton from memory.
      if let Some(async_singleton) = engine.get_singleton(crate::runtime::tokio::AsyncRuntime::SINGLETON) {
        engine.unregister_singleton(crate::runtime::tokio::AsyncRuntime::SINGLETON);
        async_singleton.free();
      } else {
        godot_warn!(
          "Failed to find & free singleton -> {}",
          crate::runtime::tokio::AsyncRuntime::SINGLETON
        );
      }
    }
  }
}
