use hashbrown::HashMap;
use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::url::{Url, UrlCow};

use super::Ember;

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct EmberBulkRename<'a> {
	pub changes: HashMap<UrlCow<'a>, UrlCow<'a>>,
}

impl<'a> EmberBulkRename<'a> {
	pub fn borrowed<I>(changes: I) -> Ember<'a>
	where
		I: Iterator<Item = (Url<'a>, Url<'a>)>,
	{
		Self { changes: changes.map(|(from, to)| (from.into(), to.into())).collect() }.into()
	}
}

impl EmberBulkRename<'static> {
	pub fn owned<'a, I>(changes: I) -> Ember<'static>
	where
		I: Iterator<Item = (Url<'a>, Url<'a>)>,
	{
		Self {
			changes: changes.map(|(from, to)| (from.to_owned().into(), to.to_owned().into())).collect(),
		}
		.into()
	}
}

impl<'a> From<EmberBulkRename<'a>> for Ember<'a> {
	fn from(value: EmberBulkRename<'a>) -> Self { Self::BulkRename(value) }
}

impl IntoLua for EmberBulkRename<'_> {
	fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
		lua
			.create_table_from(
				self.changes.into_iter().map(|(from, to)| (from.into_owned(), to.into_owned())),
			)?
			.into_lua(lua)
	}
}
