use std::sync::mpsc::{ self, Receiver };
use std::time::{ Duration, Instant };

/// Background `fprintd-verify` listener. Polls a match for up to 120 s and
/// reports once over a channel the host drains each tick.
pub struct FingerprintListener
{
	rx: Option<Receiver<bool>>,
}

impl FingerprintListener
{
	pub fn start() -> Self
	{
		let ( tx, rx ) = mpsc::channel();
		let spawned = std::thread::Builder::new()
			.name( "fprintd".into() )
			.spawn( move ||
			{
				let deadline = Instant::now() + Duration::from_secs( 120 );
				while Instant::now() < deadline
				{
					match std::process::Command::new( "fprintd-verify" )
						.arg( "--finger" ).arg( "any" )
						.output()
					{
						Ok( out ) if out.status.success() =>
						{
							if String::from_utf8_lossy( &out.stdout ).contains( "verify-match" )
							{
								let _ = tx.send( true );
								return;
							}
						}
						Err( _ ) => return,
						_ => {}
					}
					std::thread::sleep( Duration::from_secs( 1 ) );
				}
			} );

		Self { rx: spawned.ok().map( |_| rx ) }
	}

	pub fn poll( &mut self ) -> bool
	{
		if let Some( Ok( true ) ) = self.rx.as_ref().map( |rx| rx.try_recv() )
		{
			self.rx = None;
			return true;
		}
		false
	}
}
