pub use crate::types::*;

pub mod error;
pub mod parser;
pub mod types;

#[cfg(test)]
mod tests {
    use crate::error::Error;
    use crate::types::{Bencode, Bencode::*};
    use std::collections::HashMap;

    #[test]
    fn happy_path_as_int() {
        let (res1, offset1) = Bencode::from_bytes(b"i10e").unwrap();
        assert_eq!(res1, Integer(10));
        assert_eq!(offset1, 4);

        // TODO: torrent v2 wont accept this, but we can, since v1 does.
        let (res2, offset2) = Bencode::from_bytes(b"i0005e").unwrap();
        assert_eq!(res2, Integer(5));
        assert_eq!(offset2, 6);

        let (res3, offset3) = Bencode::from_bytes(b"i123456e").unwrap();
        assert_eq!(res3, Integer(123456));
        assert_eq!(offset3, 8);
    }

    #[test]
    fn happy_path_as_bstr() {
        let (res1, offset1) = Bencode::from_bytes(b"1:a").unwrap();
        assert_eq!(res1, ByteStr(b"a".to_vec()));
        assert_eq!(offset1, 3);

        // even if the data is longer, we truncate to the length specified
        let (res2, offset2) = Bencode::from_bytes(b"3:apple").unwrap();
        assert_eq!(ByteStr(b"app".to_vec()), res2);
        assert_eq!(5, offset2);

        let (res3, offset3) = Bencode::from_bytes(&[51, 58, 68, 111, 103]).unwrap();
        assert_eq!(ByteStr(b"Dog".to_vec()), res3);
        assert_eq!(5, offset3);

        // make sure we can do arbitrary bytes
        let (res4, offset4) = Bencode::from_bytes(&[55, 58, 0, 1, 2, 3, 4, 5, 6]).unwrap();
        assert_eq!(ByteStr(vec![0, 1, 2, 3, 4, 5, 6]), res4);
        assert_eq!(9, offset4);
    }

    #[test]
    fn happy_path_as_list() {
        let (res1, offset1) = Bencode::from_bytes(b"li1ei2ei3ee").unwrap();
        assert_eq!(res1, List(vec![Integer(1), Integer(2), Integer(3)]));
        assert_eq!(offset1, 11);

        let (res2, offset2) = Bencode::from_bytes(b"li10e5:applee").unwrap();
        assert_eq!(res2, List(vec![Integer(10), ByteStr(b"apple".to_vec())]));
        assert_eq!(offset2, 13);
    }

    #[test]
    fn happy_path_as_list_nested() {
        let (res, offset) = Bencode::from_bytes(b"li1eli2eei3ee").unwrap();
        assert_eq!(
            res,
            List(vec![Integer(1), List(vec![Integer(2)]), Integer(3)])
        );
        assert_eq!(offset, 13);
    }

    #[test]
    fn happy_path_as_dict() {
        let (res, offset) = Bencode::from_bytes(b"d3:onei1ee").unwrap();
        let mut expected_map: HashMap<Vec<u8>, Bencode> = HashMap::new();
        expected_map.insert(b"one".to_vec(), Integer(1));
        assert_eq!(res, Dict(expected_map));
        assert_eq!(offset, 10);
    }

    #[test]
    fn happy_path_as_dict_nested() {
        let (res, offset) = Bencode::from_bytes(b"d4:testli1ei2ei3eee").unwrap();
        let mut expected_map: HashMap<Vec<u8>, Bencode> = HashMap::new();
        expected_map.insert(
            b"test".to_vec(),
            List(vec![Integer(1), Integer(2), Integer(3)]),
        );
        assert_eq!(res, Dict(expected_map));
        assert_eq!(offset, 19);
    }

