use serde::Deserialize;

use super::{Character, ability::Ability};

#[derive(Debug, Deserialize)]
pub struct CommandRecipe {
	pub char: Vec<Character>,
	pub r#type: char,
	pub ingredients: (String, String),
	pub chance: u8,
	#[serde(skip_deserializing)]
	pub abilities: Vec<(String, Ability)>,
}

impl CommandRecipe {
	pub fn get_ability(&self, crystal: &str) -> Option<Ability> {
		if self.r#type == '-' {
			return None;
		}

		for ability in self.abilities.iter() {
			if ability.0 == crystal {
				return Some(ability.1.clone());
			}
		}

		// This should never happen unless the json files are wrong
		panic!(
			"No ability found for {} + {} and {}",
			self.ingredients.0, self.ingredients.1, crystal
		);
	}

	pub fn can_unlock(&self, char: Character) -> bool {
		self.char.contains(&char)
	}

	pub fn get_unlock_chars(&self) -> String {
		let mut id = String::new();
		if self.can_unlock(Character::Terra) {
			id += "T"
		}

		if self.can_unlock(Character::Ventus) {
			if !id.is_empty() {
				id += " ";
			}
			id += "V";
		}

		if self.can_unlock(Character::Aqua) {
			if !id.is_empty() {
				id += " ";
			}
			id += "A";
		}

		id
	}

	pub fn set_abilities(&mut self, abilities: &[Ability]) {
		let mut vec: Vec<(String, Ability)> = vec![];

		for ability in abilities.iter() {
			if ability.types.contains(&self.r#type) {
				vec.push((ability.from.clone(), ability.clone()));
			}
		}
		vec.sort();
		self.abilities = vec;
	}
}
