use super::color3::Color3;

#[derive(Clone,Copy)]
pub struct BrickColor(rbx_types::BrickColor);
impl BrickColor{
	pub fn from_name(name:&str)->Option<Self>{
		Some(BrickColor(rbx_types::BrickColor::from_name(name)?))
	}
	pub fn from_number(number:u16)->Option<Self>{
		Some(BrickColor(rbx_types::BrickColor::from_number(number)?))
	}
}

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:mlua::Value|
			match r{
				mlua::Value::String(name)=>Ok(BrickColor::from_name(&*name.to_str()?)),
				mlua::Value::Integer(number)=>Ok(BrickColor::from_number(number as u16)),
				_=>Err(mlua::Error::runtime("Unsupported arguments"))
			}

		)?
	)?;

	macro_rules! brickcolor_constructor{
		($fname:expr,$internal:ident)=>{
			table.raw_set($fname,
				lua.create_function(|_,_:()|
					Ok(BrickColor(rbx_types::BrickColor::$internal))
				)?
			)?;
		};
	}
	brickcolor_constructor!("White",White);
	brickcolor_constructor!("Gray",MediumStoneGrey);
	brickcolor_constructor!("DarkGray",DarkStoneGrey);
	brickcolor_constructor!("Black",Black);
	brickcolor_constructor!("Red",BrightRed);
	brickcolor_constructor!("Yellow",BrightYellow);
	brickcolor_constructor!("Green",DarkGreen);
	brickcolor_constructor!("Blue",BrightBlue);

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

	Ok(())
}

impl mlua::UserData for BrickColor{
	fn add_fields<F:mlua::UserDataFields<Self>>(fields:&mut F){
		fields.add_field_method_get("Color",|_,BrickColor(this)|{
			let rbx_types::Color3uint8{r,g,b}=this.to_color3uint8();
			Ok(Color3::from_rgb(r,g,b))
		});
	}
}
type_from_lua_userdata!(BrickColor);
