use ndk::android::{hardware_buffer::AHardwareBuffer_Format, window::*};

#[repr(transparent)]
#[derive(Debug, PartialEq)]
pub struct Window {
	inner: *const ANativeWindow,
}
impl Clone for Window {
	fn clone(&self) -> Self {
		unsafe { ANativeWindow_acquire(self.inner as _) };
		Self { inner: self.inner }
	}
}
impl Drop for Window {
	fn drop(&mut self) {
		unsafe { ANativeWindow_release(self.inner as _) }
	}
}
impl Window {
	pub fn from_raw(inner: *const ANativeWindow) -> Option<Self> {
		if inner.is_null() {
			return None;
		} else {
			unsafe { ANativeWindow_acquire(inner as _) };
			Self { inner }.into()
		}
	}
	pub fn from_java(env: *mut jni::JNIEnv, surface: jni::jobject) -> Option<Self> {
		let inner = unsafe { ANativeWindow_fromSurface(env, surface) };
		Self::from_raw(inner)
	}
	pub fn as_sys(&self) -> *const ANativeWindow {
		self.inner
	}
	pub fn to_surface(&self, env: *mut jni::JNIEnv) -> jni::jobject {
		unsafe { ANativeWindow_toSurface(env, self.inner as _) }
	}
	pub fn width(&self) -> i32 {
		unsafe { ANativeWindow_getWidth(self.inner as _) }
	}
	pub fn height(&self) -> i32 {
		unsafe { ANativeWindow_getHeight(self.inner as _) }
	}
	pub fn format(&self) -> AHardwareBuffer_Format {
		unsafe { ANativeWindow_getFormat(self.inner as _) as _ }
	}
	pub fn set_geometry(&self, width: i32, height: i32, format: AHardwareBuffer_Format) -> Result<(), i32> {
		let ret = unsafe { ANativeWindow_setBuffersGeometry(self.inner as _, width, height, format as _) };
		if ret == 0 {
			Ok(())
		} else {
			Err(ret)
		}
	}
	// TODO version check
	// pub fn set_frame_rate(&self, frame_rate: f32, compatibility: i8) -> Result<(), i32> {
	// 	let ret = unsafe { ANativeWindow_setFrameRate(self.inner as _, frame_rate, compatibility) };
	// 	if ret == 0 {
	// 		Ok(())
	// 	} else {
	// 		Err(ret)
	// 	}
	// }
}
