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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//! # Integer Media File Parser
//!
//! This crate provides utilities for reading and parsing IMFs, a simple file format for storing 2D arrays.
use fancy_regex::Regex;
use std::collections::BTreeMap;
use std::fs;
use std::fs::File;
use std::io::Write;
use colors_transform::{Color, Rgb};
#[derive(Clone)]
/// Stores the version, colors, width, height and content of an Integer Media File.
pub struct IMF {
    pub version: u8,
    pub colors: BTreeMap<i32, (u8, u8, u8)>,
    pub width: usize,
    pub height: usize,
    pub map: Vec<i32>,
}

impl IMF {
    /// Returns an IMF filled with default values.
    pub fn default() -> IMF {
        let mut m: BTreeMap<i32, (u8, u8, u8)> = BTreeMap::new();
        m.insert(0, (0, 0, 0));
        m.insert(1, (127, 127, 127));
        m.insert(2, (255, 255, 255));
        m.insert(3, (255, 0, 0));
        m.insert(4, (255, 127, 0));
        m.insert(5, (255, 255, 0));
        m.insert(6, (0, 255, 0));
        m.insert(7, (0, 0, 255));
        m.insert(8, (127, 0, 255));
        m.insert(9, (255, 0, 255));

        IMF {
            version: 1,
            colors: m,
            width: 8,
            height: 8,
            map: vec![1; 64],
        }
    }
    /// Creates new IMF from file located at filepath.
    /// If you want to create a new one from existing variables, declare it like this:
    /// ```
    /// use imf::IMF;
    ///
    /// //assuming that all variables already exist
    /// let imf = IMF {
    ///     version,
    ///     colors,
    ///     width,
    ///     height,
    ///     map
    /// };
    pub fn new(path: &str) -> Result<IMF, String> {
        let file_str = fs::read_to_string(path).map_err(|e| format!("Failed to read file '{path}': \n\t{e}"))?;
        let mut imf = IMF::default();

        let version = Self::proc_version(&file_str).map_err(|e| format!("IMF::Version: {e}"))?.unwrap_or_else(|| 1);
        imf.version = version;

        imf = match version {
            1 => Self::load_v1(imf.clone(), &file_str).map_err(|e| format!("IMF::LoadV1{e}"))?,
            2 => Self::load_v2(imf.clone(), &file_str).map_err(|e| format!("IMF::LoadV2{e}"))?,
            _ => return Err("Incompatible IMF version!".to_string())
        };

        Ok(imf)
    }

    fn load_v1(imf: IMF, file: &str) -> Result<IMF, String> {
        let mut i = imf;
        let mut lines = file.split('\n').filter(|line| !line.trim().is_empty());

        let width = lines.next().unwrap().parse().map_err(|_| "::Dimensions: Width not a number")?;
        let height = lines.next().unwrap().parse().map_err(|_| "::Dimensions: Height not a number")?;

        let mut map_str = String::new();

        while let Some(line) = lines.next() {
            map_str.push_str(line)
        }

        let map_arr = str2vec(map_str.as_str()).map_err(|e| format!("::Map: {e}"))?;

        let correct_size = width * height;

        if map_arr.len() != correct_size {
            let indic = if map_arr.len() > correct_size { "many" } else { "few" };
            return Err(format!("::Map: Too {indic} numbers in list"));
        }

        i.width = width;
        i.height = height;
        i.map = map_arr;

        Ok(i)
    }
    fn load_v2(imf: IMF, file: &str) -> Result<IMF, String> {
        let mut i = imf;

        let buffer = file.lines().fold(String::new(), |mut acc, line| {
            acc.push_str(line);
            acc
        });

        let clean_file = buffer.as_str();

        let col_map = Self::proc_cols(&clean_file).map_err(|e| format!("::Colors: {e}"))?;
        let (width, height) = Self::proc_dim(&clean_file).map_err(|e| format!("::Dimensions: {e}"))?;
        let map = Self::proc_map(&clean_file, width, height).map_err(|e| format!("::Map: {e}"))?;

        i.width = width;
        i.height = height;
        i.map = map;

        if col_map.is_some() { i.colors = col_map.unwrap() }

        Ok(i)
    }

