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
#![allow(mixed_script_confusables)]
use std::io::{Read, Seek};

use calamine::Reader;

#[derive(Debug)]
pub struct Range {
    pub from: (u8, u8, u16),
    pub to: (u8, u8, u16),
}

/// The italian electrical system bills usage for three different time ranges
#[derive(Debug)]
pub enum Rate {
    /// Monday to friday, 08:00 to 19:00
    F1,
    /// Monday to friday, 19:00 to 08:00
    F2,
    /// Weekends and holidays
    F3,
}

/// Prices for electricity usage
#[derive(Debug)]
pub struct Rates {
    /// When these prices are into effect
    pub validity: Range,
    /// Energy (for meters thath cannot measure time ranges, €/kWh)
    pub pe_single_rate: f32,
    /// Energy (€/kWh)
    pub pe: [(Rate, f32); 3],
    /// Dispatch costs (€/kWh)
    pub pd: f32,
    /// Marketing and selling
    pub pcv: f32,
    /// Dispatch component
    pub disp_bt: f32,
    /// Adjustment component
    pub ppe: f32,
    /// Fixed costs for metering (€/yr)
    pub σ1: f32,
    /// Power reservation fee (€/kW/yr)
    pub σ2: f32,
    /// Management fees (€/kWh)
    pub σ3: f32,
    /// Adjustment fees (€/kWh)
    pub uc3: f32,
    /// Network improvement fees (€/kWh; €/kW/yr)
    pub uc6: [f32; 2],
    ///
    pub asos: f32,
    pub arim: f32,
}

fn load_households_generic_wb<R: Read + Seek>(reader: R, offset: u8) -> Vec<Rates> {
    let mut workbook: calamine::Xls<R> = calamine::Xls::new(reader).expect("Could not parse file");
    let sheets: Vec<_> = workbook.sheet_names().into_iter().collect();
    sheets
        .into_iter()
        .map(|x| {
            load_households_generic_sheet(
                workbook.worksheet_range(&x).expect("Sheet not found"),
                offset,
            )
        })
        .filter(|x| x.validity.from.2 >= 2018)
        .collect()
}

fn value_to_float(v: &calamine::Data) -> f32 {
    match v {
        calamine::Data::Float(x) => *x as f32,
        _ => panic!("Trying to convert {:?} to float...", v),
    }
}
fn value_to_string(v: &calamine::Data) -> String {
    match v {
        calamine::Data::String(x) => x.clone(),
        _ => panic!("Trying to convert {:?} to float...", v),
    }
}

fn month_to_number(month: &str) -> u8 {
    match month {
        "gennaio" => 1,
        "febbraio" => 2,
        "marzo" => 3,
        "aprile" => 4,
        "maggio" => 5,
        "giugno" => 6,
        "luglio" => 7,
        "agosto" => 8,
        "settembre" => 9,
        "ottobre" => 10,
        "novembre" => 11,
        "dicembre" => 12,
        _ => 0,
    }
}

fn load_households_generic_sheet(sheet: calamine::Range<calamine::Data>, offset: u8) -> Rates {
    let row = offset as usize + 18
        - if let calamine::Data::Float(_) = sheet.get((offset as usize + 18, 1)).unwrap() {
            0
        } else {
            1
        };
    let row_offset = if let calamine::Data::Empty = sheet.get((row + 1, 5)).unwrap() {
        2
    } else {
        1
    };

    let range_string = value_to_string(sheet.get((row - 3, 0)).expect("Failed to extract date"));
    let mut splitted = range_string.split(' ');
    let starting_day = splitted.next().unwrap().parse::<u8>().unwrap();
    let starting_month = splitted.next().map(month_to_number).unwrap();
    splitted.next();
    let ending_day = splitted.next().unwrap().parse::<u8>().unwrap();
    let ending_month = splitted.next().map(month_to_number).unwrap();
    let year = splitted.next().unwrap().parse::<u16>().unwrap();

    Rates {
        validity: Range {
            from: (starting_day, starting_month, year),
            to: (ending_day, ending_month, year),
        },
        pe_single_rate: value_to_float(sheet.get((row, 1)).expect("Failed to parse field")),
        pe: [
            (
                Rate::F1,
                value_to_float(sheet.get((row, 2)).expect("Failed to parse field")),
            ),
            (
                Rate::F2,
                value_to_float(sheet.get((row, 3)).expect("Failed to parse field")),
            ),
            (
                Rate::F3,
                value_to_float(sheet.get((row, 3)).expect("Failed to parse field")),
            ),
        ],
        pd: value_to_float(sheet.get((row, 4)).expect("Failed to parse field")),
        pcv: value_to_float(
            sheet
                .get((row + row_offset, 5))
                .expect("Failed to parse field"),
        ),
        disp_bt: value_to_float(
            sheet
                .get((row + row_offset, 6))
                .expect("Failed to parse field"),
        ),
        ppe: value_to_float(sheet.get((row, 7)).expect("Failed to parse field")),
        σ1: value_to_float(
            sheet
                .get((row + row_offset, 11))
                .expect("Failed to parse field"),
        ),
        σ2: value_to_float(
            sheet
                .get((row + row_offset + 1, 12))
                .expect("Failed to parse field"),
        ),
        σ3: value_to_float(sheet.get((row, 13)).expect("Failed to parse field")),
        uc3: value_to_float(sheet.get((row, 14)).expect("Failed to parse field")),
        uc6: [
            value_to_float(sheet.get((row, 15)).expect("Failed to parse field")),
            value_to_float(
                sheet
                    .get((row + row_offset + 1, 15))
                    .expect("Failed to parse field"),
            ),
        ],
        asos: value_to_float(sheet.get((row, 17)).expect("Failed to parse field")),
        arim: value_to_float(sheet.get((row, 18)).expect("Failed to parse field")),
    }
}

/// Load rates for first houses
pub fn load_first_household_rates<R: Read + Seek>(reader: R) -> Vec<Rates> {
    load_households_generic_wb(reader, 0)
}

#[cfg(test)]
mod tests {}