use std::fmt;

/// A specialized `Result` type for fwf operations.
pub type Result<T> = std::result::Result<T, FwfError>;

/// Errors that can occur when building or using a reader or writer.
#[derive(Debug)]
#[non_exhaustive]
pub enum FwfError {
    /// A field range exceeds the record width.
    #[non_exhaustive]
    FieldOutOfBounds {
        /// The field index in the schema.
        field_index: usize,
    },
    /// An I/O error occurred while reading.
    Io(std::io::Error),
    /// The source ended with an incomplete record.
    #[non_exhaustive]
    IncompleteRecord {
        /// Number of bytes read in the partial record.
        bytes_read: usize,
        /// Expected record width.
        expected: usize,
    },
    /// The source ended with an incomplete record separator.
    #[non_exhaustive]
    IncompleteSeparator {
        /// Number of bytes read in the partial separator.
        bytes_read: usize,
        /// Expected separator length.
        expected: usize,
    },
    /// The bytes read as a record separator did not match the expected separator.
    InvalidSeparator,
    /// An error occurred while decoding bytes to a string.
    #[cfg(feature = "encoding_rs")]
    #[non_exhaustive]
    Encoding {
        /// The field index that failed to decode.
        field_index: usize,
    },
    /// A value exceeds the field width, and the truncation policy is [`Error`](crate::TruncationPolicy::Error).
    #[non_exhaustive]
    ValueTooLong {
        /// The field index whose value was too long.
        field_index: usize,
        /// The byte length of the value.
        value_len: usize,
    },
    /// The number of values provided does not match the expected count.
    #[non_exhaustive]
    ValueCountMismatch {
        /// The number of values provided.
        provided: usize,
        /// The number of values expected.
        expected: usize,
    },
}

impl fmt::Display for FwfError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FieldOutOfBounds { field_index } => {
                write!(f, "field {field_index} range exceeds record width")
            }
            Self::Io(err) => write!(f, "{err}"),
            Self::IncompleteRecord {
                bytes_read,
                expected,
            } => {
                write!(
                    f,
                    "incomplete record: read {bytes_read} bytes, expected {expected}"
                )
            }
            Self::IncompleteSeparator {
                bytes_read,
                expected,
            } => {
                write!(
                    f,
                    "incomplete separator: read {bytes_read} bytes, expected {expected}"
                )
            }
            Self::InvalidSeparator => {
                write!(f, "invalid record separator")
            }
            #[cfg(feature = "encoding_rs")]
            Self::Encoding { field_index } => {
                write!(f, "failed to decode field {field_index}")
            }
            Self::ValueTooLong {
                field_index,
                value_len,
            } => {
                write!(
                    f,
                    "value for field {field_index} is {value_len} bytes, exceeds field width"
                )
            }
            Self::ValueCountMismatch { provided, expected } => {
                write!(f, "provided {provided} values, expected {expected}")
            }
        }
    }
}

impl std::error::Error for FwfError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(err) => Some(err),
            _ => None,
        }
    }
}

impl From<std::io::Error> for FwfError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}
