use std::{error::Error, io};

pub struct Response<'a> {
    response: &'a str,
}

impl<'a> Response<'a> {
    pub fn new(response: &str) -> Response {
        let parse = Response { response: response };
        Response {
            response: parse.response,
        }
    }
    pub fn method(&self) -> &str {
        let method = self.response.split(" ").nth(0).unwrap();
        method
    }
    pub fn path(&self) -> &str {
        let path = self.response.split(" ").nth(1).unwrap();
        // println!("{}", path);
        path
    }
    pub fn content(&self) -> &str {
        let content = self
            .response
            .find("\r\n\r\n")
            .unwrap_or(self.response.len());
        let response = self.response[content..].trim().trim_end_matches("\0");
        response
    }
    pub fn token(&self) -> &str {
        match self.response.find("Authorization : Bearer") {
            Some(size) => {
                let response = self.response[size..].trim().trim_end_matches("\r\n\r\n");
                response
            }
            None => "Invalid token",
        }
    }
    pub fn cookie(&self) -> Result<&str, Box<dyn Error>> {
        // println!("{}", self.response);
        match self.response.find("Cookie: ") {
            Some(size) => {
                let size = size + "Cookie :".len();
                let cookie = self.response[size..]
                    .trim()
                    .trim_end_matches("\r\n\r\n")
                    .trim_end_matches("\0");
                println!("{:?}", cookie);
                Ok(cookie)
            }
            None => Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidData,
                "Cookie Not found",
            ))),
        }
    }
}
