use crate::tree::TreeNode;
use bit_vec::BitVec;
use priority_queue::PriorityQueue;
use std::cmp::Reverse;
use std::collections::HashMap;
use std::fmt;
//type HuffCode = Vec<bool>;
type HuffCode = BitVec;
type HuffCodeMap = HashMap<char, HuffCode>;
type CodeMap = HashMap<char, String>;
pub trait Coder {
    fn new(alphabet: Vec<(char, f64)>) -> Self;
    fn encode(&self, input: &str) -> String;
    fn decode(&self, input: &str) -> String;
}
#[derive(Debug)]
pub struct Huffman {
    alphabet_root: Box<TreeNode<char>>,
    codes: CodeMap,
}

impl Coder for Huffman {
    fn new(mut alphabet: Vec<(char, f64)>) -> Huffman {
        let mut pq = PriorityQueue::new();
        for tuple in alphabet {
            pq.push(
                Box::new(TreeNode::new(Some(tuple.0))),
                Reverse((tuple.1 * 1000.0) as u64),
            );
        }
        while pq.len() != 1 {
            let mut b = Box::new(TreeNode::<char>::new(None));
            let l = pq.pop().unwrap();
            let r = pq.pop().unwrap();
            b.insert_left(l.0);
            b.insert_right(r.0);
            pq.push(b, Reverse((l.1).0 + (r.1).0)); // sum the priorities and push the new node back
        }
        //print!("{}:{}", pq.peek().unwrap().0, (pq.peek().unwrap().1).0);
        let root = pq.pop().unwrap().0;
        let mut prefix = bit_vec::BitVec::new();
        //let mut prefix: HuffCode = Vec::new();
        let mut codes = HuffCodeMap::new();
        Self::generate_codes(&root, &mut prefix, &mut codes);

        let mut codes_conv = CodeMap::new();
        for (z, c) in codes.iter() {
            let mut buf = String::new();
            for i in c.iter() {
                if i {
                    buf.push('1');
                } else {
                    buf.push('0');
                }
            }
            codes_conv.entry(*z).or_insert(buf);
        }
        Huffman {
            alphabet_root: root,
            codes: codes_conv,
        }
    }
    fn encode(&self, input: &str) -> String {
        let mut it = input.chars();
        let mut output = String::new();

        while let Some(i) = it.next() {
            let buf = &self.codes[&i];
            output.push_str(&buf);
        }
        output
    }

    fn decode(&self, input: &str) -> String {
        let mut input = String::from(input);
        let mut output = String::new();
        while input.len() != 0 {
            for (z, c) in self.codes.iter() {
                if input.starts_with(c) {
                    input = (&input[c.len()..]).to_string();
                    output.push(*z);
                }
            }
        }
        output
    }
}

impl Huffman {
    fn generate_codes(node: &TreeNode<char>, prefix: &mut HuffCode, codes: &mut HuffCodeMap) {
        if node.value != None {
            codes.entry(node.value.unwrap()).or_insert(prefix.clone());
        } else {
            let mut l_prefix = prefix.clone();
            l_prefix.push(false);
            let n = node.left.as_ref().unwrap();
            Self::generate_codes(&n, &mut l_prefix, codes);

            let mut r_prefix = prefix.clone();
            r_prefix.push(true);
            let n = node.right.as_ref().unwrap();
            Self::generate_codes(&n, &mut r_prefix, codes);
        }
    }
}
#[derive(Debug)]
pub struct Shannon {
    codes: CodeMap,
}

impl Coder for Shannon {
    fn new(mut alphabet: Vec<(char, f64)>) -> Shannon {
        alphabet.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
        println!("Alphabet Shanon:\n{:#?}", alphabet);
        let mut codes = CodeMap::new();
        let mut prev_sum: f64 = 0.0;
        for (ch, p) in alphabet.iter() {
            let l = (-p.log2()).ceil() as u32;
            let base = fmt::format(format_args!("{:b}", prev_sum.fract() as u64));

            let code = &base[0..l].to_string(); //first two are "0."
            codes.entry(*ch).or_insert(code);
            //end
            prev_sum += p;
        }

        Shannon { codes: codes }
    }
    fn encode(&self, input: &str) -> String {
        String::new()
    }
    fn decode(&self, input: &str) -> String {
        String::new()
    }
}
