use super::page::{Page, PageTemplate}; use crate::app::AppConfig; use crate::static_files::StaticFilesManager; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebSiteBuilder { root_page: Page, #[serde(default = "Vec::new")] assets_index: Vec<String>, templates: Vec<PageTemplate>, } #[derive(Debug, Clone)] pub struct WebSite { root_page: Page, pub static_files_manager: StaticFilesManager, templates: Vec<PageTemplate>, } impl WebSiteBuilder { pub fn from_json(json: &str) -> Self { serde_json::from_str(json).unwrap() } pub fn with_static_files_manager( &mut self, static_files_manager: StaticFilesManager, ) -> WebSite { WebSite { root_page: self.root_page.clone(), static_files_manager: { let mut static_files_manager = static_files_manager; static_files_manager.add_pathes(&self.assets_index); static_files_manager }, templates: self.templates.clone(), } } #[cfg(test)] pub fn testing(test_dir: &PathBuf) -> WebSite { Self::from_json(crate::testing::TEST_JSON_WEBSITE) .with_static_files_manager(StaticFilesManager::testing_new(test_dir).unwrap()) } pub fn load(config: &AppConfig) -> WebSiteBuilder { let file_path = match &config.load { None => std::env::current_dir() .unwrap() .join("templates") .join("new_website.json"), Some(pth) => pth.clone(), }; WebSiteBuilder::from_json(&std::fs::read_to_string(file_path).unwrap()) } } impl WebSite { pub fn build(&mut self) -> Result<Self, String> { if let Err(err) = self.root_page.build( &self.templates, PathBuf::from("/"), &self.static_files_manager, ) { return Err(err); }; Ok(self.clone()) } }