1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
pub mod dossier_configuration_style;
pub mod dossier_configuration_compilation;
pub mod dossier_configuration_path_reference;
pub mod dossier_configuration_path_reference_manager;
pub mod dossier_configuration_table_of_contents;
pub mod dossier_configuration_bibliography;

use std::collections::HashMap;
use std::io;
use std::path::PathBuf;

use dossier_configuration_bibliography::DossierConfigurationBibliography;
use dossier_configuration_table_of_contents::DossierConfigurationTableOfContents;
use getset::{Getters, Setters};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
use log;

use crate::constants::{DOSSIER_CONFIGURATION_JSON_FILE_NAME, DOSSIER_CONFIGURATION_YAML_FILE_NAME, NMD_EXTENSION};
use crate::resource::text_reference::TextReferenceMap;
use crate::resource::Resource;
use crate::resource::{disk_resource::DiskResource, ResourceError};
use crate::utility::file_utility;

use self::dossier_configuration_path_reference::{DossierConfigurationPathReference, DossierConfigurationRawPathReference};
use self::dossier_configuration_path_reference_manager::DOSSIER_CONFIGURATION_RAW_REFERENCE_MANAGER;
use self::{dossier_configuration_compilation::DossierConfigurationCompilation, dossier_configuration_style::DossierConfigurationStyle};



#[derive(Debug, Clone, Deserialize, Serialize, Getters, Setters)]
pub struct DossierConfiguration {
    #[serde(default = "default_name")]
    #[getset(get = "pub", set = "pub")]
    name: String,

    #[serde(rename(serialize = "toc", deserialize = "toc"), default = "default_toc")]
    table_of_contents_configuration: DossierConfigurationTableOfContents,

    #[serde(rename = "documents")]
    raw_documents_paths: Vec<DossierConfigurationRawPathReference>,

    #[serde(default = "default_style")]
    style: DossierConfigurationStyle,

    #[serde(default = "default_references")]
    references: TextReferenceMap,

    #[serde(default = "default_bibliography")]
    bibliography: DossierConfigurationBibliography,

    #[serde(default = "default_compilation")]
    compilation: DossierConfigurationCompilation,
}

fn default_name() -> String {
    "new-dossier".to_string()
}

fn default_style() -> DossierConfigurationStyle {
    DossierConfigurationStyle::default()
}

fn default_references() -> TextReferenceMap {
    HashMap::new()
}

fn default_compilation() -> DossierConfigurationCompilation {
    DossierConfigurationCompilation::default()
}

fn default_toc() -> DossierConfigurationTableOfContents {
    DossierConfigurationTableOfContents::default()
}

fn default_bibliography() -> DossierConfigurationBibliography {
    DossierConfigurationBibliography::default()
}


#[allow(dead_code)]
impl DossierConfiguration {

    pub fn new(root_path: PathBuf, name: String, toc: DossierConfigurationTableOfContents, raw_documents_paths: Vec<String>, style: DossierConfigurationStyle, references: TextReferenceMap, compilation: DossierConfigurationCompilation, bibliography: DossierConfigurationBibliography) -> Self {
        
        DOSSIER_CONFIGURATION_RAW_REFERENCE_MANAGER.lock().unwrap().set_root_path(root_path);
        
        Self {
            name,
            table_of_contents_configuration: toc,
            raw_documents_paths,
            style,
            references,
            compilation,
            bibliography
        }
    }

    pub fn raw_documents_paths(&self) -> &Vec<String> {
        &self.raw_documents_paths
    }

    pub fn documents_paths(&self) -> Vec<DossierConfigurationPathReference> {

        let dcrfm = DOSSIER_CONFIGURATION_RAW_REFERENCE_MANAGER.lock().unwrap();

        if self.compilation.parallelization() {

            return self.raw_documents_paths.par_iter().map(|raw_reference| {
                dcrfm.parse_raw_reference(raw_reference, None)
            }).collect()

        } else {

            return self.raw_documents_paths.iter().map(|raw_reference| {
                dcrfm.parse_raw_reference(raw_reference, None)
            }).collect()
        }
    }

    pub fn set_raw_documents_paths(&mut self, documents: Vec<String>) -> () {
        self.raw_documents_paths = documents
    }

    pub fn append_raw_document_path(&mut self, raw_document_path: String) -> () {
        self.raw_documents_paths.push(raw_document_path)
    }

    pub fn style(&self) -> &DossierConfigurationStyle {
        &self.style
    }

    pub fn compilation(&self) -> &DossierConfigurationCompilation {
        &self.compilation
    }

    pub fn references(&self) -> &TextReferenceMap {
        &self.references
    }

    pub fn bibliography(&self) -> &DossierConfigurationBibliography {
        &self.bibliography
    }

    pub fn table_of_contents_configuration(&self) -> &DossierConfigurationTableOfContents {
        &self.table_of_contents_configuration
    }

