use num::bigint::BigInt;
use std::io;
use super::DomainEncode;
use super::boundary as B;
use super::signed_integer::SignedIntegerRepr;
use super::repr::{Value, NestedValue, Float, Double};

pub trait CompoundWriter: Writer {
    fn boundary(&mut self, b: &B::Type) -> io::Result<()>;
}

pub trait Writer: Sized {
    type AnnWriter: CompoundWriter;
    type RecWriter: CompoundWriter;
    type SeqWriter: CompoundWriter;
    type SetWriter: CompoundWriter;
    type DictWriter: CompoundWriter;
    type EmbeddedWriter: Writer;

    fn start_annotations(&mut self) -> io::Result<Self::AnnWriter>;
    fn end_annotations(&mut self, ann: Self::AnnWriter) -> io::Result<()>;

    fn write_bool(&mut self, v: bool) -> io::Result<()>;

    fn write_f32(&mut self, v: f32) -> io::Result<()>;
    fn write_f64(&mut self, v: f64) -> io::Result<()>;

    fn write_i8(&mut self, v: i8) -> io::Result<()>;
    fn write_u8(&mut self, v: u8) -> io::Result<()>;
    fn write_i16(&mut self, v: i16) -> io::Result<()>;
    fn write_u16(&mut self, v: u16) -> io::Result<()>;
    fn write_i32(&mut self, v: i32) -> io::Result<()>;
    fn write_u32(&mut self, v: u32) -> io::Result<()>;
    fn write_i64(&mut self, v: i64) -> io::Result<()>;
    fn write_u64(&mut self, v: u64) -> io::Result<()>;
    fn write_i128(&mut self, v: i128) -> io::Result<()>;
    fn write_u128(&mut self, v: u128) -> io::Result<()>;
    fn write_int(&mut self, v: &BigInt) -> io::Result<()>;

    fn write_string(&mut self, v: &str) -> io::Result<()>;
    fn write_bytes(&mut self, v: &[u8]) -> io::Result<()>;
    fn write_symbol(&mut self, v: &str) -> io::Result<()>;

    fn start_record(&mut self, field_count: Option<usize>) -> io::Result<Self::RecWriter>;
    fn end_record(&mut self, rec: Self::RecWriter) -> io::Result<()>;

    fn start_sequence(&mut self, item_count: Option<usize>) -> io::Result<Self::SeqWriter>;
    fn end_sequence(&mut self, seq: Self::SeqWriter) -> io::Result<()>;

    fn start_set(&mut self, item_count: Option<usize>) -> io::Result<Self::SetWriter>;
    fn end_set(&mut self, set: Self::SetWriter) -> io::Result<()>;

    fn start_dictionary(&mut self, entry_count: Option<usize>) -> io::Result<Self::DictWriter>;
    fn end_dictionary(&mut self, dict: Self::DictWriter) -> io::Result<()>;

    fn start_embedded(&mut self) -> io::Result<Self::EmbeddedWriter>;
    fn end_embedded(&mut self, ptr: Self::EmbeddedWriter) -> io::Result<()>;

    fn flush(&mut self) -> io::Result<()>;

    //---------------------------------------------------------------------------

    fn write<N: NestedValue, Enc: DomainEncode<N::Embedded>>(
        &mut self,
        enc: &mut Enc,
        v: &N,
    ) -> io::Result<()> {
        match v.annotations().maybe_slice() {
            None => {
                self.write_value(enc, v.value())?;
            }
            Some(anns) => {
                let mut a = self.start_annotations()?;
                let mut b = B::Type::default();
                for ann in anns {
                    b.shift(Some(B::Item::Annotation));
                    a.boundary(&b)?;
                    a.write(enc, ann)?;
                }
                b.shift(Some(B::Item::AnnotatedValue));
                a.boundary(&b)?;
                a.write_value(enc, v.value())?;
                b.shift(None);
                a.boundary(&b)?;
                self.end_annotations(a)?;
            }
        }
        Ok(())
    }

    fn write_value<N: NestedValue, Enc: DomainEncode<N::Embedded>>(
        &mut self,
        enc: &mut Enc,
        v: &Value<N>,
    ) -> io::Result<()> {
        match v {
            Value::Boolean(b) => self.write_bool(*b),
            Value::Float(Float(f)) => self.write_f32(*f),
            Value::Double(Double(d)) => self.write_f64(*d),
            Value::SignedInteger(n) => match n.repr() {
                SignedIntegerRepr::I128(i) => self.write_i128(*i),
                SignedIntegerRepr::U128(u) => self.write_u128(*u),
                SignedIntegerRepr::Big(n) => self.write_int(n),
            }
            Value::String(s) => self.write_string(s),
            Value::ByteString(bs) => self.write_bytes(bs),
            Value::Symbol(s) => self.write_symbol(s),
            Value::Record(r) => {
                let mut c = self.start_record(Some(r.arity()))?;
                let mut b = B::start(B::Item::RecordLabel);
                c.boundary(&b)?;
                c.write(enc, r.label())?;
                for f in r.fields() {
                    b.shift(Some(B::Item::RecordField));
                    c.boundary(&b)?;
                    c.write(enc, f)?;
                }
                b.shift(None);
                c.boundary(&b)?;
                self.end_record(c)
            }
            Value::Sequence(vs) => {
                let mut c = self.start_sequence(Some(vs.len()))?;
                let mut b = B::Type::default();
                for v in vs {
                    b.shift(Some(B::Item::SequenceValue));
                    c.boundary(&b)?;
                    c.write(enc, v)?;
                }
                b.shift(None);
                c.boundary(&b)?;
                self.end_sequence(c)
            }
            Value::Set(vs) => {
                let mut c = self.start_set(Some(vs.len()))?;
                let mut b = B::Type::default();
                for v in vs {
                    b.shift(Some(B::Item::SetValue));
                    c.boundary(&b)?;
                    c.write(enc, v)?;
                }
                b.shift(None);
                c.boundary(&b)?;
                self.end_set(c)
            }
            Value::Dictionary(vs) => {
                let mut c = self.start_dictionary(Some(vs.len()))?;
                let mut b = B::Type::default();
                for (k, v) in vs {
                    b.shift(Some(B::Item::DictionaryKey));
                    c.boundary(&b)?;
                    c.write(enc, k)?;
                    b.shift(Some(B::Item::DictionaryValue));
                    c.boundary(&b)?;
                    c.write(enc, v)?;
                }
                b.shift(None);
                c.boundary(&b)?;
                self.end_dictionary(c)
            }
            Value::Embedded(d) => {
                let mut c = self.start_embedded()?;
                enc.encode_embedded(&mut c, d)?;
                self.end_embedded(c)
            }
        }
    }
}

pub fn varint<W: io::Write>(w: &mut W, mut v: u64) -> io::Result<usize> {
    let mut byte_count = 0;
    loop {
        byte_count += 1;
        if v < 128 {
            w.write_all(&[v as u8])?;
            return Ok(byte_count);
        } else {
            w.write_all(&[((v & 0x7f) + 128) as u8])?;
            v >>= 7;
        }
    }
}
