use super::number::Number;

#[derive(Clone,Copy)]
pub struct Color3{
	r:f32,
	g:f32,
	b:f32,
}
impl Color3{
	pub const fn new(r:f32,g:f32,b:f32)->Self{
		Self{r,g,b}
	}
	pub const fn from_rgb(r:u8,g:u8,b:u8)->Self{
		Color3::new(r as f32/255.0,g as f32/255.0,b as f32/255.0)
	}
}
impl From<rbx_types::Color3> for Color3{
	fn from(value:rbx_types::Color3)->Color3{
		Color3::new(value.r,value.g,value.b)
	}
}
impl From<Color3> for rbx_types::Color3{
	fn from(value:Color3)->rbx_types::Color3{
		rbx_types::Color3::new(value.r,value.g,value.b)
	}
}

pub fn set_globals(lua:&mlua::Lua,globals:&mlua::Table)->Result<(),mlua::Error>{
	let table=lua.create_table()?;

	table.raw_set("new",
		lua.create_function(|_,(r,g,b):(Number,Number,Number)|
			Ok(Color3::new(r.into(),g.into(),b.into()))
		)?
	)?;

	let from_rgb=lua.create_function(|_,(r,g,b):(u8,u8,u8)|
		Ok(Color3::from_rgb(r,g,b))
	)?;
	table.raw_set("fromRGB",from_rgb.clone())?;
	table.raw_set("FromRGB",from_rgb)?;

	globals.set("Color3",table)?;

	Ok(())
}
fn lerp(lhs:f32,rhs:f32,t:f32)->f32{
	lhs+(rhs-lhs)*t
}

impl mlua::UserData for Color3{
	fn add_fields<F:mlua::UserDataFields<Self>>(fields:&mut F){
		fields.add_field_method_get("r",|_,this|Ok(this.r));
		fields.add_field_method_set("r",|_,this,val|{
			this.r=val;
			Ok(())
		});
		fields.add_field_method_get("g",|_,this|Ok(this.g));
		fields.add_field_method_set("g",|_,this,val|{
			this.g=val;
			Ok(())
		});
		fields.add_field_method_get("b",|_,this|Ok(this.b));
		fields.add_field_method_set("b",|_,this,val|{
			this.b=val;
			Ok(())
		});
	}
	fn add_methods<M:mlua::UserDataMethods<Self>>(methods:&mut M){
		methods.add_method("Lerp",|_,this,(other,t):(Self,f32)|
			Ok(Color3::new(
				lerp(this.r,other.r,t),
				lerp(this.g,other.g,t),
				lerp(this.b,other.b,t),
			))
		)
	}
}
type_from_lua_userdata!(Color3);
