// License: see LICENSE file at root directory of `master` branch

//! # Range

#![deprecated(note = "Beta")]

mod impls;
mod kind;

use {
    core::{
        fmt::{self, Display, Formatter},
        ops::RangeInclusive,
    },

    crate::Semver,

    self::kind::Kind,
};

/// # Range
///
/// A range can be respresented in string, following these rules:
///
/// - Start and end are placed inside one of `[]`, `[)`..., separated by a comma.
/// - `[` and `]` are inclusive.
/// - `(` and `)` are exclusive.
/// - White spaces can be included. They will be ignored by parser.
/// - Length of the string must be equal to or smaller than 4096 bytes. It's for protection against flood attack.
///
/// ## Notes
///
/// Large ranges, such as `[,]`, `(,)`, [`start,`], [`,end`]... are not supported. Technically it's doable, but using such wild ranges in
/// software development is not recommended.
///
/// ## Examples
///
/// ```
/// use core::str::FromStr;
/// use dia_semver::{Range, Semver};
///
/// // An empty range
/// let range = Range::from(Semver::new(0, 1, 2)..Semver::new(0, 0, 0));
/// assert!(range.is_empty());
///
/// // Only one single semver
/// let range = Range::from(Semver::new(0, 1, 2));
/// assert!(range.contains(&Semver::new(0, 1, 2)));
/// assert!(range.contains(&Semver::new(0, 1, 3)) == false);
///
/// // Inclusive range
/// let range = Range::from_str("[0.1.2, 0.2.0-beta]")?;
/// assert!(range.contains(&Semver::new(0, 1, 3)));
/// assert!(range.contains(&Semver::from_str("0.2.0-alpha")?));
/// assert!(range.contains(&Semver::new(0, 2, 0)) == false);
///
/// // Exclusive range
/// let range = Range::from(Semver::new(0, 1, 2)..Semver::new(0, 2, 0));
/// assert!(range.contains(&Semver::new(0, 2, 0)) == false);
///
/// # dia_semver::Result::Ok(())
/// ```
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Range {
    kind: Kind,
}

impl Range {

    /// # Checks if this range is empty
    pub fn is_empty(&self) -> bool {
        match &self.kind {
            Kind::InclusiveInclusive(range) => range.is_empty(),
            Kind::InclusiveExclusive(range) => range.start() >= range.end(),
            Kind::ExclusiveExclusive(range) => range.start() >= range.end(),
            Kind::ExclusiveInclusive(range) => range.start() >= range.end(),
        }
    }

    /// # Checks if this range contains a semver
    pub fn contains(&self, semver: &Semver) -> bool {
        match &self.kind {
            Kind::InclusiveInclusive(range) => range.contains(semver),
            Kind::InclusiveExclusive(range) => semver >= range.start() && semver < range.end(),
            Kind::ExclusiveExclusive(range) => semver > range.start() && semver < range.end(),
            Kind::ExclusiveInclusive(range) => semver > range.start() && semver <= range.end(),
        }
    }

}

impl From<&Semver> for Range {

    fn from(semver: &Semver) -> Self {
        Self {
            kind: Kind::InclusiveInclusive(RangeInclusive::new(semver.clone(), semver.clone())),
        }
    }

}

impl From<Semver> for Range {

    fn from(semver: Semver) -> Self {
        Self::from(&semver)
    }

}

impl From<core::ops::Range<Semver>> for Range {

    fn from(range: core::ops::Range<Semver>) -> Self {
        Self {
            kind: Kind::InclusiveExclusive(RangeInclusive::new(range.start, range.end)),
        }
    }

}

impl From<RangeInclusive<Semver>> for Range {

    fn from(range: RangeInclusive<Semver>) -> Self {
        Self {
            kind: Kind::InclusiveInclusive(range),
        }
    }

}

impl Display for Range {

    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        const INCLUSIVE_OPEN: char = '[';
        const INCLUSIVE_CLOSE: char = ']';
        const EXCLUSIVE_OPEN: char = '(';
        const EXCLUSIVE_CLOSE: char = ')';

        let (open, start, end, close) = match &self.kind {
            Kind::InclusiveInclusive(range) => (INCLUSIVE_OPEN, range.start(), range.end(), INCLUSIVE_CLOSE),
            Kind::InclusiveExclusive(range) => (INCLUSIVE_OPEN, range.start(), range.end(), EXCLUSIVE_CLOSE),
            Kind::ExclusiveExclusive(range) => (EXCLUSIVE_OPEN, range.start(), range.end(), EXCLUSIVE_CLOSE),
            Kind::ExclusiveInclusive(range) => (EXCLUSIVE_OPEN, range.start(), range.end(), INCLUSIVE_CLOSE),
        };

        write!(
            f,
            concat!("{open}", "{start}", ',', ' ', "{end}", "{close}"),
            open=open,
            start=start.to_short_format(),
            end=end.to_short_format(),
            close=close,
        )
    }

}