    #[test]
    fn error_test_as_int() {
        assert_eq!(
            // oops, we forgot an 'e'
            Bencode::from_bytes(b"i12345").err().unwrap(),
            Error::MissingSentinel
        );
        assert_eq!(
            // oh boy, we have letters...
            Bencode::from_bytes(b"i1ae").err().unwrap(),
            Error::InvalidIntegerString
        );
        assert_eq!(
            // this isn't your grandmother's ascii. (max ascii is 127 [DEL])
            Bencode::from_bytes(&[105, 48, 49, 128, 101]).err().unwrap(),
            Error::InvalidASCIIBytes
        );
        assert_eq!(
            // this isn't your grandmother's ascii. (max ascii is 127 [DEL])
            Bencode::from_bytes(b"ie").err().unwrap(),
            Error::InvalidIntegerString
        );
    }

    #[test]
    fn error_test_as_bstr() {
        assert_eq!(
            // we forgot our ':'
            Bencode::from_bytes(b"123").err().unwrap(),
            Error::MissingSentinel
        );
        assert_eq!(
            // we forgot our ':'
            Bencode::from_bytes(b"9999999lalalala").err().unwrap(),
            Error::InvalidIntegerString
        );
        assert_eq!(
            // using letters to specify the length is illegal!
            Bencode::from_bytes(b"five:hello").err().unwrap(),
            Error::NotAValidBencodeByte
        );
        assert_eq!(
            // we used an invalid ascii byte in the length definition
            Bencode::from_bytes(&[48, 49, 50, 128, 58]).err().unwrap(),
            Error::InvalidASCIIBytes
        );
        assert_eq!(
            // bytestring overflow
            Bencode::from_bytes(b"9999:yikes").err().unwrap(),
            Error::ByteStringLengthOverflow
        );
    }

    #[test]
    fn error_test_as_list() {
        // there aren't any unique errors for lists.
        // this just verifies that errors bubble up properly through
        assert_eq!(
            // skipped an 'e' vv   there.
            Bencode::from_bytes(b"li1ei2ei3i4ei5ee").err().unwrap(),
            Error::InvalidIntegerString
        );
        assert_eq!(
            // skipped an 'e' at the end.
            Bencode::from_bytes(b"li1ei2ei3ei4ei5e").err().unwrap(),
            Error::MissingSentinel
        );
        assert_eq!(
            Bencode::from_bytes(b"l4:hie").err().unwrap(),
            Error::ByteStringLengthOverflow
        );
    }

    #[test]
    fn simple_integer() {
        let input = b"i10e";
        if let Ok((res, _)) = Bencode::from_bytes(input) {
            assert_eq!(Bencode::Integer(10), res)
        }
    }

    #[test]
    fn simple_enum_unwrapping() {
        // integer unwrapping
        let bint = Bencode::Integer(10);
        assert_eq!(&10, bint.as_int().unwrap());

        // bytestring unwrapping
        let bstr = Bencode::ByteStr(b"foo".to_vec());
        assert_eq!(&b"foo".to_vec(), bstr.as_bstr().unwrap());

        // list unwrapping
        let blist = Bencode::List(vec![Bencode::Integer(1), Bencode::Integer(2)]);

        let expected_list = vec![Bencode::Integer(1), Bencode::Integer(2)];
        let unwrapped_list = blist.as_list().unwrap();
        assert_eq!(unwrapped_list, &expected_list);
        assert_eq!(&1, unwrapped_list.get(0).unwrap().as_int().unwrap());

        // dictionary unwrapping
        let mut dict = HashMap::new();
        dict.insert(b"foo".to_vec(), ByteStr(b"bar".to_vec()));
        let bdict = Bencode::Dict(dict);

        let mut expected_dict = HashMap::new();
        let unwrapped_dict = bdict.as_dict().unwrap();
        expected_dict.insert(b"foo".to_vec(), ByteStr(b"bar".to_vec()));
        assert_eq!(&expected_dict, bdict.as_dict().unwrap());
        assert_eq!(
            &b"bar".to_vec(),
            unwrapped_dict
                .get(&b"foo".to_vec())
                .unwrap()
                .as_bstr()
                .unwrap()
        );
    }
}
