projects involving the gemini protocol
//! Gemini Status Codes
//!
//! This module contains types to represent Gemini response statuses, construct
//! them from numbers or byte-strings, as well as to process them by `Category`
//! to allow for "simple but complete" clients and servers as mentioned in the
//! Gemini spec.
//!
//! # Examples
//!
//! ```
//! use gemini::{Category, Status};
//!
//! assert_eq!(Status::from_u8(20).unwrap(), Status::SUCCESS);
//! assert_eq!(Status::NOT_FOUND.code_number(), 51);
//! assert_eq!(Status::TEMPORARY_REDIRECT.category(), Category::Redirect)
//! ```
//!
//! inspiration taken from
//! https://github.com/hyperium/http/blob/master/src/status.rs
//!
//! note: currently constant and `Code` doc comments are taken verbatim from
//! [the Gemini spec](https://gemini.circumlunar.space/docs/specification.html).

use std::{convert::TryFrom, fmt::Display};

use thiserror::Error;

/// A Gemini status response.
///
/// Known responses should be constructed from the various constants in
/// `Status`, and unknown responses can be parsed from a single `u8` number or
/// from a series of bytes representing utf-8 encoded text.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Status {
    category: Category,
    code: Code,
}

/// Error to indicate a failure in parsing a `Status` from a numeric or textual
/// code.
#[derive(Debug, Copy, Clone, Error)]
pub struct InvalidStatusCode {
    _priv: (),
}

impl Display for InvalidStatusCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid status code")
    }
}

impl InvalidStatusCode {
    fn new() -> Self {
        InvalidStatusCode { _priv: () }
    }
}

