use super::{CalibrationSource, Result, Scope};
use crate::{error, R64};
use indexmap::IndexMap;
use snafu::ensure;

#[derive(PartialEq, Debug)]
pub enum Direction {
    Incline,
    Decline,
}

pub trait HasReverse {
    fn reversed(&self) -> Self;
}

impl HasReverse for IndexMap<R64, R64> {
    fn reversed(&self) -> Self {
        self.iter()
            .map(|(k, v)| (v.clone(), k.clone()))
            .collect::<IndexMap<R64, R64>>()
    }
}

pub trait HasDirection {
    fn determine_direction(&self) -> Option<Direction>;
    fn check_direction(
        &self,
        scope: &Scope,
        calibration: &CalibrationSource,
    ) -> Result<()> {
        ensure!(
            self.determine_direction().is_some(),
            error::InvalidCalibrationCurve {
                scope: scope.clone(),
                calibration: calibration.clone(),
            }
        );
        Ok(())
    }
}

impl HasDirection for IndexMap<R64, R64> {
    fn determine_direction(&self) -> Option<Direction> {
        let mut res = None;
        let mut last_item: Option<R64> = None;
        let mut cloned = self.clone();
        cloned.sort_keys();
        for v in cloned.into_iter().map(|(_k, v)| v) {
            if let Some(last_value) = last_item {
                if v == last_value {
                    return None;
                } else if v > last_value {
                    if res == None {
                        res = Some(Direction::Incline);
                    } else if res == Some(Direction::Decline) {
                        return None;
                    }
                } else if v < last_value {
                    if res == None {
                        res = Some(Direction::Decline);
                    } else if res == Some(Direction::Incline) {
                        return None;
                    }
                }
            }
            last_item = Some(v);
        }
        res
    }
}

#[cfg(test)]
mod tests {
    use super::{Direction, HasDirection};
    use crate::R64;
    use indexmap::IndexMap;

    #[test]
    fn determine_direction() {
        let map = [(0f64, 0f64), (1f64, 1f64), (2f64, 2f64)]
            .into_iter()
            .map(|&(x, y)| (R64::from(x), R64::from(y)))
            .collect::<IndexMap<R64, R64>>();
        assert_eq!(map.determine_direction(), Some(Direction::Incline));

        let map = [(0f64, 0f64), (1f64, 1f64), (2f64, 0f64)]
            .into_iter()
            .map(|&(x, y)| (R64::from(x), R64::from(y)))
            .collect::<IndexMap<R64, R64>>();
        assert_eq!(map.determine_direction(), None);

        let map = [(0f64, 1f64), (1f64, 0f64), (2f64, 1f64)]
            .into_iter()
            .map(|&(x, y)| (R64::from(x), R64::from(y)))
            .collect::<IndexMap<R64, R64>>();
        assert_eq!(map.determine_direction(), None);

        let map = [(0f64, 2f64), (1f64, 1f64), (2f64, 0f64)]
            .into_iter()
            .map(|&(x, y)| (R64::from(x), R64::from(y)))
            .collect::<IndexMap<R64, R64>>();
        assert_eq!(map.determine_direction(), Some(Direction::Decline));
    }
}
