CGGItemSets/src/data_source.rs
nyyu d854da599f
All checks were successful
continuous-integration/drone/push Build is passing
ms: improve
2021-10-31 10:12:53 +01:00

141 lines
3.5 KiB
Rust

use crate::ChampInfo;
use crate::Champion;
use indexmap::IndexMap;
use log::{error, info};
use serde_derive::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::fs;
use std::path::Path;
#[derive(Serialize, Deserialize)]
struct ItemSet {
title: String,
#[serde(rename = "type")]
type_: String,
map: String,
mode: String,
priority: bool,
sortrank: u32,
blocks: Vec<Value>,
}
#[derive(Serialize, Deserialize)]
pub struct Build {
#[serde(rename = "type")]
pub type_: String,
pub items: Vec<Item>,
}
#[derive(Serialize, Deserialize)]
pub struct Item {
pub id: String,
pub count: u8,
}
pub struct Stat {
pub win_rate: f64,
pub games: u32,
pub kda: f64,
pub patch: String,
}
pub trait DataSource {
fn get_alias(&self) -> &str;
fn get_timeout(&self) -> u64;
fn get_champs_with_positions(
&self,
client: &ureq::Agent,
champion: &Champion,
) -> IndexMap<u32, Vec<String>>;
fn make_item_set(&self, items: Vec<&str>, label: String) -> Value {
json!({
"items": items.iter().map(|x| json!({"id": x.to_string(), "count": 1})).collect::<Vec<Value>>(),
"type": label
})
}
fn get_champ_data_with_win_pourcentage(
&self,
champ: &ChampInfo,
positions: &[String],
client: &ureq::Agent,
) -> Vec<(String, Vec<Value>, Stat)>;
fn write_item_set(
&self,
champ: &ChampInfo,
positions: &[String],
path: &Path,
client: &ureq::Agent,
) {
info!(
"{}: Retrieving data for {} at {}",
self.get_alias(),
champ.name,
positions.join(", ")
);
let data = self.get_champ_data_with_win_pourcentage(champ, positions, client);
let mut missing_roles = vec![];
for pos in positions {
let mut ok = false;
for build in &data {
if build.0 == *pos {
ok = true;
break;
}
}
if !ok {
missing_roles.push(pos.to_owned());
}
}
if !missing_roles.is_empty() {
error!(
"{}: Can't get data for {} at {}",
self.get_alias(),
champ.id,
missing_roles.join(", ")
);
}
for build in data {
let item_set = ItemSet {
title: format!(
"{} {} {} - {:.2}% wins - {} games - {:.2} kda",
self.get_alias(),
build.0,
build.2.patch,
build.2.win_rate,
build.2.games,
build.2.kda
),
type_: "custom".to_string(),
map: "any".to_string(),
mode: "any".to_string(),
priority: false,
sortrank: 0,
blocks: build.1,
};
info!(
"{}: Writing item set for {} at {}",
self.get_alias(),
champ.name,
build.0
);
fs::write(
path.join(format!(
"{}_{}_{}.json",
self.get_alias(),
champ.id,
build.0
)),
serde_json::to_string_pretty(&item_set).unwrap(),
)
.unwrap();
}
}
}