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 { id: String, pub name: String, pub board: String, #[serde(skip, default)] tile_board: Option, } impl Blueprint { pub fn new(content: &Board, number: usize) -> Self { Self { id: format!("blueprint_{number}"), name: format!("Blueprint {number}"), board: content.to_string(), tile_board: Some(content.clone()), } } 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(); dir.join(format!("{}.json", &self.id)) } 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}"); } } }