use godot::{
    classes::{AudioServer, CheckButton, Control, IControl},
    prelude::*,
};

#[derive(GodotClass)]
#[class(base=Control)]
pub struct MainMenu {
    #[export]
    game_scene_path: GString,

    #[export]
    mute_button: Option<Gd<CheckButton>>,

    base: Base<Control>,
}

#[godot_api]
impl IControl for MainMenu {
    fn init(base: Base<Control>) -> Self {
        Self {
            game_scene_path: GString::new(),
            mute_button: None,
            base,
        }
    }

    fn ready(&mut self) {
        let mut audio_server = AudioServer::singleton();
        let master_bus = audio_server.get_bus_index("Master");
        audio_server.set_bus_mute(master_bus, false);
    }
}

#[godot_api]
impl MainMenu {
    #[func]
    fn on_play_pressed(&mut self) {
        if self.game_scene_path.is_empty() {
            godot_error!("MainMenu: Game Scene Path is empty!");
            return;
        }

        let path = self.game_scene_path.clone();

        let scene = load::<PackedScene>(&path);

        if let Some(mut tree) = self.base().get_tree() {
            tree.change_scene_to_packed(&scene);
        }
    }

    #[func]
    fn on_quit_pressed(&mut self) {
        if let Some(mut tree) = self.base().get_tree() {
            tree.quit();
        }
    }

    #[func]
    fn on_mute_toggled(&mut self, toggled_on: bool) {
        let mut audio_server = AudioServer::singleton();
        let master_bus = audio_server.get_bus_index("Master");
        audio_server.set_bus_mute(master_bus, toggled_on);
    }
}
