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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use serde::{Deserialize, Serialize};
use std::{
    fs::{self, File},
    io::{BufReader, BufWriter, Write},
    path::{Path, PathBuf},
};

use crate::{
    Arguments, MyResult,
    WSError::{self, *},
    ENVIRON,
};

/// Configuration variables
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    /// Desktops: gnome, xfce, openbox, ...
    pub desktop: String,
    /// Minimum dimension
    pub min_dimension: u64,
    /// Maximum dimension
    pub max_dimension: u64,
    /// Minimum file size
    pub min_size: u64,
    /// Maximum file size
    pub max_size: u64,
    /// Directory containing image files
    pub dirs: Vec<PathBuf>,
    /// Image file extension (identify -list format)
    pub extensions: Vec<String>,
    /// Interval (in seconds) between each wallpaper displayed
    pub interval: u64,
    /// Set the number of monitors.
    pub monitor: u8,
    /// Sort the images found.
    pub sort: bool,
    /// Show intermediate runtime messages.
    pub verbose: bool,
    /// Wallpaper file path used by gnome desktop
    pub wallpaper: PathBuf,
}

impl Default for Config {
    fn default() -> Self {
        // set image extensions
        // identify -list format
        let extensions: Vec<String> = ["avif", "jpg", "jpeg", "png", "svg", "tif", "webp"]
            .iter()
            .map(ToString::to_string)
            .collect();

        // interval: 30 * 60 = 1800 seconds (30 minutes)
        let interval: u64 = 30 * 60;

        // dimension.height >= min_dimension && dimension.width >= min_dimension
        let min_dimension: u64 = 600;

        // dimension.height <= max_dimension && dimension.width <= max_dimension
        let max_dimension: u64 = 128_000;

        Config {
            desktop: ENVIRON.desktop.to_string(),
            min_dimension,
            max_dimension,
            min_size: u64::pow(1024, 1), // 1024 ^ 1 = 1kb
            max_size: u64::pow(1024, 3), // 1024 ^ 3 = 1Gb
            dirs: get_dirs(),
            extensions,
            interval,
            monitor: 2,
            sort: false,
            verbose: false,
            wallpaper: get_wallpaper_path(),
        }
    }
}

// Set boundary config values
fn config_boundary() -> Config {
    Config {
        interval: 5,
        min_dimension: 10,
        min_size: 1,
        monitor: 1,
        ..Config::default()
    }
}

impl Config {
    /// Read command line arguments with priority order:
    ///
    /// 1. read config file || read default config
    /// 2. set_command_line_arguments
    /// 3. validate_config
    /// 4. write_config_file
    ///
    /// At the end add or update config file.
    pub fn new() -> MyResult<Self> {
        let mut read_default_config = false;
        let config_path: PathBuf = get_config_path()?;

        let args = Arguments::build()?;

        let config: Config = match read_config_file(&config_path) {
            Ok(configuration) => configuration,
            Err(_) => {
                read_default_config = true;
                Self::default()
            }
        }
        .set_command_line_arguments(&args)?
        .validate_config()
        .map_err(|error| {
            eprintln!("{error}");
            error
        })?
        .write_config_file(&config_path, read_default_config)?;

        Ok(config)
    }

    /// Check if the value is in the range.
    pub fn in_range(&self, value: u64) -> bool {
        self.min_dimension <= value && value <= self.max_dimension
    }

    /// Print Config.
    pub fn print(&self) -> MyResult<()> {
        let json: String = serde_json::to_string_pretty(self)?;
        println!("Config:\n{json}\n");

        Ok(())
    }

    /// Set command-line arguments for configuration
    ///
    /// Update self: Config values
    fn set_command_line_arguments(mut self, args: &Arguments) -> MyResult<Self> {
        if let Some(min_dimension) = args.min_dimension {
            self.min_dimension = min_dimension;
        }

        if let Some(max_dimension) = args.max_dimension {
            self.max_dimension = max_dimension;
        }

        if let Some(min_size) = args.min_size {
            self.min_size = min_size;
        }

        if let Some(max_size) = args.max_size {
            self.max_size = max_size;
        }

        if let Some(interval) = args.interval {
            self.interval = interval;
        }

        if let Some(monitor) = args.monitor {
            self.monitor = monitor;
        }

        if args.sort {
            self.sort = !self.sort;
        }

        if args.verbose {
            self.verbose = !self.verbose;
        }

        self.desktop = ENVIRON.desktop.to_string(); // update desktop

        Ok(self)
    }

