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
#[cfg(feature = "filesystem")]
use crate::package::FsPackage;
use crate::package::{CorePackage, Package, RawPackage};
use crate::LoadingConfig;
use melodium_common::descriptor::{
    Collection, Context, Entry, Function, Identifier, Loader as LoaderTrait, LoadingError, Model,
    Treatment,
};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, RwLock, RwLockReadGuard};

/**
 * Manages loading of Mélodium packages.
 */
#[derive(Debug)]
pub struct Loader {
    collection: RwLock<Collection>,
    packages: RwLock<HashMap<String, Box<dyn Package>>>,
    search_locations: Vec<PathBuf>,
}

impl Loader {
    pub fn new(config: LoadingConfig) -> Self {
        Self {
            collection: RwLock::new(Collection::new()),
            packages: RwLock::new(
                config
                    .core_packages
                    .into_iter()
                    .map(|p| {
                        (
                            p.name().to_string(),
                            Box::new(CorePackage::new(p)) as Box<dyn Package>,
                        )
                    })
                    .collect(),
            ),
            search_locations: config.search_locations,
        }
    }

    pub fn load_package(&self, name: &str) -> Result<(), LoadingError> {
        if !self.packages.read().unwrap().contains_key(name) {
            for location in &self.search_locations {
                let mut path = location.clone();
                path.push(name);
                if path.exists() {
                    #[cfg(feature = "filesystem")]
                    if let Ok(package) = FsPackage::new(&path) {
                        for req in package.requirements() {
                            self.load_package(req)?;
                        }
                        self.packages
                            .write()
                            .unwrap()
                            .insert(name.to_string(), Box::new(package));
                        return Ok(());
                    }
                }
            }
            Err(LoadingError::NoPackage)
        } else {
            Ok(())
        }
    }

    pub fn load_raw(&self, raw_content: &str) -> Result<String, LoadingError> {
        let package = RawPackage::new(raw_content)?;
        let name = package.name().to_string();

        self.packages
            .write()
            .unwrap()
            .insert(package.name().to_string(), Box::new(package));

        Ok(name)
    }

    pub fn load(&self, identifier: &Identifier) -> Result<Collection, LoadingError> {
        self.get_with_load(identifier)?;
        Ok(self.collection.read().unwrap().clone())
    }

    pub fn full_load(&self) -> Result<Collection, LoadingError> {
        for (_name, package) in self.packages.read().unwrap().iter() {
            let additions = package.full_collection(self)?;
            self.add_collection(additions);
        }
        Ok(self.collection.read().unwrap().clone())
    }

    pub fn build(&self) -> Result<Arc<Collection>, LoadingError> {
        let collection = Arc::new(self.collection.read().unwrap().clone());

        for (_name, package) in self.packages.read().unwrap().iter() {
            package.make_building(&collection)?;
        }

        Ok(collection)
    }

    pub fn collection(&self) -> RwLockReadGuard<Collection> {
        self.collection.read().unwrap()
    }

    pub fn get_with_load(&self, identifier: &Identifier) -> Result<Entry, LoadingError> {
        let entry = self.collection.read().unwrap().get(identifier).cloned();
        if let Some(entry) = entry {
            Ok(entry)
        } else if let Some(package) = self.packages.read().unwrap().get(identifier.root()) {
            let additions = package.element(self, identifier)?;
            self.add_collection(additions);

            Ok(self
                .collection
                .read()
                .unwrap()
                .get(identifier)
                .unwrap()
                .clone())
        } else {
            Err(LoadingError::NoPackage)
        }
    }

    fn add_collection(&self, other_collection: Collection) {
        let existing = self.collection.read().unwrap().identifiers();
        let mut others = other_collection.identifiers();

        others.retain(|id| !existing.contains(id));

        if !others.is_empty() {
            let mut collection = self.collection.write().unwrap();
            for id in &others {
                collection.insert(other_collection.get(id).unwrap().clone());
            }
        }
    }
}

impl LoaderTrait for Loader {
    fn load_context(&self, identifier: &Identifier) -> Result<Arc<dyn Context>, LoadingError> {
        match self.get_with_load(identifier)? {
            Entry::Context(context) => Ok(context),
            _ => Err(LoadingError::ContextExpected),
        }
    }

    fn load_function(&self, identifier: &Identifier) -> Result<Arc<dyn Function>, LoadingError> {
        match self.get_with_load(identifier)? {
            Entry::Function(function) => Ok(function),
            _ => Err(LoadingError::FunctionExpected),
        }
    }

    fn load_model(&self, identifier: &Identifier) -> Result<Arc<dyn Model>, LoadingError> {
        match self.get_with_load(identifier)? {
            Entry::Model(model) => Ok(model),
            _ => Err(LoadingError::ModelExpected),
        }
    }

    fn load_treatment(&self, identifier: &Identifier) -> Result<Arc<dyn Treatment>, LoadingError> {
        match self.get_with_load(identifier)? {
            Entry::Treatment(treatment) => Ok(treatment),
            _ => Err(LoadingError::TreatmentExpected),
        }
    }
}