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
use regex::Regex;

use super::Error;
use std::{
    fs::File,
    io::{BufReader, Read},
    path::Path,
};

use super::DELIMITERS_PATTERN;

/// A struct for representing tilt angles in lumminaires.
#[derive(Debug, Clone, Default)]
pub struct Tilt {
    lamp_to_lumminaire_geometry: usize,
    no_tilt_angles: usize,
    angles: Vec<f32>,
    multiplying_factors: Vec<f32>,
}

impl Tilt {
    pub fn new() -> Tilt {
        Self {
            ..Default::default()
        }
    }

    pub fn from_file(filepath: &Path) -> Result<Option<Tilt>, Error> {
        let infile = File::open(filepath)?;
        let mut tilt_string_buf = String::new();
        BufReader::new(infile).read_to_string(&mut tilt_string_buf)?;
        Tilt::parse(&tilt_string_buf)
    }

    pub fn parse(tilt_str: &str) -> Result<Option<Tilt>, Error> {
        let split_regex = Regex::new(DELIMITERS_PATTERN).unwrap();
        let mut tilt = Tilt::new();
        let errors: Vec<Result<(), Error>> = tilt_str
            .lines()
            .into_iter()
            .enumerate()
            .map(|(iline, line)| {
                match iline {
                    // Get the lamp to lumminaire geometry.
                    0 => match line.parse::<u8>() {
                        Ok(val) => {
                            tilt.lamp_to_lumminaire_geometry = val as usize;
                            Ok(())
                        }
                        Err(e) => Err(crate::io::ies::Error::ParseIntError(iline, None, e)),
                    },
                    // Get the number of tilt angles.
                    1 => match line.parse::<u8>() {
                        Ok(val) => {
                            tilt.no_tilt_angles = val as usize;
                            Ok(())
                        }
                        Err(e) => Err(crate::io::ies::Error::ParseIntError(iline, None, e)),
                    },
                    // Get the tilt angles.
                    2 => {
                        let (vals, errs): (Vec<_>, Vec<_>) = split_regex
                            .split(line)
                            .map(|str| str.parse::<f32>())
                            .partition(Result::is_ok);
                        let numbers: Vec<_> = vals.into_iter().map(Result::unwrap).collect();
                        let errors: Vec<_> = errs.into_iter().map(Result::unwrap_err).collect();
                        match errors.first() {
                            None => {
                                if numbers.len() == tilt.no_tilt_angles {
                                    tilt.angles = numbers;
                                    Ok(())
                                } else {
                                    Err(crate::io::ies::Error::ArrayIncorrectLength(
                                        iline,
                                        tilt.no_tilt_angles,
                                        numbers.len(),
                                    ))
                                }
                            }
                            Some(e) => Err(crate::io::ies::Error::ParseFloatError(
                                iline,
                                None,
                                e.clone(),
                            )),
                        }
                    }
                    // Get the multiplying factors.
                    3 => {
                        let (vals, errs): (Vec<_>, Vec<_>) = split_regex
                            .split(line)
                            .map(|str| str.parse::<f32>())
                            .partition(Result::is_ok);
                        let numbers: Vec<_> = vals.into_iter().map(Result::unwrap).collect();
                        let errors: Vec<_> = errs.into_iter().map(Result::unwrap_err).collect();
                        match errors.first() {
                            None => {
                                if numbers.len() == tilt.no_tilt_angles {
                                    tilt.multiplying_factors = numbers;
                                    Ok(())
                                } else {
                                    Err(crate::io::ies::Error::ArrayIncorrectLength(
                                        iline,
                                        tilt.no_tilt_angles,
                                        numbers.len(),
                                    ))
                                }
                            }
                            Some(e) => Err(crate::io::ies::Error::ParseFloatError(
                                iline,
                                None,
                                e.clone(),
                            )),
                        }
                    }
                    _ => Err(Error::TiltFiltTooLong(iline)),
                }
            })
            .filter(Result::is_err)
            .collect();

        match errors.first() {
            None => Ok(Some(tilt)),
            Some(err) => Err(err.as_ref().unwrap_err().clone()),
        }
    }
}

impl ToString for Tilt {
    fn to_string(&self) -> String {
        format!(
            "TILT=INCLUDE\n{}\n{}\n{}\n{}\n",
            self.lamp_to_lumminaire_geometry,
            self.no_tilt_angles,
            self.angles
                .iter()
                .fold("".to_string(), |accum, val| accum + &format!("{} ", val)),
            self.multiplying_factors
                .iter()
                .fold("".to_string(), |accum, val| accum + &format!("{} ", val)),
        )
    }
}