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

//! # `FromStr`

use {
    core::{
        ops::RangeInclusive,
        str::FromStr,
    },

    crate::{
        ParseSemverError, Semver, SemverErrorKind, Range,
        range::Kind,
    },
};

/// # Mark size in bytes
const MARK_SIZE: usize = 1;

#[derive(Debug)]
enum Mark {
    Inclusive,
    Exclusive,
}

#[test]
fn test_mark() {
    for c in &['[', ']', '(', ')'] {
        assert_eq!(c.len_utf8(), MARK_SIZE);
    }
}

impl FromStr for Range {

    type Err = ParseSemverError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const MAX_LEN: usize = 4096;

        if s.len() > MAX_LEN {
            return Err(ParseSemverError {
                kind: SemverErrorKind::Other(alloc::format!("String is too long, max length supported: {} bytes", MAX_LEN)),
            });
        }

        let err = || ParseSemverError {
            kind: SemverErrorKind::Other(alloc::format!("Invalid range: {:?}", s)),
        };

        let open_mark = match s.chars().next() {
            Some('[') => Mark::Inclusive,
            Some('(') => Mark::Exclusive,
            _ => return Err(err()),
        };
        let close_mark = if s.ends_with(']') {
            Mark::Inclusive
        } else if s.ends_with(')') {
            Mark::Exclusive
        } else {
            return Err(err());
        };

        let mut parts = s[MARK_SIZE .. s.len() - MARK_SIZE].trim().split(',');
        match (parts.next().map(|from| Semver::from_str(from)), parts.next().map(|to| Semver::from_str(to)), parts.next()) {
            (Some(Ok(from)), Some(Ok(to)), None) => {
                let range = RangeInclusive::new(from, to);
                match (open_mark, close_mark) {
                    (Mark::Inclusive, Mark::Inclusive) => Ok(Self {
                        kind: Kind::InclusiveInclusive(range),
                    }),
                    (Mark::Inclusive, Mark::Exclusive) => Ok(Self {
                        kind: Kind::InclusiveExclusive(range),
                    }),
                    (Mark::Exclusive, Mark::Exclusive) => Ok(Self {
                        kind: Kind::ExclusiveExclusive(range),
                    }),
                    (Mark::Exclusive, Mark::Inclusive) => Ok(Self {
                        kind: Kind::ExclusiveInclusive(range),
                    }),
                }
            },
            _ => Err(err()),
        }
    }

}
