use mlua::FromLua;

use super::number::Number;

#[derive(Clone,Copy)]
pub struct Vector3(pub(crate)glam::Vec3A);

impl Vector3{
	pub const fn new(x:f32,y:f32,z:f32)->Self{
		Self(glam::vec3a(x,y,z))
	}
}

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

	//Vector3.new
	table.raw_set("new",
		lua.create_function(|_,(x,y,z):(Option<Number>,Option<Number>,Option<Number>)|
			match (x,y,z){
				(Some(x),Some(y),Some(z))=>Ok(Vector3::new(x.into(),y.into(),z.into())),
				(None,None,None)=>Ok(Vector3(glam::Vec3A::ZERO)),
				_=>Err(mlua::Error::runtime("Unsupported arguments to Vector3.new")),
			}
		)?
	)?;

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

	Ok(())
}

impl From<Vector3> for rbx_types::Vector3{
	fn from(Vector3(v):Vector3)->rbx_types::Vector3{
		rbx_types::Vector3::new(v.x,v.y,v.z)
	}
}

impl From<rbx_types::Vector3> for Vector3{
	fn from(value:rbx_types::Vector3)->Vector3{
		Vector3::new(value.x,value.y,value.z)
	}
}

impl mlua::UserData for Vector3{
	fn add_fields<F:mlua::UserDataFields<Self>>(fields:&mut F){
		fields.add_field_method_get("magnitude",|_,Vector3(this)|Ok(this.length()));
		fields.add_field_method_get("Magnitude",|_,Vector3(this)|Ok(this.length()));
		fields.add_field_method_get("unit",|_,Vector3(this)|Ok(Vector3(this.normalize())));
		fields.add_field_method_get("Unit",|_,Vector3(this)|Ok(Vector3(this.normalize())));
		fields.add_field_method_get("x",|_,Vector3(this)|Ok(this.x));
		fields.add_field_method_get("X",|_,Vector3(this)|Ok(this.x));
		fields.add_field_method_get("y",|_,Vector3(this)|Ok(this.y));
		fields.add_field_method_get("Y",|_,Vector3(this)|Ok(this.y));
		fields.add_field_method_get("z",|_,Vector3(this)|Ok(this.z));
		fields.add_field_method_get("Z",|_,Vector3(this)|Ok(this.z));
	}

	fn add_methods<M:mlua::UserDataMethods<Self>>(methods:&mut M){
		//methods.add_method("area",|_,this,()| Ok(this.length * this.width));

		methods.add_meta_function(mlua::MetaMethod::Add,|_,(Vector3(this),Vector3(val)):(Self,Self)|Ok(Self(this+val)));
		methods.add_meta_function(mlua::MetaMethod::Sub,|_,(Vector3(this),Vector3(val)):(Self,Self)|Ok(Self(this-val)));
		methods.add_meta_function(mlua::MetaMethod::Mul,|lua,(lhs,rhs):(mlua::Value,mlua::Value)|{
			match (lhs,rhs){
				(mlua::Value::UserData(lhs),mlua::Value::UserData(rhs))=>lhs.borrow_scoped(|Vector3(lhs):&Vector3|rhs.borrow_scoped(|Vector3(rhs):&Vector3|Self(lhs*rhs)))?,
				(lhs,mlua::Value::UserData(rhs))=>{
					let lhs=Number::from_lua(lhs,lua)?;
					rhs.borrow_scoped(|Vector3(rhs):&Vector3|Self(lhs.to_f32()*rhs))
				},
				(mlua::Value::UserData(lhs),rhs)=>{
					let rhs=Number::from_lua(rhs,lua)?;
					lhs.borrow_scoped(|Vector3(lhs):&Vector3|Self(lhs*rhs.to_f32()))
				},
				_=>Err(mlua::Error::runtime(format!("Expected Vector3")))
			}
		});
		methods.add_meta_function(mlua::MetaMethod::Div,|_,(Vector3(this),val):(Self,mlua::Value)|{
			match val{
				mlua::Value::Integer(n)=>Ok(Self(this/(n as f32))),
				mlua::Value::Number(n)=>Ok(Self(this/(n as f32))),
				mlua::Value::UserData(ud)=>ud.borrow_scoped(|Vector3(rhs):&Vector3|Self(this/rhs)),
				other=>Err(mlua::Error::runtime(format!("Attempt to divide Vector3 by {other:?}"))),
			}
		});
		methods.add_meta_function(mlua::MetaMethod::ToString,|_,Vector3(this):Self|
			Ok(format!("Vector3.new({},{},{})",
				this.x,
				this.y,
				this.z,
			))
		);
	}
}

type_from_lua_userdata!(Vector3);
