2024-10-10 16:58:50 +02:00
|
|
|
use std::{
|
|
|
|
fs::{self, File},
|
|
|
|
io::Write,
|
|
|
|
path::PathBuf,
|
|
|
|
};
|
|
|
|
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
|
|
|
use crate::{marble_engine::board::Board, userdata_dir};
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
|
|
pub struct Blueprint {
|
2024-10-11 23:38:35 +02:00
|
|
|
id: usize,
|
2024-10-10 16:58:50 +02:00
|
|
|
pub name: String,
|
|
|
|
pub board: String,
|
|
|
|
#[serde(skip, default)]
|
|
|
|
tile_board: Option<Board>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Blueprint {
|
2024-10-11 23:38:35 +02:00
|
|
|
pub fn new(content: &Board, id: usize) -> Self {
|
2024-10-10 16:58:50 +02:00
|
|
|
Self {
|
2024-10-11 23:38:35 +02:00
|
|
|
id,
|
|
|
|
name: format!("Blueprint {id}"),
|
2024-10-10 16:58:50 +02:00
|
|
|
board: content.to_string(),
|
|
|
|
tile_board: Some(content.clone()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-11 23:38:35 +02:00
|
|
|
pub fn id(&self) -> usize {
|
|
|
|
self.id
|
2024-10-11 21:22:56 +02:00
|
|
|
}
|
|
|
|
|
2024-10-10 16:58:50 +02:00
|
|
|
pub fn convert_board(&mut self) -> &Board {
|
|
|
|
if self.tile_board.is_none() {
|
|
|
|
self.tile_board = Some(Board::parse(&self.board));
|
|
|
|
}
|
|
|
|
self.tile_board.as_ref().unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_board(&self) -> Option<&Board> {
|
|
|
|
self.tile_board.as_ref()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn path(&self) -> PathBuf {
|
|
|
|
let dir = userdata_dir().join("blueprints");
|
|
|
|
fs::create_dir_all(&dir).unwrap();
|
2024-10-11 23:38:35 +02:00
|
|
|
dir.join(format!("blueprint_{}.json", &self.id))
|
2024-10-10 16:58:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn save(&self) {
|
|
|
|
let path = self.path();
|
|
|
|
let json = serde_json::to_string_pretty(self).unwrap();
|
|
|
|
let mut file = File::create(path).unwrap();
|
|
|
|
file.write_all(json.as_bytes()).unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn remove_file(&self) {
|
|
|
|
let path = self.path();
|
|
|
|
if let Err(e) = fs::remove_file(path) {
|
|
|
|
eprint!("Error removing blueprint file: {e}");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|