use bevy::prelude::*;

/// Plugin for all of `rantz_suite`. To setup all it's sub-plugins, add this to your app.
pub struct RantzSuitePlugin {
    /// The name of your game, used to create the root save path for `rantz_cereal`.
    /// This folder will be created in the users data directory in release builds:
    ///
    /// Platform  | Value                                   | Example
    /// Linux     | `$XDG_DATA_HOME` or $HOME/.local/share  | /home/alice/.local/share
    /// macOS     | $HOME/Library/Application Support       | /Users/Alice/Library/Application
    /// Support Windows   | `{FOLDERID_RoamingAppData}`             |
    /// C:\Users\Alice\AppData\Roaming
    ///
    /// In debug builds, the folder will be created in `saves/` in the workspace root.
    ///
    /// any non-ascii characters in the name will be replaced with _
    #[cfg(feature = "cereal")]
    pub game_name: String,
}

impl Plugin for RantzSuitePlugin {
    fn build(&self, app: &mut App) {
        self.init_resources(app);
        self.add_systems(app);
        self.add_plugins(app);
    }
}

impl RantzSuitePlugin {
    /// Creates a new `CerealPlugin` with the given save root
    pub fn new(root_save_path: &str) -> Self {
        let root_save_path = root_save_path.replace(|c: char| !c.is_ascii(), "_");
        Self {
            game_name: root_save_path,
        }
    }

    fn init_resources(&self, _: &mut App) {}

    fn add_systems(&self, _: &mut App) {}

    fn add_plugins(&self, app: &mut App) {
        #[cfg(feature = "spatial2d")]
        app.add_plugins(crate::spatial2d::SpatialPlugin2D);
        #[cfg(feature = "camera2d")]
        app.add_plugins(crate::camera2d::CameraPlugin2D);
        #[cfg(all(feature = "proto", not(feature = "cereal")))]
        app.add_plugins(crate::proto::ProtoPlugin);
        #[cfg(feature = "cereal")]
        app.add_plugins(crate::cereal::CerealPlugin::new(&self.game_name));
    }
}

impl Default for RantzSuitePlugin {
    fn default() -> Self {
        Self::new("default_game")
    }
}
