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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
use super::err as ies_err;
use super::lum_opening::IesLuminousOpening;
use super::{phot_type::IesPhotometryType, standard::IesStandard, tilt::Tilt};
use crate::photweb::{Plane, mirror_first_quadrant, mirror_first_hemisphere};
use crate::{
    err::Error,
    photweb::{IntensityUnits, PhotometricWeb, PhotometricWebReader, PlaneOrientation},
};
use property::Property;
use regex::Regex;
use std::{
    collections::HashMap,
    default::Default,
    fs::File,
    io::{BufReader, Read, Write},
    path::Path,
    rc::Rc,
    f64::consts::{PI}
};

pub const DELIMITERS_PATTERN: &str = "[ ]+|,|[\r\n]";

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LuminousOpeningUnits {
    Feet = 1,
    Meters = 2,
}

impl Default for LuminousOpeningUnits {
    fn default() -> Self {
        LuminousOpeningUnits::Meters
    }
}

impl From<usize> for LuminousOpeningUnits {
    fn from(val: usize) -> Self {
        match val {
            1 => Self::Feet,
            2 => Self::Meters,
            _ => Self::default(),
        }
    }
}

impl std::fmt::Display for LuminousOpeningUnits {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Feet => "1",
                Self::Meters => "2",
            }
        )
    }
}

#[allow(dead_code)]
#[derive(Default, Clone, Debug, Property)]
pub struct IesFile {
    standard: IesStandard,
    keywords: HashMap<String, String>,
    tilt: Option<Tilt>,

    // First line of parameters
    n_lamps: usize,
    lumens_per_lamp: f64,
    candela_multiplying_factor: f64,
    n_vertical_angles: usize,
    n_horizontal_angles: usize,
    photometric_type: IesPhotometryType,
    luminous_opening_units: LuminousOpeningUnits,
    luminous_opening_width: f64,
    luminous_opening_length: f64,
    luminous_opening_height: f64,

    // Second line of parameters.
    ballast_factor: f64,
    input_watts: f64,

    // Angles
    vertical_angles: Vec<f64>,
    horizontal_angles: Vec<f64>,

    // Brightness vaulues, measured in candellas.
    candela_values: Vec<f64>,
}

impl IesFile {
    /// Returns a new instance of an IES file with default values.
    pub fn new() -> IesFile {
        IesFile {
            ..Default::default()
        }
    }

    /// A wrapper around the parsing code, that opens a file and reads it.
    pub fn parse_file(filepath: &Path) -> Result<IesFile, Error> {
        let infile = File::open(filepath)?;
        let mut ies_string_buf = String::new();
        BufReader::new(infile).read_to_string(&mut ies_string_buf)?;
        let mut ies_file = IesFile::new();
        ies_file.parse(&ies_string_buf)?;
        Ok(ies_file)
    }

    /// Attempts to parse an input file.
    pub fn parse(&mut self, ies_string: &String) -> Result<(), Error> {
        let standard = match ies_string.lines().into_iter().nth(0) {
            None => Err(Error::IESError(ies_err::Error::EmptyFile)),
            Some(val) => Ok(IesStandard::from(val)),
        };

        // If at this point we have an error, just return it. Else we can continue.
        if standard.is_err() {
            return Err(standard.unwrap_err());
        }
        self.standard = standard.unwrap();

        // Parse the keywords.
        self.parse_keywords(&ies_string)?;

        // Parse the TILT.
        self.parse_tilt(&ies_string)?;

        // Now get he remaining values.
        self.parse_properties(&ies_string)?;

        Ok(())
    }

