pub use tick::Tick;
mod tick{
	#[derive(Clone,Copy,Default,Hash,PartialEq,Eq,PartialOrd,Ord)]
	pub struct Tick(u64);
	impl std::ops::Add<u64> for Tick{
		type Output=Self;
		fn add(self,rhs:u64)->Self::Output{
			Self(self.0+rhs)
		}
	}
	impl std::ops::Sub<u64> for Tick{
		type Output=Self;
		fn sub(self,rhs:u64)->Self::Output{
			Self(self.0-rhs)
		}
	}
	impl std::ops::AddAssign<u64> for Tick{
		fn add_assign(&mut self,rhs:u64){
			self.0+=rhs;
		}
	}
	impl std::ops::SubAssign<u64> for Tick{
		fn sub_assign(&mut self,rhs:u64){
			self.0-=rhs;
		}
	}
}
#[derive(Default)]
pub struct Scheduler{
	tick:Tick,
	schedule:std::collections::HashMap<Tick,Vec<mlua::Thread>>,
}

impl Scheduler{
	pub fn has_scheduled_threads(&self)->bool{
		!self.schedule.is_empty()
	}
	pub fn schedule_thread(&mut self,delay:u64,thread:mlua::Thread){
		self.schedule.entry(self.tick+delay.max(1))
		.or_insert(Vec::new())
		.push(thread);
	}
	pub fn tick_threads(&mut self)->Option<Vec<mlua::Thread>>{
		self.tick+=1;
		self.schedule.remove(&self.tick)
	}
}

pub fn scheduler_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut Scheduler)->mlua::Result<T>)->mlua::Result<T>{
	let mut scheduler=lua.app_data_mut::<Scheduler>().ok_or_else(||mlua::Error::runtime("Scheduler missing"))?;
	f(&mut *scheduler)
}

pub fn schedule_thread(lua:&mlua::Lua,dt:mlua::Value)->Result<(),mlua::Error>{
	let delay=match dt{
		mlua::Value::Integer(i)=>i.max(0) as u64*60,
		mlua::Value::Number(f)=>{
			let delay=f.max(0.0)*60.0;
			match delay.classify(){
				std::num::FpCategory::Nan=>Err(mlua::Error::runtime("NaN"))?,
				// cases where the number is too large to schedule
				std::num::FpCategory::Infinite
				|std::num::FpCategory::Normal if (u64::MAX as f64)<delay=>{
					return Ok(());
				},
				_=>(),
			}
			delay as u64
		},
		mlua::Value::Nil=>0,
		_=>Err(mlua::Error::runtime("Expected float"))?,
	};
	scheduler_mut(lua,|scheduler|{
		scheduler.schedule_thread(delay.max(2),lua.current_thread());
		Ok(())
	})
}
