//! Sets up the game's camera controls etc.
//! Uses [bevy_third_person_camera](https://lib.rs/crates/bevy_third_person_camera)
use bevy::prelude::*;
use bevy_third_person_camera::*;

use crate::{AppState, TPCTarget};

use super::GameplaySet;

pub fn plugin(app: &mut App) {
    app.add_plugins(ThirdPersonCameraPlugin)
        .add_systems(
            OnEnter(AppState::Ingame),
            setup_game_camera.in_set(GameplaySet),
        )
        // .add_systems(Update, auto_target)
        .add_systems(OnExit(AppState::Ingame), remove_tpc.in_set(GameplaySet));
}

/// Adds [ThirdPersonCamera] to our existing camera.
pub fn setup_game_camera(mut c: Commands, cam: Single<Entity, With<Camera3d>>) {
    c.entity(*cam).insert(ThirdPersonCamera {
        cursor_lock_key: KeyCode::Space,
        cursor_lock_toggle_enabled: true,
        gamepad_settings: CustomGamepadSettings::default(),
        cursor_lock_active: true,
        sensitivity: Vec2::new(1.0, 1.0),
        mouse_orbit_button_enabled: true,
        mouse_orbit_button: MouseButton::Middle,
        offset_enabled: false,
        offset: Offset::new(0.5, 0.4),
        offset_toggle_enabled: false,
        offset_toggle_speed: 5.0,
        offset_toggle_key: KeyCode::KeyE,
        zoom_enabled: true,
        zoom: Zoom::new(1.5, 30.0),
        zoom_sensitivity: 1.0,
        ..Default::default()
    });
    info!("Third person camera set up!")
}

// fn auto_target(
//     mut c: Commands,
//     without_custom: Query<Entity, (With<ThirdPersonCameraTarget>, Without<TPCTarget>)>,
//     without_lib: Query<Entity, (Without<ThirdPersonCameraTarget>, With<TPCTarget>)>,
// ) {
//     without_custom.iter().for_each(|e| {
//         info!("Deleting ThirdPersonCameraTarget from {e}");
//         c.entity(e).remove::<ThirdPersonCameraTarget>();
//     });
//     without_lib.iter().for_each(|e| {
//         info!("Inserting TPCTarget into {e}");
//         c.entity(e).insert(ThirdPersonCameraTarget);
//     });
// }

/// Removes [ThirdPersonCamera] from the camera.
pub fn remove_tpc(mut c: Commands, cam: Single<Entity, (With<Camera3d>, With<ThirdPersonCamera>)>) {
    c.entity(*cam).remove::<ThirdPersonCamera>();
}
