use bevy::prelude::*;
use bevy_steamworks::{Client, FriendFlags, SteamworksEvent};
use std::io::{Read, Write};

pub fn plugin(app: &mut App) {
    app.add_plugins(shared::steam::plugin);

    app.add_systems(
        Startup,
        (test_steam_system, log_steam_events)
            .chain()
            .run_if(resource_exists::<Client>),
    );
}

fn log_steam_events(mut events: EventReader<SteamworksEvent>) {
    for e in events.read() {
        info!("steam ev: {:?}", e);
    }
}

fn test_steam_system(steam_client: Res<Client>) {
    steam_client.matchmaking().request_lobby_list(|list| {
        let Ok(list) = list else { return };

        info!("lobby list: [{}]", list.len());
        for (i, l) in list.iter().enumerate() {
            info!("lobby [{i}]: {:?}", l);
        }
    });

    steam_client
        .matchmaking()
        .create_lobby(
            steamworks::LobbyType::FriendsOnly,
            4,
            |result| match result {
                Ok(lobby_id) => {
                    info!("Created lobby with ID: {:?}", lobby_id);
                }
                Err(e) => error!("Failed to create lobby: {}", e),
            },
        );

    for friend in steam_client.friends().get_friends(FriendFlags::IMMEDIATE) {
        info!(
            "Steam Friend: {:?} - {}({:?})",
            friend.id(),
            friend.name(),
            friend.state()
        );
    }

    steam_client
        .remote_storage()
        .set_cloud_enabled_for_app(true);
    let f = steam_client.remote_storage().file("hedz_data.dat");
    if f.exists() {
        let mut buf = String::new();
        if let Err(e) = f.read().read_to_string(&mut buf) {
            error!("File read error: {}", e);
        } else {
            info!("File content: {}", buf);
        }
    } else {
        info!("File does not exist");

        if let Err(e) = f.write().write_all(String::from("hello world").as_bytes()) {
            error!("steam cloud error: {}", e);
        } else {
            info!("steam cloud saved");
        }
    }
}
