use std::ops::Deref;

use mlua::{AnyUserData, LuaSerdeExt, UserData, UserDataFields};
use yazi_shim::mlua::{SER_OPT, UserDataFieldsExt};

use super::{Lives, PtrCell};
use crate::lives::{Behavior, TaskSnap};

pub(super) struct Tasks {
	inner: PtrCell<yazi_core::tasks::Tasks>,
}

impl Deref for Tasks {
	type Target = yazi_core::tasks::Tasks;

	fn deref(&self) -> &Self::Target { &self.inner }
}

impl Tasks {
	pub(super) fn make(inner: &yazi_core::tasks::Tasks) -> mlua::Result<AnyUserData> {
		Lives::scoped_userdata(Self { inner: inner.into() })
	}
}

impl UserData for Tasks {
	fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
		fields.add_field_method_get("cursor", |_, me| Ok(me.cursor));

		fields.add_static_field("behavior", |_, me| Behavior::make(&me.scheduler.behavior));

		fields.add_static_field("snaps", |lua, me| {
			let tbl = lua.create_table_with_capacity(me.snaps.len(), 0)?;
			for snap in &me.snaps {
				tbl.raw_push(TaskSnap::make(snap)?)?;
			}
			Ok(tbl)
		});

		fields.add_cached_field("summary", |lua, me| lua.to_value_with(&me.summary, SER_OPT));
	}
}