    pub fn set_root_path(&mut self, root_path: PathBuf) {
        DOSSIER_CONFIGURATION_RAW_REFERENCE_MANAGER.lock().unwrap().set_root_path(root_path);
    }

    pub fn dump_as_yaml(&self, complete_output_path: PathBuf) -> Result<(), ResourceError> {
        let yaml_string = serde_yaml::to_string(&self).unwrap();

        let mut disk_resource = DiskResource::try_from(complete_output_path)?;

        disk_resource.erase()?;

        log::debug!("dump dossier configuration:\n{:#?}\n", self);
        disk_resource.write(&yaml_string)?;

        Ok(())
    }

    pub fn with_files_in_dir(mut self, dir_path: &PathBuf) -> Result<Self, io::Error> {
        let files = file_utility::all_files_in_dir(dir_path, &vec![NMD_EXTENSION.to_string()])?;

        self.raw_documents_paths = files.iter().map(|f| f.to_string_lossy().to_string()).collect();

        Ok(self)
    }
}

impl Default for DossierConfiguration {
    fn default() -> Self {
        Self {
            name: String::from("New Dossier"),
            raw_documents_paths: vec![],
            style: DossierConfigurationStyle::default(),
            references: HashMap::new(),
            compilation: DossierConfigurationCompilation::default(),
            table_of_contents_configuration: DossierConfigurationTableOfContents::default(),
            bibliography: DossierConfigurationBibliography::default()
        }
    }
}


impl DossierConfiguration {
    fn try_from_as_yaml(content: String) -> Result<Self, ResourceError> {

        log::info!("try to load dossier configuration from yaml content...");
        
        match serde_yaml::from_str(&content) {
            Ok(config) => {
                log::info!("dossier configuration loaded from yaml");
                return Ok(config)
            },
            Err(e) => return Err(ResourceError::InvalidResourceVerbose(e.to_string()))
        }
    }

    fn try_from_as_json(content: String) -> Result<Self, ResourceError> {

        log::info!("try to load dossier configuration from json content...");

        match serde_json::from_str(&content) {
            Ok(config) => {
                log::info!("dossier configuration loaded from json");
                return Ok(config)
            },
            Err(e) => return Err(ResourceError::InvalidResourceVerbose(e.to_string()))
        }
    }

    pub fn load(path_buf: &PathBuf) -> Result<Self, ResourceError> {
        Self::try_from(path_buf)
    }
}

impl TryFrom<&PathBuf> for DossierConfiguration {
    type Error = ResourceError;

    fn try_from(path_buf: &PathBuf) -> Result<Self, Self::Error> {

        if path_buf.is_file() {
            if let Some(file_name) = path_buf.file_name() {

                let file_content = file_utility::read_file_content(path_buf)?;

                if file_name.to_string_lossy().eq(DOSSIER_CONFIGURATION_YAML_FILE_NAME) {

                    log::info!("{} found", DOSSIER_CONFIGURATION_YAML_FILE_NAME);

                    let mut config = Self::try_from_as_yaml(file_content)?;

                    config.set_root_path(path_buf.clone());

                    return Ok(config)
                }

                if file_name.to_string_lossy().eq(DOSSIER_CONFIGURATION_JSON_FILE_NAME) {

                    log::info!("{} found", DOSSIER_CONFIGURATION_JSON_FILE_NAME);

                    let mut config = Self::try_from_as_json(file_content)?;

                    config.set_root_path(path_buf.clone());

                    return Ok(config)
                }
            }
        }

        if path_buf.is_dir() {

            let yaml_path_buf = path_buf.join(DOSSIER_CONFIGURATION_YAML_FILE_NAME);

            if yaml_path_buf.exists() {

                let file_content = file_utility::read_file_content(&yaml_path_buf)?;

                let mut config = Self::try_from_as_yaml(file_content)?;

                config.set_root_path(path_buf.clone());

                return Ok(config)
            }

            let json_path_buf = path_buf.join(DOSSIER_CONFIGURATION_JSON_FILE_NAME);

            if json_path_buf.exists() {
                
                let file_content = file_utility::read_file_content(&json_path_buf)?;
                
                let mut config = Self::try_from_as_json(file_content)?;

                config.set_root_path(path_buf.clone());

                return Ok(config)
            }
        }

        Err(ResourceError::ResourceNotFound("dossier configuration".to_string()))
    }
}


#[cfg(test)]
mod test {
    use std::path::PathBuf;
    use super::*;


    #[test]
    fn apply_root_path() {
        let project_directory = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let dossier_dir = "nmd-test-dossier-1";
        let nmd_dossier_path = project_directory.join("test-resources").join(dossier_dir);

        let configuration = DossierConfiguration::try_from(&nmd_dossier_path).unwrap();

        assert_eq!(configuration.documents_paths()[0], nmd_dossier_path.join("d1.nmd").to_string_lossy().to_string())
    }
}