use crate::message::Message;

use std::time::{ Duration, Instant };

const TIMEOUT_SECS: u64 = 2;

/// Transient on-screen-display toast (volume / brightness feedback).
pub struct Osd
{
	text:  Option<String>,
	value: f32,
	start: Option<Instant>,
}

impl Osd
{
	pub fn new() -> Self
	{
		Self {
			text:  None,
			value: 0.0,
			start: None,
		}
	}

	pub fn show( &mut self, text: String, value: f32 )
	{
		self.text  = Some( text );
		self.value = value;
		self.start = Some( Instant::now() );
	}

	/// Expire the toast if it has outlived its timeout. Call once per
	/// `poll_external` tick.
	pub fn tick( &mut self )
	{
		if let Some( start ) = self.start
		{
			if start.elapsed() > Duration::from_secs( TIMEOUT_SECS )
			{
				self.text  = None;
				self.start = None;
			}
		}
	}

	pub fn view( &self ) -> Option<ltk::Element<Message>>
	{
		let text = self.text.as_ref()?;

		let toast = ltk::container::<Message>(
			ltk::column::<Message>()
				.padding( 0.0 )
				.spacing( 8.0 )
				.push(
					ltk::text( text.as_str() )
						.size( 16.0 )
						.color( ltk::theme_palette().text_primary )
						.align_center(),
				)
				.push( ltk::progress_bar( self.value ) ),
		)
		.background( ltk::theme_palette().surface_alt )
		.radius( 12.0 )
		.padding( 16.0 );

		Some(
			ltk::column::<Message>()
				.padding( 0.0 )
				.spacing( 0.0 )
				.max_width( 250.0 )
				.push( ltk::spacer() )
				.push( ltk::spacer() )
				.push( ltk::spacer() )
				.push( toast )
				.into(),
		)
	}
}