    fn proc_version(file: &str) -> Result<Option<u8>, String> {
        let r = Regex::new(r"(?i)(?:\[v)(\d+)(?:])").unwrap();

        let version = match r.captures(file) {
            Ok(Some(m)) => m.get(1).unwrap().as_str(),
            Ok(None) => return Ok(None),
            Err(_) => return Err("Regex matching error".to_string())
        };

        Ok(version.parse().ok())
    }
    fn proc_dim(file: &str) -> Result<(usize, usize), String> {
        // matches with 'width/height'
        let r = Regex::new(r"\d+,\d+(?=\s*;)").unwrap();

        let dim_str = r.find(file).map_err(|_| "Regex matching error")?;
        if dim_str.is_none() { return Err("Dimensions not found".to_string()); }

        let dims: Vec<&str> = dim_str.unwrap().as_str().split(',').collect();
        if dims.len() != 2 { return Err("Invalid amount of dimensions".to_string()); }

        let x = dims[0].parse().map_err(|_| "Width is not a number")?;
        let y = dims[1].parse().map_err(|_| "Height is not a number")?;

        Ok((x, y))
    }
    fn proc_cols(file: &str) -> Result<Option<BTreeMap<i32, (u8, u8, u8)>>, String> {
        let r = Regex::new(r"(\d+\([0-9a-fA-F]{6}\))+").unwrap();
        let colors_str: &str;

        match r.find(file) {
            Ok(Some(c)) => colors_str = c.as_str(),
            Ok(None) => return Ok(None),
            Err(_) => return Err("Regex matching error".to_string())
        }

        let colors_list = colors_str.split(')').filter(|s| !s.is_empty()).collect::<Vec<&str>>();
        let mut color_map: BTreeMap<i32, (u8, u8, u8)> = BTreeMap::new();

        for c in colors_list {
            let key;
            let val;

            if let Some((key_str, col_str)) = c.split_once('(') {
                key = key_str.parse::<i32>().map_err(|_| format!("'{key_str}' not a number"))?;
                val = col_str;
            } else {
                return Err(format!("Incorrect formatting on line '{c})'"));
            }

            let hex = format!("#{val}");
            let rgb = Rgb::from_hex_str(hex.as_str()).map_err(|_| format!("'{hex}' is not a valid hex code!"))?;

            color_map.insert(key, (
                (rgb.get_red() * 255f32) as u8,
                (rgb.get_green() * 255f32) as u8,
                (rgb.get_blue() * 255f32) as u8),
            );
        }

        Ok(Some(color_map))
    }
    fn proc_map(file: &str, w: usize, h: usize) -> Result<Vec<i32>, String> {
        let r = Regex::new(r"(?<=\[)(\d+,?)+(?=\])").unwrap();

        let map_str: &str = match r.find(file).expect("Regex matching error") {
            Some(m) => m.as_str(),
            None => return Err("Integer list not found".to_string())
        };

        let map_arr = str2vec(map_str)?;

        if map_arr.len() != w * h {
            let indic = if map_arr.len() < w * h { "many" } else { "few" };
            return Err(format!("Too {indic} numbers in list"));
        }

        Ok(map_arr.to_vec())
    }

