//! Multiplayer / determinism editor tooling (H4).

use bevy::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NetPlayProfile {
    #[default]
    LocalPie,
    ListenServer,
    ConnectToServer,
}

#[derive(Resource)]
pub struct NetEditorState {
    pub profile: NetPlayProfile,
    pub server_address: String,
    pub show_determinism_hud: bool,
    pub last_state_hash: u64,
    pub replay_tick: u64,
}

impl Default for NetEditorState {
    fn default() -> Self {
        Self {
            profile: NetPlayProfile::LocalPie,
            server_address: "127.0.0.1:7777".into(),
            show_determinism_hud: true,
            last_state_hash: 0,
            replay_tick: 0,
        }
    }
}

pub struct NetEditorPlugin;

impl Plugin for NetEditorPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<NetEditorState>()
            .add_systems(Update, update_determinism_hud);
    }
}

fn update_determinism_hud(
    mut state: ResMut<NetEditorState>,
    players: Query<(&Transform, &sim::PlayerVelocity), With<sim::Player>>,
) {
    if !state.show_determinism_hud {
        return;
    }
    let Some((transform, velocity)) = players.iter().next() else {
        return;
    };
    state.replay_tick = state.replay_tick.wrapping_add(1);
    let bits = transform.translation.to_array().map(f32::to_bits);
    let vel = velocity.0.to_array().map(f32::to_bits);
    state.last_state_hash = bits[0] as u64 ^ (bits[1] as u64) << 16 ^ vel[0] as u64;
}