    /// Validate configuration
    pub fn validate_config(self) -> Result<Self, WSError<'static>> {
        let boundary: Config = config_boundary();

        if self.interval < boundary.interval {
            let value = self.interval.to_string();
            return Err(AtLeastValue("--interval", value, boundary.interval));
        }

        if self.min_dimension < boundary.min_dimension {
            let value = self.min_dimension.to_string();
            return Err(AtLeastValue(
                "--min_dimension",
                value,
                boundary.min_dimension,
            ));
        }

        if self.min_size < boundary.min_size {
            let value = self.min_size.to_string();
            return Err(AtLeastValue("--min_size", value, boundary.min_size));
        }

        if self.monitor < boundary.monitor {
            let value = self.monitor.to_string();
            return Err(AtLeastValue("--interval", value, boundary.monitor.into()));
        }

        if let Some(parent) = self.wallpaper.parent() {
            if !parent.exists() {
                let dir: PathBuf = parent.to_path_buf();
                return Err(Parent(dir));
            }
        }

        if self.min_dimension > self.max_dimension || self.min_size > self.max_size {
            return Err(WSError::MinMaxValue);
        }

        Ok(self)
    }

    /// Write config file path:: "/home/user_name/.config/wallswitch/wallswitch.json"
    pub fn write_config_file(self, path: &PathBuf, read_default_config: bool) -> MyResult<Self> {
        if read_default_config {
            eprintln!("Create the configuration file: {path:?}\n");
        }

        // Recursively create a directory and all of its parent components if they are missing.
        if let Some(parent) = path.parent() {
            // println!("parent: {parent:?}");
            fs::create_dir_all(parent)?
        };

        //let file = File::create(path)?;

        let file: File = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .map_err(|io_error| {
                // Add a custom error message
                WSError::IOError(path.to_path_buf(), io_error.into())
            })?;

        let mut writer = BufWriter::new(file);
        serde_json::to_writer_pretty(&mut writer, &self)?;
        writer.flush()?;

        Ok(self)
    }
}

/// default wallpaper path: "/home/user_name/wallswitch.jpg"
pub fn get_wallpaper_path() -> PathBuf {
    let home = ENVIRON.get_home();
    let pkg_name = ENVIRON.get_pkg_name();

    let mut wallpaper_path: PathBuf = [home, pkg_name].iter().collect();
    wallpaper_path.set_extension("jpg");

    wallpaper_path
}

/// Default directories to search for images.
pub fn get_dirs() -> Vec<PathBuf> {
    /*
    "/home/user_name/Figures",
    "/home/user_name/Images",
    "/home/user_name/Pictures",
    "/home/user_name/Wallpapers",
    "/home/user_name/Imagens",
    */

    let home = ENVIRON.get_home(); // "/home/user_name"
    let images = ["Figures", "Images", "Pictures", "Wallpapers", "Imagens"];

    // Create a vector of image directories under the home directory
    let dirs_home: Vec<PathBuf> = images
        .into_iter()
        .map(|image| Path::new(home).join(image)) // add "home/image"
        .collect();

    /*
    "/usr/share/wallpapers",
    "/usr/share/backgrounds",
    "/tmp/teste",
    */

    let sep: &str = std::path::MAIN_SEPARATOR_STR;

    // add "/usr/share/wallpapers"
    let path1: PathBuf = [sep, "usr", "share", "wallpapers"].iter().collect();
    let path2: PathBuf = [sep, "usr", "share", "backgrounds"].iter().collect();
    let path3: PathBuf = [sep, "tmp", "teste"].iter().collect();

    // Create a vector of additional image directories
    let dirs_others: Vec<PathBuf> = vec![path1, path2, path3];

    // Combine the two vectors and return
    dirs_home.into_iter().chain(dirs_others).collect()
}

/// Config file path: "/home/user_name/.config/wallswitch/wallswitch.json"
pub fn get_config_path() -> MyResult<PathBuf> {
    let home = ENVIRON.get_home();
    let hidden_dir = ".config";
    let pkg_name = ENVIRON.get_pkg_name();

    let mut config_path: PathBuf = [home, hidden_dir, pkg_name, pkg_name].iter().collect();
    config_path.set_extension("json");

    Ok(config_path)
}

/// Read config file path: "/home/user_name/.config/wallswitch/wallswitch.json"
pub fn read_config_file<P>(path: P) -> MyResult<Config>
where
    P: AsRef<Path>,
{
    // Open the file in read-only mode with buffer.
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    // Read the JSON contents of the file as an instance of `Config`.
    let config: Config = serde_json::from_reader(reader)?;

    Ok(config)
}