    /// Parses the keywords section of the file.
    pub fn parse_keywords(&mut self, ies_string: &String) -> Result<(), ies_err::Error> {
        // First we find the start line, if not 1986 standard, this will be after the first line.
        let start = if self.standard == IesStandard::Iesna1986 {
            0
        } else {
            1
        };
        // Now find the ending of the keyword section. We can guarantee the line after will always start with "TILT=".
        let end = ies_string
            .lines()
            .position(|line| line.starts_with("TILT="));
        if end.is_none() {
            return Err(ies_err::Error::TiltNotDefined);
        }

        // Build the Regex for Keywork matching.
        let kw_regex = Regex::new("\\[([A-Z_]+)\\] (.*)").unwrap();

        // Get those lines and iterate through them.
        let (keywords, errors): (
            Vec<Result<(String, String), ies_err::Error>>,
            Vec<Result<(String, String), ies_err::Error>>,
        ) = ies_string
            .lines()
            .into_iter()
            .enumerate()
            .skip(start)
            .take(end.unwrap() - start)
            .map(|(iline, line)| {
                // Get the keyword.
                let cap = kw_regex.captures_iter(line);
                match cap.into_iter().nth(0) {
                    None => Err(ies_err::Error::InvalidKeyword(start + iline + 1)),
                    Some(kw) => {
                        // We have a keyword - data pair.
                        Ok((
                            kw.get(1).unwrap().as_str().to_owned(),
                            kw.get(2).unwrap().as_str().to_owned(),
                        ))
                    }
                }
            })
            .partition(Result::is_ok);

        let mut previous_kw: Option<String> = None;
        match errors.first() {
            None => {
                for vals in keywords {
                    let kw = vals.unwrap();

                    if kw.0 == "MORE" {
                        self.keywords
                            .get_mut(previous_kw.as_ref().unwrap())
                            .unwrap()
                            .push_str(&format!(" {}", kw.1));
                    } else {
                        previous_kw = Some(kw.0.clone());
                        self.keywords.insert(kw.0, kw.1);
                    }
                }
                Ok(())
            }
            Some(err) => Err(err.as_ref().unwrap_err().clone()),
        }
    }

