use super::BluetoothState;
use std::process::Command;

pub fn get_bluetooth_state() -> BluetoothState
{
	let output = Command::new( "bluetoothctl" )
		.args( ["show"] )
		.output();

	match output
	{
		Ok( out ) =>
		{
			let stdout = String::from_utf8_lossy( &out.stdout );
			let enabled = stdout.contains( "Powered: yes" );

			let connected_output = Command::new( "bluetoothctl" )
				.args( ["devices", "Connected"] )
				.output();

			let connected = match connected_output
			{
				Ok( out ) =>
				{
					let connected_stdout = String::from_utf8_lossy( &out.stdout );
					let lines: Vec<&str> = connected_stdout.lines().collect();
					!lines.is_empty() && !lines[0].trim().is_empty()
				}
				Err( _ ) => false,
			};

			BluetoothState { enabled, connected }
		}
		Err( _ ) => BluetoothState::default(),
	}
}

pub fn set_bluetooth_power( on: bool )
{
	let arg = if on { "on" } else { "off" };
	if let Err( e ) = Command::new( "bluetoothctl" )
		.args( ["power", arg] )
		.spawn()
	{
		tracing::error!( "Failed to set bluetooth power {}: {}", arg, e );
	}
}


