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
use crate::{MyResult, WSError, ENVIRON};
use serde::{Deserialize, Serialize};
use std::{
    fs::{self, File},
    io::{BufReader, BufWriter, Write},
    path::{Path, PathBuf},
};

/// Configuration variables
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub interval: u64,
    pub min_dimension: u32,
    pub wallpaper: PathBuf,
    pub desktop: String,
    pub dirs: Vec<String>,
}

impl Default for Config {
    fn default() -> Self {
        let interval: u64 = 30 * 60; // 30 * 60 = 1800 seconds (30 minutes)
        let min_dimension: u32 = 800; // minimum dimension height x width

        let home = ENVIRON.get_home();
        let figures = format!("{home}/Figures");
        let images = format!("{home}/Images");
        let wallpapers = format!("{home}/Wallpapers");
        let pictures = format!("{home}/Pictures");
        let imagens = format!("{home}/Imagens");

        // Create the wallpaper path
        let pkg_name = ENVIRON.get_pkg_name();
        let mut wallpaper: PathBuf = [home, pkg_name].iter().collect();
        wallpaper.set_extension("jpg");

        let dirs: Vec<String> = [
            &figures,
            &images,
            &wallpapers,
            &pictures,
            &imagens,
            "/usr/share/wallpapers",
            "/usr/share/backgrounds",
            "/usr/share/antergos/wallpapers",
            "/tmp/teste",
        ]
        .iter()
        .map(ToString::to_string)
        .collect();

        Config {
            interval,
            min_dimension,
            wallpaper,
            desktop: ENVIRON.desktop.to_string(),
            dirs,
        }
    }
}

impl Config {
    pub fn new() -> MyResult<Self> {
        let config_path: PathBuf = get_config_path()?;

        let mut config: Config = match read_config_file(&config_path) {
            Ok(configuration) => configuration,
            Err(_) => {
                eprintln!("Create the configuration file: {config_path:#?}\n");
                Self::default()
            }
        };

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

        config.write_config_file(&config_path)?;

        Ok(config)
    }

    /// Write config file path:: "/home/user_name/.config/wallswitch/wallswitch.json"
    ///
    /// cat wallswitch.json | jq
    pub fn write_config_file(&self, path: &PathBuf) -> MyResult<()> {
        // 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(|error| {
                // Add a custom error message
                eprintln!("Failed to create file {path:?}");
                eprintln!("Perhaps lack of permission!");
                error
            })?;

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

        Ok(())
    }

    fn limits(&self) -> Self {
        Config {
            interval: 5,
            min_dimension: 10,
            ..Config::default()
        }
    }

    /// Validate configuration
    pub fn is_valid(&self) -> Result<(), WSError> {
        let limits = self.limits();

        if self.interval < limits.interval {
            return Err(WSError::IntervalError(self.interval));
        }

        if self.min_dimension < limits.min_dimension {
            return Err(WSError::DimensionError(self.min_dimension));
        }

        if let Some(parent) = self.wallpaper.parent() {
            if !parent.exists() {
                return Err(WSError::ParentError(parent.to_path_buf()));
            }
        }

        Ok(())
    }
}

/// Config file path: "/home/user_name/.config/wallswitch/wallswitch.json"
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)?;

    config.is_valid().map_err(|error| {
        eprintln!("{error}");
        error
    })?;

    Ok(config)
}