use super::{
    build_names, sink_names_trigger, BinBuildEnvironment, BinDescription,
    Calculator, FetchItem, GetCalibration, Item, Iteration, Result, Scope,
    SinkBin, SinkNames, SourceBin, SourceId, SourceNames,
    SourceSinkBinDescription, WriteDotSimple, SINK_TRIGGER,
};
use crate::error;
use indexmap::{IndexMap, IndexSet};
use snafu::OptionExt;

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

pub struct Bin {
    scope: Scope,
    source_trigger: Box<FetchItem>,
    outputs: IndexMap<String, Item>,
}

impl SinkBin for Bin {}

impl SourceBin for Bin {
    fn get_source_data(&self, source: &SourceId) -> Result<Item> {
        self.outputs
            .get(&source.id)
            .context(error::MissingSourceName {
                scope: self.scope.clone(),
                name: source.id.to_string(),
                bin_type: BIN_TYPE.to_string(),
            })
            .map(Clone::clone)
    }
}

impl Calculator for Bin {
    fn calculate(&mut self, _iteration: &Iteration) -> Result<()> {
        self.source_trigger.fetch_item(&self.scope)?;
        Ok(())
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Description {
    pub values: IndexMap<String, 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> {
        sink_names_trigger()
    }
}

impl SourceNames for Description {
    fn source_names(&self) -> Result<IndexSet<String>> {
        Ok(build_names(&self.values.keys().collect::<Vec<_>>()))
    }
}

impl SourceSinkBinDescription for Description {
    fn build_bin(
        &self,
        scope: &Scope,
        env: &mut BinBuildEnvironment,
    ) -> Result<Self::Bin> {
        Ok(Bin {
            scope: scope.clone(),
            source_trigger: env.resolve(SINK_TRIGGER)?,
            outputs: self.values.clone(),
        })
    }
}

impl WriteDotSimple for Description {}
