use crate::error::{Error::*, *};
use std::collections::HashMap;

pub trait BencodeParseAsString {
    fn as_string(self) -> String;
}

pub type BencodeInteger = usize;
pub type BencodeByteStr = Vec<u8>;
impl BencodeParseAsString for BencodeByteStr {
    fn as_string(self) -> String {
        String::from_utf8(self).unwrap()
    }
}
pub type BencodeList = Vec<Bencode>;
pub type BencodeDict = HashMap<BencodeByteStr, Bencode>;

/// The object structure of a bencode file.
#[derive(Eq, PartialEq, Debug)]
pub enum Bencode {
    /// an integer value. in the format "i{VALUE}e"
    Integer(BencodeInteger),
    /// a byte string value. in the format "{LENGTH}:{DATA}"
    ByteStr(BencodeByteStr),
    /// a list of any Bencode type. in the format "l{BENCODE_OBJECTS}e"
    List(BencodeList),
    /// a list (Bencode::ByteString, Bencode). in the format "d{PAIRS}e"
    Dict(BencodeDict),
}

impl Bencode {
    /// parse a byte array into a bencode tree.
    pub fn from_bytes(bytes: &[u8]) -> Result {
        crate::parser::parse_child(bytes)
    }
    /// destructure a Bencode::Dict into a HashMap.
    pub fn as_dict(&self) -> GenResult<&BencodeDict> {
        match self {
            Bencode::Dict(val) => Ok(val),
            _ => Err(CannotParseAsDictionary),
        }
    }
    /// destructure a Bencode::List into a Vec.
    pub fn as_list(&self) -> GenResult<&BencodeList> {
        match self {
            Bencode::List(val) => Ok(val),
            _ => Err(CannotParseAsList),
        }
    }
    /// destructure a Bencode::Integer into a usize.
    pub fn as_int(&self) -> GenResult<&BencodeInteger> {
        match self {
            Bencode::Integer(val) => Ok(val),
            _ => Err(CannotParseAsInteger),
        }
    }
    /// destructure a Bencode::ByteStr into a Vec<u8>.
    pub fn as_bstr(&self) -> GenResult<&BencodeByteStr> {
        match self {
            Bencode::ByteStr(val) => Ok(val),
            _ => Err(CannotParseAsByteString),
        }
    }
    /// destructure a Bencode::ByteStr into a String.
    pub fn as_string(&self) -> GenResult<String> {
        match self {
            Bencode::ByteStr(val) => {
                Ok(String::from_utf8(val.to_vec()).unwrap())
            }
            _ => Err(CannotParseAsByteString),
        }
    }
}