macro_rules! status_consts {
    ($(
        $(#[$outer:meta])*
        $cat:ident: [$(
            $(#[$inner:meta])*
            $name:ident: $code:ident($code_num:expr, $msg:expr)
        ),+]
    ),*) => {
        impl Status {
            $($(
                $(#[$inner])*
                pub const $name: Self = Self::new(Category::$cat, Code::$code);
            )+)*

            /// Attempt to turn valid `u8` codes into `Status` objects.
            ///
            /// Any codes not present in the
            /// [Gemini spec](https://gemini.circumlunar.space/docs/specification.html)
            /// are considered errors.
            pub fn from_u8(code: u8) -> Result<Self, InvalidStatusCode> {
                Ok(match code {
                    $($($code_num => Self::$name,)*)+
                    _ => return Err(InvalidStatusCode::new()),
                })
            }

            /// Get a short text based description for a `Status` object.
            /// Strings will be returned in ALL CAPS.
            pub fn description(&self) -> &'static str {
                match self {
                    $($(&Self::$name => $msg,)*)+
                    _ => unreachable!("Invalid status"),
                }
            }
        }

        /// A high level category derived from the leading digit of a `Status`
        /// code.
        ///
        /// Simple clients and servers can examine only the `Category` of a
        /// `Status` and still follow the spec.
        #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
        pub enum Category {
            $(
                $(#[$outer])*
                $cat,
            )*
        }

        /// The precise two digit numeric code associated with a `Status`.
        ///
        /// Status codes not present in
        /// [the spec](https://gemini.circumlunar.space/docs/specification.html)
        /// are considered errors.
        #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
        pub enum Code {
            $($(
                $(#[$inner])*
                $code = $code_num,
            )*)+
        }
    };
}

status_consts!(
    /// Status codes which indicate that the client should ask the user for more input.
    Input: [
        /// The requested resource accepts a line of textual user input. The <META> line is a prompt which should be displayed to the user. The same resource should then be requested again with the user's input included as a query component. Queries are included in requests as per the usual generic URL definition in RFC3986, i.e. separated from the path by a ?. Reserved characters used in the user's input must be "percent-encoded" as per RFC3986, and space characters should also be percent-encoded.
        INPUT: Input(10, "INPUT"),
        /// As per status code 10, but for use with sensitive input such as passwords. Clients should present the prompt as per status code 10, but the user's input should not be echoed to the screen to prevent it being read by "shoulder surfers".
        SENSITIVE_INPUT: SensitiveInput(11, "SENSITIVE INPUT")
    ],
    /// Status codes that indicate a successful request/response cycle.
    Success: [
        /// The request was handled successfully and a response body will follow the response header. The <META> line is a MIME media type which applies to the response body.
        SUCCESS: Success(20, "SUCCESS")
    ],
    /// Status codes that indicate that a resource has moved.
    Redirect: [
        /// The server is redirecting the client to a new location for the requested resource. There is no response body. <META> is a new URL for the requested resource. The URL may be absolute or relative. The redirect should be considered temporary, i.e. clients should continue to request the resource at the original address and should not performance convenience actions like automatically updating bookmarks. There is no response body.
        TEMPORARY_REDIRECT: TemporaryRedirect(30, "REDIRECT - TEMPORARY"),
        /// The requested resource should be consistently requested from the new URL provided in future. Tools like search engine indexers or content aggregators should update their configurations to avoid requesting the old URL, and end-user clients may automatically update bookmarks, etc. Note that clients which only pay attention to the initial digit of status codes will treat this as a temporary redirect. They will still end up at the right place, they just won't be able to make use of the knowledge that this redirect is permanent, so they'll pay a small performance penalty by having to follow the redirect each time.
        PERMANENT_REDIRECT: PermanentRedirect(31, "REDIRECT - PERMANENT")
    ],
    /// Status codes that indicate a failure which should eventually be resolved.
    TemporaryFailure: [
        /// The request has failed. There is no response body. The nature of the failure is temporary, i.e. an identical request MAY succeed in the future. The contents of <META> may provide additional information on the failure, and should be displayed to human users.
        TEMPORARY_FAILURE: TemporaryFailure(40, "TEMPORARY FAILURE"),
        /// The server is unavailable due to overload or maintenance. (cf HTTP 503)
        SERVER_UNAVAILABLE: ServerUnavailable(41, "SERVER UNAVAILABLE"),
        /// A CGI process, or similar system for generating dynamic content, died unexpectedly or timed out.
        CGI_ERROR: CGIError(42, "CGI ERROR"),
        /// A proxy request failed because the server was unable to successfully complete a transaction with the remote host. (cf HTTP 502, 504)
        PROXY_ERROR: ProxyError(43, "PROXY ERROR"),
        /// Rate limiting is in effect. <META> is an integer number of seconds which the client must wait before another request is made to this server. (cf HTTP 429)
        SLOW_DOWN: SlowDown(44, "SLOW DOWN")
    ],
    /// Status codes that indicate a failure which will likely continue.
    PermanentFailure: [
        /// The request has failed. There is no response body. The nature of the failure is permanent, i.e. identical future requests will reliably fail for the same reason. The contents of <META> may provide additional information on the failure, and should be displayed to human users. Automatic clients such as aggregators or indexing crawlers should not repeat this request.
        PERMANENT_FAILURE: PermanentFailure(50, "PERMANENT FAILURE"),
        /// The requested resource could not be found but may be available in the future. (cf HTTP 404) (struggling to remember this important status code? Easy: you can't find things hidden at Area 51!)
        NOT_FOUND: NotFound(51, "NOT FOUND"),
        /// The resource requested is no longer available and will not be available again. Search engines and similar tools should remove this resource from their indices. Content aggregators should stop requesting the resource and convey to their human users that the subscribed resource is gone. (cf HTTP 410)
        GONE: Gone(52, "GONE"),
        /// The request was for a resource at a domain not served by the server and the server does not accept proxy requests.
        PROXY_REQUEST_REFUSED: ProxyRequestRefused(53, "PROXY REQUEST REFUSED"),
        /// The server was unable to parse the client's request, presumably due to a malformed request. (cf HTTP 400)
        BAD_REQUEST: BadRequest(59, "BAD REQUEST")
    ],
    /// Status codes that indicate the client must ask the user to provide a valid certificate.
    ClientCertificateRequired: [
        /// The requested resource requires a client certificate to access. If the request was made without a certificate, it should be repeated with one. If the request was made with a certificate, the server did not accept it and the request should be repeated with a different certificate. The contents of <META> (and/or the specific 6x code) may provide additional information on certificate requirements or the reason a certificate was rejected.
        CLIENT_CERTIFICATE_REQUIRED: ClientCertificateRequired(
            60,
            "CLIENT CERTIFICATE REQUIRED"
        ),
        /// The supplied client certificate is not authorised for accessing the particular requested resource. The problem is not with the certificate itself, which may be authorised for other resources.
        CLIENT_CERTIFICATE_NOT_AUTHORISED: ClientCertificateNotAuthorised(
            61,
            "CLIENT CERTIFICATE NOT AUTHORISED"
        ),
        /// The supplied client certificate was not accepted because it is not valid. This indicates a problem with the certificate in and of itself, with no consideration of the particular requested resource. The most likely cause is that the certificate's validity start date is in the future or its expiry date has passed, but this code may also indicate an invalid signature, or a violation of a X509 standard requirements. The <META> should provide more information about the exact error.
        CERTIFICATE_NOT_VALID: CertificateNotValid(62, "CERTIFICATE NOT VALID")
    ]
);

impl Status {
    const fn new(category: Category, code: Code) -> Self {
        Status { category, code }
    }

    /// Attempt to turn a valid series of bytes into a `Status`.
    ///
    /// Only byte sequences of length 2 are valid.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, InvalidStatusCode> {
        match bytes {
            [b1, b2] if (&b'0'..=&b'9').contains(&b1) && &b'0' <= b2 && b2 <= &b'9' => {
                let d1 = b1 - b'0';
                let d2 = b2 - b'0';
                Self::from_u8(d1 * 10 + d2)
            }
            _ => Err(InvalidStatusCode::new()),
        }
    }

    /// Return the `Category` of this `Status`.
    pub fn category(&self) -> Category {
        self.category
    }

    /// Return the `Code` of this `Status`.
    pub fn code(&self) -> Code {
        self.code
    }

    /// Return the numeric code of this `Status`.
    pub fn code_number(&self) -> u8 {
        self.code as u8
    }
}

impl TryFrom<u8> for Status {
    type Error = InvalidStatusCode;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        Self::from_u8(value)
    }
}

impl TryFrom<&[u8]> for Status {
    type Error = InvalidStatusCode;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        Self::from_bytes(value)
    }
}

/// Parser
#[cfg(feature = "parsers")]
pub mod parse {
    use nom::{bytes::streaming::take, combinator::map_res, error::context, IResult};

    use super::*;

    /// A simple `nom` parser for Gemini statuses based on `Status::from_bytes`.
    pub fn status(input: &[u8]) -> IResult<&[u8], Status> {
        context("status code", map_res(take(2usize), Status::from_bytes))(input)
    }

    #[cfg(test)]
    mod test {
        use super::*;

        #[test]
        fn test_good_statuses() {
            let statuses = vec![
                b"10", b"11", b"20", b"30", b"31", b"40", b"41", b"42", b"43", b"44", b"50", b"51",
                b"52", b"53", b"59", b"60", b"61", b"62",
            ];

            for code in statuses {
                assert!(status(code).is_ok())
            }
        }

        #[test]
        fn test_bad_statuses() {
            let base_code = b"70";
            for i in 0..40 {
                let mut code = base_code.clone();
                code[1] += i;
                assert!(status(&code).is_err())
            }
        }
    }
}