Documentation
// Copyright 2019 YechaoLi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{collections::btree_map::BTreeMap, fmt};

#[derive(Debug, PartialEq)]
pub struct ValidationErrorItem {
    pub code: u64,
    pub message: String,
}

#[derive(Debug, PartialEq)]
pub enum ValidationError {
    Err(ValidationErrorItem),
    Map(BTreeMap<String, ValidationError>),
    List(BTreeMap<u64, ValidationError>),
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.first()
                .as_ref()
                .map(|x| x.message.as_str())
                .unwrap_or("empty validation error")
        )
    }
}

impl std::error::Error for ValidationError {}

impl ValidationError {
    pub fn is_empty(&self) -> bool {
        match self {
            ValidationError::Err(_) => false,
            ValidationError::Map(m) => m.is_empty(),
            ValidationError::List(l) => l.is_empty(),
        }
    }

    pub fn first(&self) -> Option<&ValidationErrorItem> {
        match self {
            ValidationError::Err(e) => Some(e),
            ValidationError::Map(m) => m.iter().next().map(|(_, x)| x.first()).unwrap_or(None),
            ValidationError::List(l) => l.iter().next().map(|(_, x)| x.first()).unwrap_or(None),
        }
    }
}