f_value 0.1.6

Tool for NISECI and HFBI calc
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
// SPDX-License-Identifier: GPL-3.0-only
/*
    Copyright (C) 2024-2026 jgabaut, gioninjo

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, version 3 of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
pub(crate) struct OutputController;
use crate::app::core::{Action, Localize};
use crate::app::model::{Model, SubModel};
use crate::controllers::{Controller, CurrentView, OutputModel};
use crate::core::pdf::{esporta_pdf_hfbi, esporta_pdf_niseci};
use crate::core::{gen_logfile_name, CommaFormat};
use crate::MainState;
use dirs::document_dir;
use esox::domain::hfbi::{AnagraficaHFBI, RisultatoHFBI, ValoriIntermediHFBI};
use esox::domain::index::Indice;
use esox::domain::niseci::{AnagraficaNISECI, RiferimentoNISECI};

#[cfg(not(feature = "lessclone"))]
use esox::{
    domain::niseci::{RisultatoNISECI, ValoriIntermediNISECI},
    engines::niseci::full::{
        calculate_niseci, calculate_rqe_niseci, calculate_stato_ecologico_niseci,
    },
};

#[cfg(feature = "lessclone")]
use esox::{
    domain::niseci::lessclone::{RisultatoNISECI, ValoriIntermediNISECI},
    engines::niseci::full::lessclone::{
        calculate_niseci, calculate_rqe_niseci, calculate_stato_ecologico_niseci,
    },
};

use esox::engines::hfbi::full::{calculate_hfbi, calculate_stato_ecologico_hfbi};
use raylib::RaylibHandle;
use std::fs::{create_dir, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

impl Controller for OutputController {
    type SubModel = OutputModel;

    fn update(
        &self,
        _rl: &mut RaylibHandle,
        state: &mut Model,
        actions: &mut Vec<Action>,
        main_state: &mut MainState,
    ) {
        state.output_model.increment_frame_counter();

        if state.output_model.get_should_reset() {
            main_state.showing_reset_win = true;
            state.output_model.set_should_reset(false);
            return;
        }
        if main_state.should_reset {
            eprintln!("OutputController: Resetting");
            main_state.should_reset = false;
            state.home_model.reset();
            state.second_model.reset();
            state.indice_model.reset();
            state.fileinput_model.reset();
            state.infoaggiuntive_model.reset();
            state.data_model.reset();
            state.output_model.reset();
            state.console_model.reset();
            main_state.set_current_view(CurrentView::Home);
            return;
        }

        if state.data_model.get_errors_occurred() {
            eprintln!("OutputController:  Errors occurred");
            eprintln!("OutputController:  Let's update current view and go to CONSOLE.");
            main_state.set_current_view(CurrentView::Console);
            eprintln!("OutputController:  Clearing error state");
            state.data_model.set_errors_occurred(false);
        }

        for a in actions.drain(..) {
            match a {
                Action::RunCalc => {
                    if let Some(idx) = state.indice_model.get_selected_index() {
                        match idx {
                            Indice::Niseci => {
                                self.calc_niseci(state, main_state.locale);
                            }
                            Indice::Hfbi => {
                                self.calc_hfbi(state, main_state.locale);
                            }
                        }
                    } else {
                        eprintln!(
                            "OutputController:  Can't handle action {} without a selected index",
                            a
                        );
                    }
                }
                Action::ConfirmCalc => {
                    self.user_confirm_calc(state);
                }
                Action::ExportPdf(path) => {
                    if let Some(idx) = state.indice_model.get_selected_index() {
                        match idx {
                            Indice::Niseci => {
                                self.esporta_pdf_niseci(state, path);
                            }
                            Indice::Hfbi => {
                                self.esporta_pdf_hfbi(state, path);
                            }
                        }
                    } else {
                        eprintln!(
                            "OutputController:  Can't handle action pdf export without a selected index"

                        );
                    }
                }
                Action::Reset => {
                    self.prompt_reset(state);
                }
                _ => {
                    println!("OutputController:  Got action {}", a);
                }
            }
        }
        match main_state.current_view {
            CurrentView::ProduzioneOutput => {
                if state.output_model.is_done_user_confirm() {
                    eprintln!("OutputController:  User confirmed");
                    eprintln!(
                        "OutputController:  Let's update current view and go to ProduzionePDF."
                    );
                    main_state.set_current_view(CurrentView::ProduzionePDF);
                }
            }
            CurrentView::ProduzionePDF => {}
            _ => {}
        }
    }
}

impl OutputController {
    pub(crate) fn new() -> Self {
        Self
    }

    fn prep_logfile_dir(&self) -> Option<PathBuf> {
        if let Some(documents_dir) = document_dir() {
            let dir = documents_dir.join("f_value");
            if let Err(e) = create_dir(&dir) {
                if e.kind() != std::io::ErrorKind::AlreadyExists {
                    eprintln!("Failed to create dir: {}, {}", dir.display(), e);
                    return None;
                }
            };
            Some(dir)
        } else {
            let dir = PathBuf::from("./f_value");
            if let Err(e) = create_dir(&dir) {
                if e.kind() != std::io::ErrorKind::AlreadyExists {
                    eprintln!("Failed to create dir: {}, {}", dir.display(), e);
                    return None;
                }
            };
            Some(dir)
        }
    }

    pub(crate) fn get_is_done_calc(&self, state: &Model) -> bool {
        state.output_model.is_done_calc()
    }

    fn set_data_risultato_niseci(&self, state: &mut Model, risultato: RisultatoNISECI) {
        self.set_console_env(
            state,
            ("risultato_niseci".to_string(), format!("{risultato}")),
        );
        state.data_model.set_risultato_niseci(Some(risultato));
        state.output_model.set_done_calc(true);
    }

    pub(crate) fn calc_niseci(&self, state: &mut Model, locale: Localize) {
        let riferimento = state.data_model.get_riferimento_niseci();
        let campionamento = state.data_model.get_campionamento_niseci();
        let anagrafica = state.data_model.get_anagrafica_niseci();

        let mut valid = true;

        if riferimento.is_none() {
            // Implementation error, this should never happen
            valid = false;
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: riferimento niseci was None in calc_niseci()".to_string(),
            );
        }
        if campionamento.is_none() {
            // Implementation error, this should never happen
            valid = false;
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: campionamento niseci was None in calc_niseci()".to_string(),
            );
        }
        if anagrafica.is_none() {
            // Implementation error, this should never happen
            valid = false;
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: anagrafica niseci was None in calc_niseci()".to_string(),
            );
        }
        if valid {
            let riferimento = riferimento.expect("calc_niseci() checked is_none() before");
            let campionamento = campionamento.expect("calc_niseci() checked is_none() before");
            let anagrafica = anagrafica.expect("calc_niseci() checked is_none() before");

            match calculate_niseci(&campionamento, &riferimento, &anagrafica) {
                Ok((niseci, intermediates)) => {
                    let niseci_str = match niseci {
                        Some(val) => match locale {
                            Localize::Italian => val.comma().to_string(),
                            Localize::International => {
                                format!("{val}")
                            }
                        },
                        None => "NC".to_string(),
                    };
                    self.add_console_message(state, format!("NISECI: {niseci_str}"));

                    let rqe_niseci = calculate_rqe_niseci(niseci);
                    let rqe_niseci_str = match rqe_niseci {
                        Some(val) => match locale {
                            Localize::Italian => val.comma().to_string(),
                            Localize::International => {
                                format!("{val}")
                            }
                        },
                        None => "NC".to_string(),
                    };
                    self.add_console_message(state, format!("RQE NISECI: {rqe_niseci_str}"));

                    let stato_ecologico =
                        calculate_stato_ecologico_niseci(niseci, &anagrafica.area);
                    let stato_ecologico_str = match stato_ecologico {
                        Some(val) => {
                            format!("{val}")
                        }
                        None => "NC".to_string(),
                    };
                    self.add_console_message(
                        state,
                        format!("Stato ecologico: {stato_ecologico_str}"),
                    );

                    let risultato_niseci =
                        RisultatoNISECI::new(niseci, rqe_niseci, intermediates.clone());
                    self.log_niseci_values(
                        locale,
                        &anagrafica,
                        &risultato_niseci,
                        &state
                            .fileinput_model
                            .get_riferimento_path()
                            .expect("Failed initialising riferimento niseci path"),
                    );

                    //This logs to stdout
                    println!("{}", intermediates);

                    self.add_console_message(state, format!("{intermediates}"));

                    self.log_niseci_intermediates(
                        locale,
                        &intermediates,
                        &riferimento,
                        &state
                            .fileinput_model
                            .get_riferimento_path()
                            .expect("Failed initialising riferimento niseci path"),
                        &anagrafica.codice_stazione,
                    );

                    self.set_data_risultato_niseci(state, risultato_niseci);
                    println!("OutputController: Finished NISECI calc");
                }
                Err(niseci_errors) => {
                    for e in niseci_errors {
                        self.add_console_message(
                            state,
                            format!("Errore durante il calcolo NISECI: {}", e),
                        );
                    }
                    state.data_model.set_errors_occurred(true);
                    state.output_model.set_done_calc(false);
                    state.data_model.set_risultato_niseci(None);
                }
            }
        } else {
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: spurious state in calc_niseci()".to_string(),
            );
            state.data_model.set_errors_occurred(true);
        }
    }

    pub(crate) fn log_niseci_values(
        &self,
        locale: Localize,
        anagrafica: &AnagraficaNISECI,
        risultato: &RisultatoNISECI,
        ref_filename: &Path,
    ) {
        let name = gen_logfile_name(ref_filename, &anagrafica.codice_stazione, true);
        let log_file_path;
        if let Some(dir) = self.prep_logfile_dir() {
            log_file_path = dir.join(name);
        } else {
            return;
        }
        let file_result = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(log_file_path);

        match file_result {
            Ok(mut file) => {
                let comma_csv_delimiter = match locale {
                    Localize::Italian => false,
                    Localize::International => true,
                };
                let string_representation = risultato.to_csv(anagrafica, comma_csv_delimiter);
                let write_result = writeln!(file, "{string_representation}");
                match write_result {
                    Ok(_) => println!("Successfully wrote to file."),
                    Err(e) => eprintln!("Failed to write to file: {}", e),
                }
            }
            Err(e) => {
                eprintln!("Failed to open file: {}", e);
            }
        }
    }

    pub(crate) fn log_niseci_intermediates(
        &self,
        locale: Localize,
        intermediates: &ValoriIntermediNISECI,
        riferimento: &RiferimentoNISECI,
        ref_filename: &Path,
        station_code: &str,
    ) {
        let name = gen_logfile_name(ref_filename, station_code, false);
        let log_file_path;
        if let Some(dir) = self.prep_logfile_dir() {
            log_file_path = dir.join(name);
        } else {
            return;
        }

        let file_result = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(log_file_path);

        match file_result {
            Ok(mut file) => {
                let comma_csv_delimiter = match locale {
                    Localize::Italian => false,
                    Localize::International => true,
                };
                let string_representation =
                    intermediates.to_csv_joined(riferimento, comma_csv_delimiter);
                let write_result = writeln!(file, "{string_representation}");
                match write_result {
                    Ok(_) => println!("Successfully wrote to file."),
                    Err(e) => eprintln!("Failed to write to file: {}", e),
                }
            }
            Err(e) => {
                eprintln!("Failed to open file: {}", e);
            }
        }
    }

    pub(crate) fn esporta_pdf_niseci(&self, state: &mut Model, export_path: PathBuf) {
        self.add_console_message(
            state,
            format!("Esportazione pdf in {}", export_path.display()),
        );

        let risultato_niseci = state
            .data_model
            .get_risultato_niseci()
            .expect("Failed calculating NISECI before requesting export");

        let anagrafica_niseci = state
            .data_model
            .get_anagrafica_niseci()
            .expect("Failed getting AnagraficaNISECI before requesting export");

        let riferimento_niseci = state
            .data_model
            .get_riferimento_niseci()
            .expect("Failed getting RiferimentoNISECI before requesting export");

        esporta_pdf_niseci(
            export_path,
            riferimento_niseci,
            anagrafica_niseci,
            risultato_niseci,
        );
        self.set_done_export(state, true);
    }

    pub(crate) fn calc_hfbi(&self, state: &mut Model, locale: Localize) {
        let campionamento = state.data_model.get_campionamento_hfbi();
        let anagrafica = state.data_model.get_anagrafica_hfbi();

        let mut valid = true;

        if campionamento.is_none() {
            // Implementation error, this should never happen
            valid = false;
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: campionamento hfbi was None in calc_hfbi()".to_string(),
            );
        }
        if anagrafica.is_none() {
            // Implementation error, this should never happen
            valid = false;
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: anagrafica hfbi was None in calc_hfbi()".to_string(),
            );
        }

        if valid {
            let campionamento = campionamento.expect("calc_hfbi() checked is_none() before");
            let anagrafica = anagrafica.expect("calc_hfbi() checked is_none() before");

            match calculate_hfbi(&campionamento, &anagrafica) {
                Ok((hfbi, intermediates)) => {
                    self.add_console_message(state, format!("HFBI: {hfbi}"));

                    let stato_ecologico = calculate_stato_ecologico_hfbi(Some(hfbi));
                    let stato_ecologico_str = match stato_ecologico {
                        Some(val) => {
                            format!("{val}")
                        }
                        None => "NC".to_string(),
                    };
                    self.add_console_message(
                        state,
                        format!("Stato ecologico: {stato_ecologico_str}"),
                    );

                    let risultato_hfbi = RisultatoHFBI::new(Some(hfbi), intermediates.clone());

                    self.log_hfbi_values(
                        locale,
                        &anagrafica,
                        &risultato_hfbi,
                        &state
                            .fileinput_model
                            .get_campionamento_path()
                            .expect("Failed initialising campionamento hfbi path"),
                    );

                    //This logs to stdout
                    intermediates.log();
                    println!("HFBI: {hfbi}");

                    self.add_console_message(state, format!("{intermediates}"));

                    self.log_hfbi_intermediates(
                        locale,
                        &intermediates,
                        &state
                            .fileinput_model
                            .get_campionamento_path()
                            .expect("Failed initialising campionamento hfbi path"),
                        &anagrafica.codice_stazione,
                    );

                    self.set_data_risultato_hfbi(state, risultato_hfbi);
                    println!("OutputController: Finished HFBI calc");
                }
                Err(hfbi_errors) => {
                    self.add_console_message(
                        state,
                        format!("Errore durante il calcolo HFBI: {}", hfbi_errors),
                    );
                    state.data_model.set_errors_occurred(true);
                    state.output_model.set_done_calc(false);
                    state.data_model.set_risultato_hfbi(None);
                }
            }
        } else {
            self.add_console_message(
                state,
                "IMPLEMENTATION ERROR: spurious state in calc_hfbi()".to_string(),
            );
            state.data_model.set_errors_occurred(true);
        }
    }

    pub(crate) fn log_hfbi_values(
        &self,
        locale: Localize,
        anagrafica: &AnagraficaHFBI,
        risultato: &RisultatoHFBI,
        samp_filename: &Path,
    ) {
        let name = gen_logfile_name(samp_filename, &anagrafica.codice_stazione, true);
        let log_file_path;
        if let Some(dir) = self.prep_logfile_dir() {
            log_file_path = dir.join(name);
        } else {
            return;
        }
        let file_result = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(log_file_path);

        match file_result {
            Ok(mut file) => {
                let comma_csv_delimiter = match locale {
                    Localize::Italian => false,
                    Localize::International => true,
                };
                let string_representation = risultato.to_csv(anagrafica, comma_csv_delimiter);
                let write_result = writeln!(file, "{string_representation}");
                match write_result {
                    Ok(_) => println!("Successfully wrote to file."),
                    Err(e) => eprintln!("Failed to write to file: {}", e),
                }
            }
            Err(e) => {
                eprintln!("Failed to open file: {}", e);
            }
        }
    }

    pub(crate) fn log_hfbi_intermediates(
        &self,
        locale: Localize,
        intermediates: &ValoriIntermediHFBI,
        samp_filename: &Path,
        station_code: &str,
    ) {
        let name = gen_logfile_name(samp_filename, station_code, false);
        let log_file_path;
        if let Some(dir) = self.prep_logfile_dir() {
            log_file_path = dir.join(name);
        } else {
            return;
        }
        let file_result = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(log_file_path);

        match file_result {
            Ok(mut file) => {
                let comma_csv_delimiter = match locale {
                    Localize::Italian => false,
                    Localize::International => true,
                };
                let string_representation = intermediates.to_csv(comma_csv_delimiter);
                let write_result = writeln!(file, "{string_representation}");
                match write_result {
                    Ok(_) => println!("Successfully wrote to file."),
                    Err(e) => eprintln!("Failed to write to file: {}", e),
                }
            }
            Err(e) => {
                eprintln!("Failed to open file: {}", e);
            }
        }
    }

    pub(crate) fn esporta_pdf_hfbi(&self, state: &mut Model, export_path: PathBuf) {
        self.add_console_message(
            state,
            format!("Esportazione pdf in {}", export_path.display()),
        );

        let risultato_hfbi = self
            .get_data_risultato_hfbi(state)
            .expect("Failed calculating HFBI before requesting export");

        let anagrafica_hfbi = self
            .get_data_anagrafica_hfbi(state)
            .expect("Failed getting AnagraficaHFBI before requesting export");

        esporta_pdf_hfbi(export_path, anagrafica_hfbi, risultato_hfbi);
        self.set_done_export(state, true);
    }

    pub(crate) fn user_confirm_calc(&self, state: &mut Model) {
        state.output_model.set_done_user_confirm(true);
    }

    pub(crate) fn set_done_export(&self, state: &mut Model, val: bool) {
        state.output_model.set_done_export(val);
    }

    pub(crate) fn get_data_risultato_hfbi(&self, state: &Model) -> Option<RisultatoHFBI> {
        if self.get_is_done_calc(state) {
            state.data_model.get_risultato_hfbi()
        } else {
            None
        }
    }

    pub(crate) fn get_data_anagrafica_hfbi(&self, state: &Model) -> Option<AnagraficaHFBI> {
        state.data_model.get_anagrafica_hfbi()
    }

    fn set_data_risultato_hfbi(&self, state: &mut Model, risultato: RisultatoHFBI) {
        self.set_console_env(
            state,
            ("risultato_hfbi".to_string(), format!("{risultato}")),
        );
        state.data_model.set_risultato_hfbi(Some(risultato));
        state.output_model.set_done_calc(true);
    }

    pub(crate) fn prompt_reset(&self, state: &mut Model) {
        state.output_model.set_should_reset(true);
    }

    pub(crate) fn set_console_env(&self, state: &mut Model, (key, val): (String, String)) {
        state.console_model.console.set_env((key, val));
    }
}