//! Play mode toggles and possession controls.

use bevy::prelude::*;

use crate::play::state::{toggle_play_possession_world, EditorMode, PlayPaused};
use crate::project_io::UserPreferences;
use crate::scene_io::{save_active_or_prompt_world, SceneIo};

pub fn toggle_play_mode(world: &mut World) {
    let entering_play = *world.resource::<State<EditorMode>>().get() == EditorMode::Editing;
    if entering_play {
        let save_before = world.resource::<UserPreferences>().save_before_play;
        if save_before && world.resource::<SceneIo>().dirty {
            let status = save_active_or_prompt_world(world);
            if status.contains("failed") || status.contains("cancelled") {
                world.resource_mut::<SceneIo>().set_status(status);
                return;
            }
        }
    }
    let next = if entering_play {
        EditorMode::Playing
    } else {
        EditorMode::Editing
    };
    world.resource_mut::<NextState<EditorMode>>().set(next);
}

pub fn toggle_play_paused(world: &mut World) {
    if *world.resource::<State<EditorMode>>().get() != EditorMode::Playing {
        return;
    }
    let mut paused = world.resource_mut::<PlayPaused>();
    paused.0 = !paused.0;
}

pub fn toggle_possession(world: &mut World) {
    toggle_play_possession_world(world);
}
