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

/// configuration variables
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub interval: u64,
    pub min_dimension: u32,
    pub wallpaper: String,
    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 = get_home();
        let pictures = format!("{home}/Pictures");
        let imagens = format!("{home}/Imagens");

        // Create a string for the wallpaper path
        let wallpaper = format!("{home}/wallswitch.jpg");

        let dirs: Vec<String> = [
            &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: get_desktop(),
            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(_) => Self::default(),
        };

        config.desktop = get_desktop(); // 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(false)
            .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(())
    }
}

/// Config file path: "/home/user_name/.config/wallswitch/wallswitch.json"
fn get_config_path() -> MyResult<PathBuf> {
    let home = env::var("HOME").map_err(|error| {
        eprintln!("env HOME not found!");
        eprintln!("echo $HOME");
        error
    })?;

    let hidden_dir = ".config".to_string();

    let pkg_name = "wallswitch".to_string();

    /*
    let pkg_name = env::var("CARGO_PKG_NAME").map_err(|error| {
        eprintln!("env CARGO_PKG_NAME not found!");
        error
    })?;
    */

    let config_file = format!("{pkg_name}.json");

    let config_path: PathBuf = [home, hidden_dir, pkg_name, config_file].iter().collect();

    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)
}

/// echo $HOME
pub fn get_home() -> String {
    match env::var("HOME") {
        Ok(home) => home,
        Err(why) => {
            eprintln!("echo $HOME");
            panic!("Error: Unable to get home path! {why}");
        }
    }
}

/// echo $DESKTOP_SESSION
pub fn get_desktop() -> String {
    match env::var("DESKTOP_SESSION") {
        Ok(desktop) => desktop,
        Err(why) => {
            eprintln!("echo $DESKTOP_SESSION");
            panic!("Error: Unable to get desktop type! {why}");
        }
    }
}

#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct FileInfo {
    pub resolution: Resolution,
    pub valid: bool,
    pub size: u64,
    pub path: PathBuf,
}

impl FileInfo {
    pub fn path_contains(&self, string: &str) -> bool {
        match self.path.to_str() {
            Some(p) => p.contains(string),
            None => false,
        }
    }

    pub fn is_valid(&self, config: &Config) -> bool {
        // Calcular o mínimo entre largura e altura
        let width = self.resolution.width;
        let height = self.resolution.height;
        let min = width.min(height);

        min > config.min_dimension
    }

    pub fn update_info(&mut self, config: &Config) -> MyResult<()> {
        let identify = Command::new("identify")
            .arg("-format")
            .arg("%wx%h") // x separator
            .arg(&self.path)
            .output()?;

        let sdt_output = String::from_utf8(identify.stdout)?;
        let resolution = Resolution::new(&sdt_output);

        self.resolution = resolution;
        self.valid = self.is_valid(config);

        println!("file_info: {self:?}");

        Ok(())
    }
}

pub trait SortFiles {
    fn unique(&mut self);
}

impl SortFiles for Vec<FileInfo> {
    fn unique(&mut self) {
        self.sort();
        self.dedup();
    }
}

#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct Resolution {
    pub width: u32,
    pub height: u32,
}

impl Resolution {
    pub fn new(string: &str) -> Resolution {
        let (width, height) = split_str(string);
        Resolution { width, height }
    }
}

fn split_str(string: &str) -> (u32, u32) {
    let numbers: Vec<u32> = string
        .trim()
        .split('x')
        .flat_map(|number| number.parse::<u32>())
        .collect();

    if numbers.len() != 2 {
        eprintln!("fn split_str()");
        panic!("Error: split '{string}' for Vec<u32>");
    }

    let width = numbers[0];
    let height = numbers[1];

    (width, height)
}

pub trait PrintSlice {
    fn print_slice(&self, spaces: &str);
}

impl<T> PrintSlice for [T]
where
    T: std::fmt::Display,
{
    fn print_slice(&self, spaces: &str) {
        for dir in self {
            println!("{spaces}'{dir}'");
        }
    }
}