use bendy::decoding::{Error, FromBencode, Object};

#[derive(Debug, Default)]
pub struct Response {
    pub complete: u32,
    pub incomplete: u32,
    pub interval: u32,
    pub peers: Vec<u8>,
    pub peers6: Vec<u8>,
}

impl FromBencode for Response {
    fn decode_bencode_object(object: Object) -> Result<Self, Error> {
        let mut dict = object.try_into_dictionary()?;
        let mut response = Self::default();

        while let Some(pair) = dict.next_pair()? {
            match pair {
                (b"interval", value) => {
                    response.interval = value
                        .try_into_integer()
                        .unwrap_or_default()
                        .parse()
                        .unwrap_or_default()
                }
                (b"complete", value) => {
                    response.complete = value
                        .try_into_integer()
                        .unwrap_or_default()
                        .parse()
                        .unwrap_or_default()
                }
                (b"incomplete", value) => {
                    response.incomplete = value
                        .try_into_integer()
                        .unwrap_or_default()
                        .parse()
                        .unwrap_or_default()
                }
                (b"peers", value) => {
                    if let Ok(bytes) = value.try_into_bytes() {
                        response.peers = bytes.to_vec();
                    }
                }
                (b"peers6", value) => {
                    if let Ok(bytes) = value.try_into_bytes() {
                        response.peers6 = bytes.to_vec();
                    }
                }
                _ => continue,
            }
        }

        Ok(response)
    }
}
