//! Cache of the most recently received reports.

use std::collections::HashMap;

use log::error;

use protocol::{Location, Value, ValueType};

/// Cache of the most recently received reports.
///
/// To remove the need to query MQTT/InfluxDB, this struct holds the most recently received reports
/// from the sensors.
pub struct CurrentValues {
    map: HashMap<Key, i64>,
}

impl CurrentValues {
    pub fn new() -> CurrentValues {
        CurrentValues {
            map: HashMap::new(),
        }
    }

    pub fn set(&mut self, location: Location, value: Value) {
        let (type_, value) = match value.split() {
            Some(x) => x,
            None => {
                error!("Invalid value passed to CurrentValues::set().");
                return;
            }
        };
        self.map.insert(Key { location, type_ }, value);
    }

    pub fn get(&self, location: Location, type_: ValueType) -> Option<Value> {
        let entry = self.map.get(&Key { location, type_ })?.clone();
        Some(Value::combine(type_, entry))
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash)]
struct Key {
    location: Location,
    type_: ValueType,
}
