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
use crate::{
    errors::BufkitDataErr,
    models::Model,
    site::{StateProv, StationNumber},
};
use chrono::FixedOffset;
use std::{collections::HashMap, str::FromStr};

/// A summary of the information about a station.
#[derive(Debug)]
pub struct StationSummary {
    /// Station number
    pub station_num: StationNumber,
    /// List of ids associated with this site
    pub ids: Vec<String>,
    /// All the models in the archive associated with this site
    pub models: Vec<Model>,
    /// Station name, common name
    pub name: Option<String>,
    /// Notes related to the site
    pub notes: Option<String>,
    /// The state-province associated with the site.
    pub state: Option<StateProv>,
    /// The time zone offset to local standard time.
    pub time_zone: Option<FixedOffset>,
    /// The number of files in the archive related to this site.
    pub number_of_files: u32,
}

struct StationEntry {
    station_num: StationNumber,
    id: Option<String>,
    model: Option<Model>,
    name: Option<String>,
    notes: Option<String>,
    state: Option<StateProv>,
    time_zone: Option<FixedOffset>,
    number_of_files: u32,
}

impl StationSummary {
    /// Concantenate the ids into a comma separated list.
    pub fn ids_as_string(&self) -> String {
        self.ids.join(", ")
    }

    /// Concatenate the models into a comma separated list.
    pub fn models_as_string(&self) -> String {
        self.models
            .iter()
            .map(|m| m.as_static_str().to_owned())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

impl From<StationEntry> for StationSummary {
    fn from(entry: StationEntry) -> Self {
        let StationEntry {
            station_num,
            id,
            model,
            name,
            notes,
            state,
            time_zone,
            number_of_files,
        } = entry;

        let mut models = vec![];
        if let Some(model) = model {
            models.push(model);
        }

        let mut ids = vec![];
        if let Some(id) = id {
            ids.push(id);
        }

        StationSummary {
            station_num,
            ids,
            models,
            name,
            notes,
            state,
            time_zone,
            number_of_files,
        }
    }
}

impl crate::Archive {
    /// Get a summary of all the stations in the archive.
    pub fn station_summaries(&self) -> Result<Vec<StationSummary>, BufkitDataErr> {
        let mut vals: HashMap<StationNumber, StationSummary> = HashMap::new();

        let mut stmt = self.db_conn.prepare(include_str!("station_summary.sql"))?;

        stmt.query_and_then([], Self::parse_row_to_entry)?
            .for_each(|stn_entry| {
                if let Ok(stn_entry) = stn_entry {
                    if let Some(summary) = vals.get_mut(&stn_entry.station_num) {
                        if let Some(id) = stn_entry.id {
                            summary.ids.push(id);
                        }

                        if let Some(model) = stn_entry.model {
                            summary.models.push(model);
                        }

                        summary.number_of_files += stn_entry.number_of_files;
                    } else {
                        vals.insert(stn_entry.station_num, StationSummary::from(stn_entry));
                    }
                }
            });

        let mut vals: Vec<StationSummary> = vals.into_iter().map(|(_, v)| v).collect();

        vals.iter_mut().for_each(|summary| {
            summary.ids.sort_unstable();
            summary.ids.dedup();
            summary.models.sort_unstable();
            summary.models.dedup();
        });

        Ok(vals)
    }

    fn parse_row_to_entry(row: &rusqlite::Row) -> Result<StationEntry, rusqlite::Error> {
        let station_num: StationNumber = row.get::<_, u32>(0).map(StationNumber::from)?;
        let id: Option<String> = row.get(1)?;

        let model: Option<Model> = row.get::<_, Option<String>>(2).and_then(|string_opt| {
            string_opt
                .map(|string| Model::from_str(&string).map_err(|_| rusqlite::Error::InvalidQuery))
                .transpose()
        })?;

        let name: Option<String> = row.get(3)?;

        let state: Option<StateProv> = row
            .get::<_, String>(4)
            .ok()
            .and_then(|a_string| StateProv::from_str(&a_string).ok());

        let notes: Option<String> = row.get(5)?;

        let time_zone: Option<chrono::FixedOffset> =
            row.get::<_, i32>(6).ok().map(|offset: i32| {
                if offset < 0 {
                    chrono::FixedOffset::west(offset.abs())
                } else {
                    chrono::FixedOffset::east(offset)
                }
            });

        let number_of_files: u32 = row.get(7)?;

        Ok(StationEntry {
            station_num,
            id,
            model,
            name,
            state,
            notes,
            time_zone,
            number_of_files,
        })
    }
}

#[cfg(test)]
mod unit {
    use crate::archive::unit::*; // test helpers.
    use crate::{Model, StationNumber};

    #[test]
    fn test_summaries() {
        let TestArchive {
            tmp: _tmp,
            mut arch,
        } = create_test_archive().expect("Failed to create test archive.");

        fill_test_archive(&mut arch);

        let sums = arch.station_summaries().unwrap();

        for sum in sums {
            println!("{:?}", sum);

            assert_eq!(sum.ids.len(), 1);
            assert_eq!(sum.ids[0], "KMSO");

            assert_eq!(sum.models.len(), 2);
            assert!(sum.models.contains(&Model::GFS));
            assert!(sum.models.contains(&Model::NAM));

            assert_eq!(sum.station_num, StationNumber::new(727730));
            assert_eq!(sum.number_of_files, 6);
            assert!(sum.name.is_none());
            assert!(sum.notes.is_none());
            assert!(sum.time_zone.is_none());
            assert!(sum.state.is_none());
        }
    }
}