use std::{cmp::Ordering, rc::Rc};

use rug::Float;

use super::{
    constant::Constant, set::Set, string_node::StringNode, Environment, Error, Node, NodeEnum, Precedence
};

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Add {
    left: Rc<NodeEnum>,
    right: Rc<NodeEnum>,
}

impl Node for Add {
    fn evaluate(&self, env: &mut Environment) -> Result<Rc<NodeEnum>, Error> {
        let evaluated_left = self.left.evaluate(env)?;
        let evaluated_right = self.right.evaluate(env)?;

        match (evaluated_left.as_ref(), evaluated_right.as_ref()) {
            // Zero rule
            (NodeEnum::Constant(zero), _) if zero.get_value() == &0.0 => Ok(evaluated_right),
            (_, NodeEnum::Constant(zero)) if zero.get_value() == &0.0 => Ok(evaluated_left),

            // Constant + Constant = Constant
            (NodeEnum::Constant(a), NodeEnum::Constant(b)) => Ok(Rc::new(
                Constant::new(Float::with_val_64(
                    env.get_float_precision(),
                    a.get_value() + b.get_value(),
                ))
                .into(),
            )),

            // Move constants after symbols in add
            (NodeEnum::Constant(_), NodeEnum::Symbol(_)) => {
                Ok(Rc::new(Add::new(evaluated_right, evaluated_left).into()))
            }

            // Concatenate sets
            (NodeEnum::Set(s1), NodeEnum::Set(s2)) => {
                let values = {
                    let mut v = s1.get_values().clone();
                    v.append(&mut s2.get_values().clone());
                    v
                };
                Ok(Set::new(values))
            }

            // Concatenate strings
            (NodeEnum::StringNode(s1), NodeEnum::StringNode(s2)) => {
                Ok(StringNode::new(s1.get_value().clone() + s2.get_value()))
            }

            (NodeEnum::Add(add), o) | (o, NodeEnum::Add(add)) => {
                // Aggregate into a single vector for easy sorting
                let mut aggregate = vec![];
                let mut queue = vec![];
                queue.push(Rc::new(o.clone()));
                let mut c: Rc<NodeEnum> = Rc::new(add.clone().into());

                loop {
                    match c.as_ref() {
                        NodeEnum::Add(m) => {
                            queue.push(m.get_left());
                            queue.push(m.get_right());
                        }
                        _ => {
                            aggregate.push(c.clone());
                        }
                    }

                    if !queue.is_empty() {
                        c = queue.pop().unwrap();
                    } else {
                        break;
                    }
                }

                aggregate.sort_by(|a, b| match (a.as_ref(), b.as_ref()) {
                    (_, NodeEnum::Constant(_)) => Ordering::Less,
                    (NodeEnum::Constant(_), _) => Ordering::Greater,
                    (NodeEnum::Symbol(s1), NodeEnum::Symbol(s2)) => s1.cmp(s2),
                    _ => a.partial_cmp(b).unwrap_or(Ordering::Equal)
                });

                let mut constant = Rc::new(Constant::new_from_float(0.0, &env).into());
                let mut constanted = false;

                while let Some(agr) = aggregate.last() {
                    if let NodeEnum::Constant(_) = agr.as_ref() {
                        constanted = true;
                        constant =
                            Add::new_rc(constant, aggregate.pop().unwrap());
                    } else {
                        break;
                    }
                }

                let mut out = aggregate.pop().unwrap();

                while let Some(a) = aggregate.pop() {
                    out = Add::new_rc(out, a);
                }

                if constanted {
                    Ok(Add::new_rc(constant.evaluate(env)?, out))
                } else {
                    Ok(out)
                }
            }

            _ => Ok(Rc::new(Add::new(evaluated_left, evaluated_right).into())),
        }
    }

    fn as_string(&self, env: Option<&Environment>) -> String {
        let left_string = if let NodeEnum::Add(_) = self.left.as_ref() {
            self.left.as_string(env)
        } else if self.left.precedence() <= self.precedence() {
            format!("({})", self.left.as_string(env))
        } else {
            self.left.as_string(env)
        };
        let right_string = if let NodeEnum::Add(_) = self.right.as_ref() {
            self.right.as_string(env)
        } else if self.right.precedence() <= self.precedence() {
            format!("({})", self.right.as_string(env))
        } else {
            self.right.as_string(env)
        };
        format!("{}+{}", left_string, right_string)
    }

    fn precedence(&self) -> Precedence {
        Precedence::Term
    }
}

impl Add {
    pub fn new(left: Rc<NodeEnum>, right: Rc<NodeEnum>) -> Self {
        Self { left, right }
    }

    pub fn new_rc(left: Rc<NodeEnum>, right: Rc<NodeEnum>) -> Rc<NodeEnum> {
        Rc::new(Self { left, right }.into())
    }

    pub fn get_left(&self) -> Rc<NodeEnum> {
        self.left.clone()
    }

    pub fn get_right(&self) -> Rc<NodeEnum> {
        self.right.clone()
    }
}
