use crate::trend_value::TrendValue;

#[derive(Debug, Clone)]
pub struct TrendMetrics {
    pub short_term_val: TrendValue,
    pub long_term_val: TrendValue,
    pub current_value: Option<f64>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TrendType {
    StrongUp,
    WeakUp,
    StrongDown,
    WeakDown,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CrossOverType {
    GoldenCross,
    DeadCross,
    None,
}

impl TrendMetrics {
    pub fn new(short_period: usize, long_period: usize) -> Self {
        Self {
            short_term_val: TrendValue::new(short_period),
            long_term_val: TrendValue::new(long_period),
            current_value: None,
        }
    }

    pub fn update(&mut self, new_value: f64, short_value: f64, long_value: f64) {
        self.current_value = Some(new_value);
        self.short_term_val.update_value(short_value);
        self.long_term_val.update_value(long_value);
    }

    pub fn trend_type(&self) -> TrendType {
        let short_term_ema = self.short_term_val.current_ema();
        let long_term_ema = self.long_term_val.current_ema();

        match (
            short_term_ema > long_term_ema,
            self.current_value.unwrap_or_default() > short_term_ema,
        ) {
            (true, true) => TrendType::StrongUp,
            (true, false) => TrendType::WeakUp,
            (false, false) => TrendType::StrongDown,
            (false, true) => TrendType::WeakDown,
        }
    }

    pub fn is_crossover(&self) -> CrossOverType {
        // Short term crosses above long term
        if self.short_term_val.current_ema() > self.long_term_val.current_ema()
            && self.short_term_val.previous_ema() <= self.long_term_val.previous_ema()
        {
            return CrossOverType::GoldenCross;
        }

        // Short term crosses below long term
        if self.short_term_val.current_ema() < self.long_term_val.current_ema()
            && self.short_term_val.previous_ema() >= self.long_term_val.previous_ema()
        {
            return CrossOverType::DeadCross;
        }

        CrossOverType::None
    }
}
