use super::{
    BinBuildEnvironment, BinDescription, Calculator, FetchItem,
    GetCalibration, Item, Iteration, Result, Scope, SinkBin, SinkNames,
    SinkOnlyBin, SinkOnlyBinDescription,
};
use indexmap::{IndexMap, IndexSet};
use std::collections::VecDeque;

static BIN_TYPE: &'static str = "verificationsink";

pub struct Bin {
    scope: Scope,

    columns: IndexSet<String>,
    expected: VecDeque<Vec<Item>>,

    sources: IndexMap<String, Box<FetchItem>>,
}

impl SinkBin for Bin {}
impl SinkOnlyBin for Bin {}

impl Calculator for Bin {
    fn calculate(&mut self, iteration: &Iteration) -> Result<()> {
        let expected = self.expected.pop_front().unwrap();

        let expected = self
            .columns
            .iter()
            .map(String::to_string)
            .zip(expected.into_iter())
            .collect::<IndexMap<_, _>>();

        let received = self
            .sources
            .iter()
            .map(|(s, ds)| {
                ds.fetch_item(&self.scope).map(|d| (s.to_string(), d))
            })
            .collect::<Result<IndexMap<String, Item>>>()?;

        assert_eq!(received, expected, "iteration: {:?}", iteration);
        Ok(())
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Description {
    pub columns: IndexSet<String>,
    pub expected: VecDeque<Vec<Item>>,
}

impl BinDescription for Description {
    type Bin = Bin;

    fn check_validity(
        &self,
        _scope: &Scope,
        _get_calibration: &mut GetCalibration,
    ) -> Result<()> {
        Ok(())
    }

    fn bin_type(&self) -> &'static str {
        BIN_TYPE
    }
}

impl SinkNames for Description {
    fn sink_names(&self) -> IndexSet<String> {
        self.columns.iter().map(String::to_string).collect()
    }
}

impl SinkOnlyBinDescription for Description {
    fn build_bin(
        &self,
        scope: &Scope,
        env: &mut BinBuildEnvironment,
    ) -> Result<Self::Bin> {
        Ok(Bin {
            scope: scope.clone(),
            columns: self.columns.clone(),
            expected: self.expected.clone(),
            sources: self
                .columns
                .iter()
                .map(|s| env.resolve(s).map(|ds| (s.to_string(), ds)))
                .collect::<Result<IndexMap<_, _>>>()?,
        })
    }
}