    pub fn parse_tilt(&mut self, ies_string: &String) -> Result<(), ies_err::Error> {
        let tilt_res = match ies_string
            .lines()
            .position(|line| line.starts_with("TILT="))
        {
            None => Err(ies_err::Error::TiltNotDefined),
            Some(val) => {
                match ies_string
                    .lines()
                    .nth(val)
                    .unwrap()
                    .replace("TILT=", "")
                    .as_str()
                {
                    "NONE" => Ok(None),
                    "INCLUDE" => {
                        // Pick off just the 4 lines we're interested in and parse.
                        let tilt_lines = ies_string
                            .lines()
                            .skip(val + 1)
                            .take(4)
                            .fold("".to_string(), |accum, item| format!("{}{}\n", accum, item));
                        Tilt::parse(tilt_lines.as_str())
                    }
                    // In this case, we are being given a filename.
                    _ => {
                        let tilt_line = ies_string.lines().nth(val).unwrap();
                        Tilt::from_file(&Path::new(&tilt_line.replace("TILT=", "").to_owned()))
                    }
                }
            }
        };

        match tilt_res {
            Ok(tilt) => {
                self.tilt = tilt;
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    /// This function reads the properties from the file into the data structure.
    pub fn parse_properties(&mut self, ies_string: &String) -> Result<(), ies_err::Error> {
        // I will likely revisit this in the future as I'm unhappy with how this is implemented.
        // It is implemented in a really awkward way. I would like to do this in a nicer way, but
        // I am in a rush and I need it to be working.
        let split_regex = Regex::new(DELIMITERS_PATTERN).unwrap();

        // Assemble and parse all of the numbers.
        let tilt_end_res = ies_string
            .lines()
            .position(|line| line.starts_with("TILT="));
        if tilt_end_res.is_none() {
            return Err(ies_err::Error::TiltNotDefined);
        };

        let tilt_skip = match ies_string
            .lines()
            .nth(tilt_end_res.unwrap())
            .unwrap()
            .replace("TILT=", "")
            .as_str()
        {
            "INCLUDE" => 5,
            _ => 1,
        };

        // Read all of the parameters as one long array, as we know the order and number.
        let start_line = tilt_end_res.unwrap() + tilt_skip;
        let lines: Vec<(usize, String)> = ies_string
            .lines()
            .skip(start_line)
            .enumerate()
            .map(|(iline, str)| {
                let tmp: Vec<(usize, String)> = split_regex
                    .split(str.trim())
                    .map(|val_str| (start_line + iline + 1, String::from(val_str)))
                    .collect();
                tmp
            })
            .flatten()
            .collect();

        let errs: Vec<ies_err::Error> = lines
            .iter()
            .enumerate()
            .map(|(iitem, (iline, item))| {
                match iitem {
                    0 => match item.parse() {
                        Ok(val) => {
                            self.n_lamps = val;
                            Ok(())
                        }
                        Err(err) => {
                            Err(ies_err::Error::ParseIntError(*iline, Some(iitem + 1), err))
                        }
                    },
                    1 => match item.parse() {
                        Ok(val) => {
                            self.lumens_per_lamp = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    2 => match item.parse() {
                        Ok(val) => {
                            self.candela_multiplying_factor = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    3 => match item.parse() {
                        Ok(val) => {
                            self.n_vertical_angles = val;
                            Ok(())
                        }
                        Err(err) => {
                            Err(ies_err::Error::ParseIntError(*iline, Some(iitem + 1), err))
                        }
                    },
                    4 => match item.parse() {
                        Ok(val) => {
                            self.n_horizontal_angles = val;
                            Ok(())
                        }
                        Err(err) => {
                            Err(ies_err::Error::ParseIntError(*iline, Some(iitem + 1), err))
                        }
                    },
                    5 => match item.parse::<usize>() {
                        Ok(val) => match val.try_into() {
                            Ok(phottype) => {
                                self.photometric_type = phottype;
                                Ok(())
                            }
                            Err(err) => {
                                Err(ies_err::Error::FromPrimitiveError(*iline, Rc::new(err)))
                            }
                        },
                        Err(err) => {
                            Err(ies_err::Error::ParseIntError(*iline, Some(iitem + 1), err))
                        }
                    },
                    6 => match item.parse::<usize>() {
                        Ok(val) => {
                            self.luminous_opening_units = val.into();
                            Ok(())
                        }
                        Err(err) => {
                            Err(ies_err::Error::ParseIntError(*iline, Some(iitem + 1), err))
                        }
                    },
                    7 => match item.parse() {
                        Ok(val) => {
                            self.luminous_opening_width = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    8 => match item.parse() {
                        Ok(val) => {
                            self.luminous_opening_length = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    9 => match item.parse() {
                        Ok(val) => {
                            self.luminous_opening_height = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    10 => match item.parse() {
                        Ok(val) => {
                            self.ballast_factor = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    11 => Ok(()),
                    12 => match item.parse() {
                        Ok(val) => {
                            self.input_watts = val;
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    // We will now read the vertical angles from the file.
                    i if i > 12 && i <= 12 + self.n_vertical_angles => match item.parse() {
                        Ok(val) => {
                            self.vertical_angles.push(val);
                            Ok(())
                        }
                        Err(err) => Err(ies_err::Error::ParseFloatError(
                            *iline,
                            Some(iitem + 1),
                            err,
                        )),
                    },
                    // Now read the horizontal values from the file.
                    i if i > 12 + self.n_vertical_angles
                        && i <= 12 + self.n_vertical_angles + self.n_horizontal_angles =>
                    {
                        match item.parse() {
                            Ok(val) => {
                                self.horizontal_angles.push(val);
                                Ok(())
                            }
                            Err(err) => Err(ies_err::Error::ParseFloatError(
                                *iline,
                                Some(iitem + 1),
                                err,
                            )),
                        }
                    }
                    // Now read the candela values.
                    i if i >= 12 + self.n_vertical_angles + self.n_horizontal_angles => {
                        match item.parse() {
                            Ok(val) => {
                                self.candela_values.push(val);
                                Ok(())
                            }
                            Err(err) => Err(ies_err::Error::ParseFloatError(
                                *iline,
                                Some(iitem + 1),
                                err,
                            )),
                        }
                    }
                    // If the properties are not consistent with the arrays, we want to put this here just to check.
                    _ => Err(ies_err::Error::UnexpectedIitem(
                        *iline,
                        12 + self.n_vertical_angles + self.n_horizontal_angles,
                        lines.iter().count(),
                    )),
                }
            })
            .filter_map(|res| {
                if res.is_err() {
                    Some(res.unwrap_err())
                } else {
                    None
                }
            })
            .collect();

        if !errs.is_empty() {
            return Err(errs.first().unwrap().clone());
        }

        Ok(())
    }

    /// Checks to see that the vertical angles are valid according to the IES standard,
    /// The valid configurations are:
    /// - Completely in the bottom hemisphere: first angles and 0 degrees and 90 degress respectively.
    /// - Completely in the top hemisphere: first angles and 90 degrees and 180 degress respectively.
    /// - Otherwise: first angles and 0 degrees and 180 degress respectively.
    pub fn vertical_angles_valid(angles: &Vec<f64>) -> bool {
        match angles.first() {
            Some(first) => match first {
                x if *x == 0.0 => match angles.last() {
                    None => false,
                    Some(last) => match last {
                        y if *y == 90.0 || *y == 180.0 => true,
                        _ => false,
                    },
                },
                x if *x == 90.0 => match angles.last() {
                    None => false,
                    Some(last) => match last {
                        y if *y == 180.0 => true,
                        _ => false,
                    },
                },
                _ => false,
            },
            None => false,
        }
    }

    /// Checks to see that the horizontal angles are valid according to the IES standard.
    /// In this case, the angles are mainly used to defined symmetries, the rules are:
    /// - First angle must always be 0.0.
    /// - If the last values is 0.0, the distribution is axially symmetric.
    /// - If the last value is 90.0 degress, the distribution is symmetric in each quadrant.
    /// - If the last value is 180.0 degress, the distribution is symmetric about a vertical plane.
    /// - If the last value is greater than 180.0 and less than or equal to 360.0, no lateral symmetries.
    /// - Hence, the valid last values are: 0.0, 90.0, 180.0 - 360.0.  
    pub fn horizontal_angles_valid(angles: &Vec<f64>) -> bool {
        match angles.first() {
            Some(first) => match first {
                x if *x == 0.0 => match angles.last() {
                    Some(last) => match last {
                        y if *y == 0.0 => true,
                        y if *y == 90.0 => true,
                        y if *y >= 180.0 && *y <= 360.0 => true,
                        _ => false,
                    },
                    None => false,
                },
                _ => false,
            },
            None => false,
        }
    }

    /// Writes the currently loaded EULUMDAT file to a specified file.
    /// The written value is determined by `LdtFile::to_string(&self)`.
    pub fn to_file(&self, outpath: &Path) -> Result<(), Error> {
        let mut file = File::create(outpath)?;
        file.write(self.to_string().as_bytes())?;
        Ok(())
    }

    /// Outputs the keywords in the file to a string.
    pub fn keywords_to_string(&self) -> String {
        self.keywords
            .iter()
            .fold("".to_string(), |accum, (key, val)| {
                accum + &format!("[{}] {}\n", key, val)
            })
    }

    /// Get the type and properties of the luminous opening.
    pub fn get_luminous_opening(&self) -> IesLuminousOpening {
        IesLuminousOpening::from_dimensions(
            self.luminous_opening_width,
            self.luminous_opening_length,
            self.luminous_opening_height,
        )
    }

    /// Gets the planes from this object.
    pub fn get_planes(&self) -> Vec<Plane> {
        match self.photometric_type {
            IesPhotometryType::TypeA => self.get_planes_type_a(),
            IesPhotometryType::TypeB => self.get_planes_type_b(),
            IesPhotometryType::TypeC => self.get_planes_type_c(),
        }
    }

    /// Get the planes from a Type A photometry IES file.
    pub fn get_planes_type_a(&self) -> Vec<Plane> {
        todo!()
    }

    /// Get the planes from a Type A photometry IES file.
    pub fn get_planes_type_b(&self) -> Vec<Plane> {
        todo!()
    }

    /// Get the planes from a Type C photometry IES file.
    pub fn get_planes_type_c(&self) -> Vec<Plane> {
        // Chunk the intensities into the planes, and give them appropriate angles.
        let mut planes = self
            .candela_values
            .chunks(self.n_vertical_angles)
            .enumerate()
            .map(|(iplane, intensities_candelas)| {
                let mut curr_plane = Plane::new();
                curr_plane.set_angle_degrees(self.horizontal_angles[iplane]);
                curr_plane.set_orientation(PlaneOrientation::Vertical);
                curr_plane.set_intensities(Vec::from(intensities_candelas));
                curr_plane.set_angles_degrees(&self.vertical_angles);
                curr_plane.set_units(IntensityUnits::Candela);
                curr_plane
            })
            .collect::<Vec<Plane>>();
        
        // Now resolve the symmetries.
        // First, check if we have the first quadrant filled (from 0 -> 90 deg).
        // If so, mirror this to fill the 0 -> 180 degree hemisphere. 
        if (planes.iter().last().unwrap().angle() - (PI / 2.0)).abs() <= f64::EPSILON {
            planes = mirror_first_quadrant(&planes);
        }

        // Now, check to see if we have the first hemisphere (0 -> 180 deg). 
        // If so mirror this to fill the final hemisphere.
        if (planes.iter().last().unwrap().angle() - (PI)).abs() <= f64::EPSILON {
            planes = mirror_first_hemisphere(&planes);
        }

        planes
    }
}

impl ToString for IesFile {
    fn to_string(&self) -> String {
        let mut output = String::new();

        // Get the standard header.
        let stan = self.standard.to_string();
        if !stan.is_empty() {
            output = format!("{}\n", &stan);
        };

        // Output keywords
        output += &self.keywords_to_string();

        // Output the tilt.
        let tilt_str = match &self.tilt {
            None => String::from("TILT=NONE\n"),
            Some(val) => val.to_string(),
        };
        output += &tilt_str;

        // Now output the parameters and arrays.
        output += &format!(
            "{} {} {} {} {} {} {} {} {} {}\n",
            self.n_lamps,
            self.lumens_per_lamp,
            self.candela_multiplying_factor,
            self.n_vertical_angles,
            self.n_horizontal_angles,
            (self.photometric_type.clone() as usize),
            self.luminous_opening_units,
            self.luminous_opening_width,
            self.luminous_opening_length,
            self.luminous_opening_height
        );
        output += &format!("{} {} {}\n", self.ballast_factor, 1, self.input_watts,);
        output += &format!(
            "{}\n",
            self.vertical_angles
                .iter()
                .fold(String::new(), |accum, val| accum + &format!("{} ", val))
        );
        output += &format!(
            "{}\n",
            self.horizontal_angles
                .iter()
                .fold(String::new(), |accum, val| accum + &format!("{} ", val))
        );
        output += &format!(
            "{}\n",
            self.candela_values
                .chunks(self.n_vertical_angles)
                .fold(String::new(), |accum, val| accum
                    + &format!(
                        "{}\n",
                        val.iter()
                            .fold(String::new(), |accum, val| accum + &format!("{} ", val))
                    ))
        );

        output
    }
}

impl From<IesFile> for PhotometricWeb {
    fn from(ies: IesFile) -> Self {
        let mut photweb = PhotometricWeb::new();
        photweb.set_planes(ies.get_planes());
        photweb
    }
}

//TODO: Implement conversion.
impl PhotometricWebReader for IesFile {
    fn read(&self, path: &Path) -> Result<PhotometricWeb, Error> {
        let ies_file = Self::parse_file(path)?;
        let photweb = ies_file.into();
        Ok(photweb)
    }
}