use simd_json::OwnedValue as Value;
use simd_json::StaticNode;
use std::fmt;

#[derive(Debug, Clone)]
pub enum FilterError {
    Parse(ParseError),
    Eval(EvalError),
}

#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    pub message: String,
    pub position: usize,
}

#[derive(Debug, Clone)]
pub enum EvalError {
    CannotIterate { value: Value, position: usize },
    TypeError { message: String, position: usize },
}

impl fmt::Display for FilterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FilterError::Parse(e) => write!(f, "{}", e.message),
            FilterError::Eval(e) => write!(f, "{}", e),
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl EvalError {
    pub fn position(&self) -> usize {
        match self {
            EvalError::CannotIterate { position, .. } => *position,
            EvalError::TypeError { position, .. } => *position,
        }
    }

    pub fn set_position(&mut self, pos: usize) {
        match self {
            EvalError::CannotIterate { position, .. } => *position = pos,
            EvalError::TypeError { position, .. } => *position = pos,
        }
    }
}

impl fmt::Display for EvalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EvalError::CannotIterate { value, .. } => {
                let type_name = match value {
                    Value::Static(StaticNode::Null) => "null",
                    Value::Static(StaticNode::Bool(_)) => "boolean",
                    Value::Static(StaticNode::I64(_) | StaticNode::U64(_) | StaticNode::F64(_)) => {
                        "number"
                    }
                    Value::String(_) => "string",
                    Value::Array(_) => "array",
                    Value::Object(_) => "object",
                };
                write!(f, "cannot iterate over {}", type_name)
            }
            EvalError::TypeError { message, .. } => {
                write!(f, "{}", message)
            }
        }
    }
}
