stat_summoner/module/championsinfos/
utils.rs

1use mongodb::Collection;
2use poise::serenity_prelude::{CreateEmbed, CreateEmbedFooter};
3use serde_json::Value;
4
5use crate::models::data::{ChampionData, EmojiId};
6use crate::models::error::Error;
7use crate::utils::get_emoji;
8
9/// ⚙️ Constructs a Discord embed containing detailed information about a League of Legends champion.
10///
11/// This function takes the champion's data and a collection of emojis to create a richly formatted Discord embed.
12/// It includes the champion's roles, winrate, banrate, popularity, recommended runes (with emojis), and core item build (with emojis).
13/// The embed is designed to provide users with an at-a-glance overview of the champion's statistics and recommended setups.
14///
15/// # Parameters:
16/// - `champion_data`: A `ChampionData` struct containing the champion's information, including roles, runes, items, and statistics.
17/// - `collection_emoji`: A reference to a MongoDB `Collection<EmojiId>` used to retrieve the appropriate emojis for runes and items.
18///
19/// # Returns:
20/// - `Result<CreateEmbed, Error>`: On success, returns a `CreateEmbed` object representing the Discord embed.
21///   On failure, returns an `Error` detailing what went wrong.
22///
23/// # ⚠️ Notes:
24/// - The function retrieves emojis asynchronously for each rune and item using the `get_emoji` function.
25/// - It formats numerical statistics (winrate, banrate, popularity) as percentages.
26/// - The embed includes a thumbnail image of the champion, fetched from the Data Dragon API.
27/// - The embed includes a footer indicating that the message will be deleted after 60 seconds.
28///
29/// # Example:
30/// ```rust
31/// let champion_data = /* Fetch or construct ChampionData */;
32/// let embed = create_embed_champions_info(champion_data, &collection_emoji).await?;
33/// ctx.send(|m| m.set_embed(embed)).await?;
34/// ```
35///
36/// This function produces an embed displaying information such as:
37/// ```text
38/// 📝 Informations sur Jhin
39/// Rôles: AD Carry
40/// Winrate: 51.74%   Banrate: 17.61%   Popularité: 27.57%
41///
42/// Runes:
43/// **Rune principale :** <FleetFootwork Emoji>
44/// <PresenceOfMind Emoji> <LegendBloodline Emoji> <CoupDeGrace Emoji>
45///
46/// **Runes secondaires:**
47/// <Celerity Emoji> <GatheringStorm Emoji>
48///
49/// **Fragments:** <AdaptiveForce Emoji> <AdaptiveForce Emoji> <HealthScale Emoji>
50///
51/// Build d'objets:
52/// <StatikkShiv Emoji> <RapidFirecannon Emoji> <InfinityEdge Emoji>
53/// ```
54///
55/// # Errors:
56/// - If any of the asynchronous calls to `get_emoji` fail, the function returns an `Error`.
57/// - If there is an issue parsing the numerical statistics from the `champion_data`.
58///
59/// # See Also:
60/// - `get_emoji`: Retrieves the emoji string corresponding to a given rune or item name.
61/// - `championsinfos`: The command that invokes this function to display the champion's information.
62///
63/// # Related Structures:
64/// - `ChampionData`: Contains the champion's details used to construct the embed.
65/// - `EmojiId`: Represents the mapping of rune or item names to their corresponding emoji IDs.
66///
67/// # Dependencies:
68/// - This function relies on external data sources such as the Data Dragon API for champion images.
69/// - It also depends on the MongoDB collection for retrieving emojis.
70pub async fn create_embed_champions_info(
71    champion_data: ChampionData,
72    collection_emoji: &Collection<EmojiId>,
73) -> Result<CreateEmbed, Error> {
74    let primary_rune_emoji = get_emoji(
75        collection_emoji.clone(),
76        "rune",
77        &champion_data.runes.parent_primary_rune,
78    )
79    .await?;
80
81    let child_primary_rune_1_emoji = get_emoji(
82        collection_emoji.clone(),
83        "rune",
84        &champion_data.runes.child_primary_rune_1,
85    )
86    .await?;
87
88    let child_primary_rune_2_emoji = get_emoji(
89        collection_emoji.clone(),
90        "rune",
91        &champion_data.runes.child_primary_rune_2,
92    )
93    .await?;
94
95    let child_primary_rune_3_emoji = get_emoji(
96        collection_emoji.clone(),
97        "rune",
98        &champion_data.runes.child_primary_rune_3,
99    )
100    .await?;
101
102    let child_secondary_rune_1_emoji = get_emoji(
103        collection_emoji.clone(),
104        "rune",
105        &champion_data.runes.child_secondary_rune_1,
106    )
107    .await?;
108
109    let child_secondary_rune_2_emoji = get_emoji(
110        collection_emoji.clone(),
111        "rune",
112        &champion_data.runes.child_secondary_rune_2,
113    )
114    .await?;
115
116    // Récupérer les émojis pour les runes tertiaires
117    let tertiary_rune_1_emoji = get_emoji(
118        collection_emoji.clone(),
119        "rune",
120        &champion_data.runes.tertiary_rune_1,
121    )
122    .await?;
123
124    let tertiary_rune_2_emoji = get_emoji(
125        collection_emoji.clone(),
126        "rune",
127        &champion_data.runes.tertiary_rune_2,
128    )
129    .await?;
130
131    let tertiary_rune_3_emoji = get_emoji(
132        collection_emoji.clone(),
133        "rune",
134        &champion_data.runes.tertiary_rune_3,
135    )
136    .await?;
137
138    // Récupérer les émojis pour les objets du build
139    let core_item_1_emoji = get_emoji(
140        collection_emoji.clone(),
141        "item",
142        &champion_data.core_build.first,
143    )
144    .await?;
145
146    let core_item_2_emoji = get_emoji(
147        collection_emoji.clone(),
148        "item",
149        &champion_data.core_build.second,
150    )
151    .await?;
152
153    let core_item_3_emoji = get_emoji(
154        collection_emoji.clone(),
155        "item",
156        &champion_data.core_build.third,
157    )
158    .await?;
159
160    let popularity = champion_data.popularity.parse::<f64>().unwrap_or(0.0) * 100.0;
161    let winrate = champion_data.winrate.parse::<f64>().unwrap_or(0.0) * 100.0;
162    let banrate = champion_data.banrate.parse::<f64>().unwrap_or(0.0) * 100.0;
163
164    let runes_description = format!(
165        "**Primary Rune:** {}\n{} {} {}\n\n**Secondary Runes:** \n{} {}\n\n**Shards:** {} {} {}",
166        primary_rune_emoji,
167        child_primary_rune_1_emoji,
168        child_primary_rune_2_emoji,
169        child_primary_rune_3_emoji,
170        child_secondary_rune_1_emoji,
171        child_secondary_rune_2_emoji,
172        tertiary_rune_1_emoji,
173        tertiary_rune_2_emoji,
174        tertiary_rune_3_emoji
175    );
176
177    let core_build_description = format!(
178        "{} {} {}",
179        core_item_1_emoji, core_item_2_emoji, core_item_3_emoji
180    );
181    let version_json: Value = reqwest::get("https://ddragon.leagueoflegends.com/api/versions.json")
182        .await?
183        .json()
184        .await?;
185    let version = version_json[0].as_str().unwrap();
186    let embed = CreateEmbed::default()
187        .title(format!("Informations about {}", champion_data.name))
188        .color(0x00ff00)
189        .field("Role", champion_data.role.join(", "), false)
190        .field("Winrate", format!("{:.2}%", winrate), true)
191        .field("Banrate", format!("{:.2}%", banrate), true)
192        .field("Popularity", format!("{:.2}%", popularity), true)
193        .field("Runes", runes_description, false)
194        .field("Build", core_build_description, false)
195        .footer(CreateEmbedFooter::new(
196            "This message will be deleted in 60 seconds.",
197        ))
198        .thumbnail(format!(
199            "https://ddragon.leagueoflegends.com/cdn/{}/img/champion/{}.png",
200            version, champion_data.id_name
201        ));
202
203    Ok(embed)
204}