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
use crate::FileSource;
use crate::{
    util::accumulate_child_keys, ConfigurationBuilder, ConfigurationPath, ConfigurationProvider,
    ConfigurationSource, LoadError, LoadResult, Value
};
use configparser::ini::Ini;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use tokens::{ChangeToken, FileChangeToken, SharedChangeToken, SingleChangeToken, Subscription};

struct InnerProvider {
    file: FileSource,
    data: RwLock<HashMap<String, (String, Value)>>,
    token: RwLock<SharedChangeToken<SingleChangeToken>>,
}

impl InnerProvider {
    fn new(file: FileSource) -> Self {
        Self {
            file,
            data: RwLock::new(HashMap::with_capacity(0)),
            token: Default::default(),
        }
    }

    fn get(&self, key: &str) -> Option<Value> {
        self.data
            .read()
            .unwrap()
            .get(&key.to_uppercase())
            .map(|t| t.1.clone())
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        Box::new(self.token.read().unwrap().clone())
    }

    fn load(&self, reload: bool) -> LoadResult {
        if !self.file.path.is_file() {
            if self.file.optional || reload {
                let mut data = self.data.write().unwrap();
                if !data.is_empty() {
                    *data = HashMap::with_capacity(0);
                }

                return Ok(());
            } else {
                return Err(LoadError::File {
                    message: format!(
                        "The configuration file '{}' was not found and is not optional.",
                        self.file.path.display()
                    ),
                    path: self.file.path.clone(),
                });
            }
        }

        let mut ini = Ini::new_cs();
        let data = if let Ok(sections) = ini.load(&self.file.path) {
            let capacity = sections.iter().map(|p| p.1.len()).sum();
            let mut map = HashMap::with_capacity(capacity);

            for (section, pairs) in sections {
                for (key, value) in pairs {
                    let mut new_key = section.to_owned();
                    let new_value = value.unwrap_or_default();

                    new_key.push_str(ConfigurationPath::key_delimiter());
                    new_key.push_str(&key);
                    map.insert(new_key.to_uppercase(), (new_key, new_value.into()));
                }
            }

            map
        } else {
            HashMap::with_capacity(0)
        };

        *self.data.write().unwrap() = data;

        let previous = std::mem::replace(
            &mut *self.token.write().unwrap(),
            SharedChangeToken::default(),
        );

        previous.notify();
        Ok(())
    }

    fn child_keys(&self, earlier_keys: &mut Vec<String>, parent_path: Option<&str>) {
        let data = self.data.read().unwrap();
        accumulate_child_keys(&data, earlier_keys, parent_path)
    }
}

/// Represents a [`ConfigurationProvider`](crate::ConfigurationProvider) for `*.ini` files.
pub struct IniConfigurationProvider {
    inner: Arc<InnerProvider>,
    _subscription: Option<Box<dyn Subscription>>,
}

impl IniConfigurationProvider {
    /// Initializes a new `*.ini` file configuration provider.
    ///
    /// # Arguments
    ///
    /// * `file` - The `*.ini` [`FileSource`](crate::FileSource) information
    pub fn new(file: FileSource) -> Self {
        let path = file.path.clone();
        let inner = Arc::new(InnerProvider::new(file));
        let subscription: Option<Box<dyn Subscription>> = if inner.file.reload_on_change {
            Some(Box::new(tokens::on_change(
                move || FileChangeToken::new(path.clone()),
                |state| {
                    let provider = state.unwrap();
                    std::thread::sleep(provider.file.reload_delay);
                    provider.load(true).ok();
                },
                Some(inner.clone()),
            )))
        } else {
            None
        };

        Self {
            inner,
            _subscription: subscription,
        }
    }
}

impl ConfigurationProvider for IniConfigurationProvider {
    fn get(&self, key: &str) -> Option<Value> {
        self.inner.get(key)
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        self.inner.reload_token()
    }

    fn load(&mut self) -> LoadResult {
        self.inner.load(false)
    }

    fn child_keys(&self, earlier_keys: &mut Vec<String>, parent_path: Option<&str>) {
        self.inner.child_keys(earlier_keys, parent_path)
    }
}

/// Represents a [`ConfigurationSource`](crate::ConfigurationSource) for `*.ini` files.
pub struct IniConfigurationSource {
    file: FileSource,
}

impl IniConfigurationSource {
    /// Initializes a new `*.ini` file configuration source.
    ///
    /// # Arguments
    ///
    /// * `file` - The `*.ini` [`FileSource`](crate::FileSource) information
    pub fn new(file: FileSource) -> Self {
        Self { file }
    }
}

impl ConfigurationSource for IniConfigurationSource {
    fn build(&self, _builder: &dyn ConfigurationBuilder) -> Box<dyn ConfigurationProvider> {
        Box::new(IniConfigurationProvider::new(self.file.clone()))
    }
}

pub mod ext {

    use super::*;

    /// Defines extension methods for [`ConfigurationBuilder`](crate::ConfigurationBuilder).
    pub trait IniConfigurationExtensions {
        /// Adds an `*.ini` file as a configuration source.
        ///
        /// # Arguments
        ///
        /// * `file` - The `*.ini` [`FileSource`](crate::FileSource) information
        fn add_ini_file<T: Into<FileSource>>(&mut self, file: T) -> &mut Self;
    }

    impl IniConfigurationExtensions for dyn ConfigurationBuilder {
        fn add_ini_file<T: Into<FileSource>>(&mut self, file: T) -> &mut Self {
            self.add(Box::new(IniConfigurationSource::new(file.into())));
            self
        }
    }

    impl<T: ConfigurationBuilder> IniConfigurationExtensions for T {
        fn add_ini_file<F: Into<FileSource>>(&mut self, file: F) -> &mut Self {
            self.add(Box::new(IniConfigurationSource::new(file.into())));
            self
        }
    }
}