    ///Returns number found at coordinates within IMF.
    ///See [`IMF::set_xy`]
    /// ## Arguments
    /// * `x` - The X coordinate
    /// * `y` - The Y coordinate
    ///
    ///## Example
    ///```
    /// use imf::IMF;
    /// //example.imf:
    /// //1,0,1,5,
    /// //4,7,3,3,
    /// //9,2,5,6,
    /// //0,5,8,2
    ///
    /// let mut imf = IMF::new("example.imf").unwrap();
    /// let n = imf.get_xy(1,1).unwrap();
    ///
    /// // n == 7
    pub fn get_xy(&self, x: usize, y: usize) -> Option<i32> {
        let index = self.xy2i(x, y)?;
        self.map.get(index).cloned()
    }
    ///Sets number at coordinates within IMF to the number specified.
    ///See [`IMF::get_xy`]
    /// ## Arguments
    /// * `x` - The X coordinate
    /// * `y` - The Y coordinate
    /// * `i` - What the number will be set to
    ///## Example
    ///```
    /// use imf::IMF;
    ///
    /// let mut imf = IMF::new("example.imf").unwrap();
    /// imf.set_xy(2,2,5);
    ///
    /// // imf.get_xy(2,2) == 5
    pub fn set_xy(&mut self, x: usize, y: usize, i: i32) -> bool {
        if let Some(index) = self.xy2i(x, y) {
            if let Some(val) = self.map.get_mut(index){
                *val = i;
                true;
            }
        }
        false
    }
    /// Converts XY coordinates to an index. This does not check to see if anything exists at that index.
    /// See [`IMF::i2xy`]
    /// ## Example
    /// ```
    /// use imf::IMF;
    /// //example.imf:
    /// //1,0,1,5,
    /// //4,7,3,3,
    /// //9,2,5,6,
    /// //0,5,8,2
    ///
    /// let imf = IMF::new("example.imf").unwrap();
    /// let n = imf.xy2i(2,2);
    ///
    /// // n == 10
    pub fn xy2i(&self, x: usize, y: usize) -> Option<usize> {
        if x >= self.width || y >= self.height { return None }

        Some(y * self.width + x)
    }
    /// Converts index to XY coordinates.
    /// See [`IMF::xy2i`]
    /// ## Example
    /// ```
    /// use imf::IMF;
    /// //example.imf:
    /// //1,0,1,5,
    /// //4,7,3,3,
    /// //9,2,5,6,
    /// //0,5,8,2
    ///
    /// let imf = IMF::new("example.imf").unwrap();
    /// let n = imf.xy2i(2,2);
    /// let m = imf.i2xy(10);
    ///
    /// // n == m
    pub fn i2xy(&self, i: usize) -> Option<(usize, usize)> {
        if i < self.map.len() {
            let y = i / self.width;
            let x = i % self.width;
            Some((x, y))
        } else {
            None
        }
    }

    ///Writes IMF to given filepath in .imf form
    pub fn write(&self, path: &str) -> Result<(), String> {
        let mut file = File::create(path).map_err(|e| e.to_string())?;

        match self.version {
            1 => {
                writeln!(file, "{}", self.width).map_err(|e| e.to_string())?;
                writeln!(file, "{}", self.height).map_err(|e| e.to_string())?;

                for y in 0..self.height {
                    for x in 0..self.width {
                        let index = self.xy2i(x, y);
                        write!(file, "{},", self.map.get(index.expect("V1 Writing failed!")).unwrap()).map_err(|e| e.to_string())?;
                    }
                    writeln!(file).map_err(|e| e.to_string())?;
                }
            }
            2 => {
                writeln!(file, "[v2]").map_err(|e| e.to_string())?;
                writeln!(file, "{},{};", self.width, self.height).map_err(|e| e.to_string())?;
                for col in self.colors.clone() {
                    let (index, (r, g, b)) = col;
                    let color = Rgb::from_tuple(&(r as f32, g as f32, b as f32)).to_css_hex_string()
                        .replace('#', "");

                    writeln!(file, "{index}({color})").map_err(|e| e.to_string())?;
                }
                writeln!(file, "[").map_err(|e| e.to_string())?;
                for y in 0..self.height {
                    for x in 0..self.width {
                        let index = self.xy2i(x, y);
                        write!(file, "{},", self.map.get(index.expect("V2 Writing failed!")).unwrap()).map_err(|e| e.to_string())?;
                    }
                    writeln!(file).map_err(|e| e.to_string())?;
                }
                writeln!(file, "]").map_err(|e| e.to_string())?;
            }
            _ => {}
        }

        Ok(())
    }
}

/// Converts string to vector of integers
/// ## Example
/// ```
/// use imf::str2vec;
///
/// //works with all spacings
/// let vec = str2vec("0,1, 2, 3 ,4 ,5");
///
/// // vec == vec![0,1,2,3,4,5];
pub fn str2vec(str: &str) -> Result<Vec<i32>, String> {
    let mut map = Vec::new();

    for item in str.split(',') {
        let t = item.trim();

        if t.is_empty() { continue; };

        match t.parse::<i32>() {
            Ok(n) => map.push(n),
            Err(_) => return Err(format!("'{t}' is not a number!"))
        }
    }

    Ok(map)
}

#[cfg(test)]
mod tests {
    // #[test]
    // fn test() {
    //     let i = IMF::new("export2.imf").unwrap();
    //     i.write("export2.imf").map_err(|e| println!("ERROR: {}", e)).ok();
    // }
}