//! [RFC 2616](https://tools.ietf.org/html/rfc2616#section-5.1)
//!
//! Request
//! =======
//! Request-Line   = Method SP Request-URI SP HTTP-Version CRLF
//! Request-URI    = "*" | absoluteURI | abs_path | authority
//!
//! Response
//! ========

use bytes::{ BytesMut, Buf };

use crate::{
    HttpResult,
    HttpError,
    Request,
};

use tokio_util::codec::{
    Decoder,
};

#[derive(Debug, Default)]
pub struct HttpCodec {
    pub pos_n: Vec<usize>,
    pub payload: BytesMut,
}

impl HttpCodec {
    #[inline(always)]
    fn _parse(&mut self, buf: &mut BytesMut) -> Option<Request> {
        for (i, c) in buf.iter().enumerate() {
            if *c == 0x0A {
                let i = self.payload.len() + i;

                self.pos_n.push(i);

                if self.pos_n.len() >= 2 && (i - 2 == self.pos_n[self.pos_n.len() - 2]) {
                    self._advance(buf);
                    return self._build_request();
                }
            }
        }

        self._advance(buf);
        None
    }

    #[inline(always)]
    fn _advance(&mut self, buf: &mut BytesMut) {
        self.payload.extend_from_slice(&buf[..]);
        buf.advance(buf.len());
    }

    #[inline(always)]
    fn _build_request(&self) -> Option<Request> {
        Some(Request::new(&self.payload, &self.pos_n))
    }
}

impl HttpCodec {

}

impl Decoder for HttpCodec {
    type Item = Request;
    type Error = HttpError;

    fn decode(&mut self, buf: &mut BytesMut) -> HttpResult<Option<Self::Item>> {
        println!("{:?}", buf);
        if let Some(request) = self._parse(buf) {
            return Ok(Some(request))
        }

        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    extern crate test;

    use bytes::{ BytesMut, BufMut };
    use super::*;
    use crate::Method;
    use test::Bencher;

    #[test]
    fn decode() {
        let mut codec = HttpCodec::default();
        let mut buf = BytesMut::from(&b"GET "[..]);
        let res = codec.decode(&mut buf);
        assert!(res.unwrap().is_none());

        buf.put_slice(&b"/ws/terminal HTTP/"[..]);
        let res = codec.decode(&mut buf);
        assert!(res.unwrap().is_none());

        buf.put_slice(&b"1.1\r\nHost: hawk.local\r"[..]);
        let res = codec.decode(&mut buf);
        assert!(res.unwrap().is_none());

        buf.put_slice(&b"\nUpgrade:websocket\r"[..]);
        let res = codec.decode(&mut buf);
        assert!(res.unwrap().is_none());

        buf.put_slice(&b"\n\r\n"[..]);
        let res = codec.decode(&mut buf);
        let req = res.unwrap().unwrap();

        assert_eq!("https://hawk.local/ws/terminal", req.url.as_str());
        assert_eq!(Method::GET, req.method);
        assert_eq!(1, req.version);
        assert_eq!("hawk.local", req.headers.get("host").unwrap());
        assert_eq!("websocket", req.headers.get("upgrade").unwrap());
    }

    #[bench]
    fn bench_decode(b: &mut Bencher) {
        // 7,760 ns/iter (+/- 185)
        // 7,848 ns/iter (+/- 587)
        // 7,938 ns/iter (+/- 617)
        b.iter(|| decode())
    }
}
