use serde::Serialize;
use super::value::IOValueDomainCodec;
use super::value::boundary as B;
use super::value::writer::{Writer, CompoundWriter};

pub use super::error::Error;
type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub struct Serializer<'w, W: Writer> {
    pub write: &'w mut W,
}

impl<'w, W: Writer> Serializer<'w, W> {
    pub fn new(write: &'w mut W) -> Self {
        Serializer { write }
    }
}

enum SequenceVariant<W: Writer> {
    Sequence(W::SeqWriter),
    Record(W::RecWriter),
}

pub struct SerializeCompound<'a, 'w, W: Writer> {
    b: B::Type,
    i: B::Item,
    ser: &'a mut Serializer<'w, W>,
    c: SequenceVariant<W>,
}

pub struct SerializeDictionary<'a, 'w, W: Writer> {
    b: B::Type,
    ser: &'a mut Serializer<'w, W>,
    d: W::DictWriter,
}

impl<'a, 'w, W: Writer> serde::Serializer for &'a mut Serializer<'w, W> {
    type Ok = ();
    type Error = Error;
    type SerializeSeq = SerializeCompound<'a, 'w, W>;
    type SerializeTuple = SerializeCompound<'a, 'w, W>;
    type SerializeTupleStruct = SerializeCompound<'a, 'w, W>;
    type SerializeTupleVariant = SerializeCompound<'a, 'w, W>;
    type SerializeMap = SerializeDictionary<'a, 'w, W>;
    type SerializeStruct = SerializeCompound<'a, 'w, W>;
    type SerializeStructVariant = SerializeCompound<'a, 'w, W>;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
        Ok(self.write.write_bool(v)?)
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok> {
        Ok(self.write.write_i8(v)?)
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok> {
        Ok(self.write.write_i16(v)?)
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
        Ok(self.write.write_i32(v)?)
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
        Ok(self.write.write_i64(v)?)
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
        Ok(self.write.write_u8(v)?)
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok> {
        Ok(self.write.write_u16(v)?)
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
        Ok(self.write.write_u32(v)?)
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
        Ok(self.write.write_u64(v)?)
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok> {
        Ok(self.write.write_f32(v)?)
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok> {
        Ok(self.write.write_f64(v)?)
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok> {
        let mut c = self.write.start_record(Some(1))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol("UnicodeScalar")?;
        c.boundary(&B::mid(B::Item::RecordLabel, B::Item::RecordField))?;
        c.write_u32(v as u32)?;
        c.boundary(&B::end(B::Item::RecordField))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok> {
        Ok(self.write.write_string(v)?)
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
        Ok(self.write.write_bytes(v)?)
    }

    fn serialize_none(self) -> Result<Self::Ok> {
        let mut c = self.write.start_record(Some(0))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol("None")?;
        c.boundary(&B::end(B::Item::RecordLabel))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_some<T: ?Sized>(self, v: &T) -> Result<Self::Ok> where T: Serialize {
        let mut c = self.write.start_record(Some(1))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol("Some")?;
        c.boundary(&B::mid(B::Item::RecordLabel, B::Item::RecordField))?;
        to_writer(&mut c, v)?;
        c.boundary(&B::end(B::Item::RecordField))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_unit(self) -> Result<Self::Ok> {
        let mut c = self.write.start_record(Some(0))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol("tuple")?;
        c.boundary(&B::end(B::Item::RecordLabel))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok> {
        let mut c = self.write.start_record(Some(0))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(name)?;
        c.boundary(&B::end(B::Item::RecordLabel))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_unit_variant(self,
                              _name: &'static str,
                              _variant: u32,
                              variant_name: &'static str) ->
        Result<Self::Ok>
    {
        let mut c = self.write.start_record(Some(0))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(variant_name)?;
        c.boundary(&B::end(B::Item::RecordLabel))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) ->
        Result<Self::Ok> where T: Serialize
    {
        match super::value::magic::receive_output_value(name, value) {
            Some(v) => Ok(self.write.write(&mut IOValueDomainCodec, &v)?),
            None => {
                // TODO: This is apparently discouraged, and we should apparently just serialize `value`?
                let mut c = self.write.start_record(Some(1))?;
                c.boundary(&B::start(B::Item::RecordLabel))?;
                c.write_symbol(name)?;
                c.boundary(&B::mid(B::Item::RecordLabel, B::Item::RecordField))?;
                to_writer(&mut c, value)?;
                c.boundary(&B::end(B::Item::RecordField))?;
                Ok(self.write.end_record(c)?)
            }
        }
    }

    fn serialize_newtype_variant<T: ?Sized>(self,
                                            _name: &'static str,
                                            _variant: u32,
                                            variant_name: &'static str,
                                            value: &T) ->
        Result<Self::Ok> where T: Serialize
    {
        let mut c = self.write.start_record(Some(1))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(variant_name)?;
        c.boundary(&B::mid(B::Item::RecordLabel, B::Item::RecordField))?;
        to_writer(&mut c, value)?;
        c.boundary(&B::end(B::Item::RecordField))?;
        Ok(self.write.end_record(c)?)
    }

    fn serialize_seq(self, count: Option<usize>) -> Result<Self::SerializeSeq> {
        let c = self.write.start_sequence(count)?;
        Ok(SerializeCompound::seq(self, c))
    }

    fn serialize_tuple(self, count: usize) -> Result<Self::SerializeTuple> {
        let mut c = self.write.start_record(Some(count))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol("tuple")?;
        Ok(SerializeCompound::rec(self, c))
    }

    fn serialize_tuple_struct(self, name: &'static str, count: usize) ->
        Result<Self::SerializeTupleStruct>
    {
        let mut c = self.write.start_record(Some(count))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(name)?;
        Ok(SerializeCompound::rec(self, c))
    }

    fn serialize_tuple_variant(self,
                               _name: &'static str,
                               _variant: u32,
                               variant_name: &'static str,
                               count: usize) ->
        Result<Self::SerializeTupleVariant>
    {
        let mut c = self.write.start_record(Some(count))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(variant_name)?;
        Ok(SerializeCompound::rec(self, c))
    }

    fn serialize_map(self, count: Option<usize>) -> Result<Self::SerializeMap> {
        let d = self.write.start_dictionary(count)?;
        Ok(SerializeDictionary { b: B::Type::default(), ser: self, d })
    }

    fn serialize_struct(self, name: &'static str, count: usize) -> Result<Self::SerializeStruct> {
        let mut c = self.write.start_record(Some(count))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(name)?;
        Ok(SerializeCompound::rec(self, c))
    }

    fn serialize_struct_variant(self,
                                _name: &'static str,
                                _variant: u32,
                                variant_name: &'static str,
                                count: usize) ->
        Result<Self::SerializeStructVariant>
    {
        let mut c = self.write.start_record(Some(count))?;
        c.boundary(&B::start(B::Item::RecordLabel))?;
        c.write_symbol(variant_name)?;
        Ok(SerializeCompound::rec(self, c))
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeMap for SerializeDictionary<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()> where T: Serialize {
        self.b.opening = Some(B::Item::DictionaryKey);
        self.d.boundary(&self.b)?;
        to_writer(&mut self.d, key)?;
        self.b.shift(None);
        Ok(())
    }

    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
        self.b.opening = Some(B::Item::DictionaryValue);
        self.d.boundary(&self.b)?;
        to_writer(&mut self.d, value)?;
        self.b.shift(None);
        Ok(())
    }

    fn end(mut self) -> Result<Self::Ok> {
        self.d.boundary(&self.b)?;
        Ok(self.ser.write.end_dictionary(self.d)?)
    }
}

impl<'a, 'w, W: Writer> SerializeCompound<'a, 'w, W> {
    fn seq(ser: &'a mut Serializer<'w, W>, c: W::SeqWriter) -> Self {
        SerializeCompound {
            b: B::Type::default(),
            i: B::Item::SequenceValue,
            ser,
            c: SequenceVariant::Sequence(c),
        }
    }

    fn rec(ser: &'a mut Serializer<'w, W>, c: W::RecWriter) -> Self {
        SerializeCompound {
            b: B::end(B::Item::RecordLabel),
            i: B::Item::RecordField,
            ser,
            c: SequenceVariant::Record(c),
        }
    }

    fn extend<T: ?Sized>(&mut self, value: &T) -> Result<()>
    where T: Serialize
    {
        self.b.opening = Some(self.i.clone());
        match &mut self.c {
            SequenceVariant::Sequence(w) => { w.boundary(&self.b)?; to_writer(w, value)?; }
            SequenceVariant::Record(w) => { w.boundary(&self.b)?; to_writer(w, value)?; }
        }
        self.b.shift(None);
        Ok(())
    }

    fn complete(self) -> Result<()> {
        match self.c {
            SequenceVariant::Sequence(mut w) => {
                w.boundary(&self.b)?;
                Ok(self.ser.write.end_sequence(w)?)
            }
            SequenceVariant::Record(mut w) => {
                w.boundary(&self.b)?;
                Ok(self.ser.write.end_record(w)?)
            }
        }
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeStruct for SerializeCompound<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: ?Sized>(&mut self, _name: &'static str, value: &T) -> Result<()>
    where T: Serialize
    {
        self.extend(value)
    }

    fn end(self) -> Result<Self::Ok> {
        self.complete()
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeStructVariant for SerializeCompound<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: ?Sized>(&mut self, _name: &'static str, value: &T) -> Result<()>
    where T: Serialize
    {
        self.extend(value)
    }

    fn end(self) -> Result<Self::Ok> {
        self.complete()
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeTuple for SerializeCompound<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
        self.extend(value)
    }

    fn end(self) -> Result<Self::Ok> {
        self.complete()
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeTupleStruct for SerializeCompound<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
        self.extend(value)
    }

    fn end(self) -> Result<Self::Ok> {
        self.complete()
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeTupleVariant for SerializeCompound<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
        self.extend(value)
    }

    fn end(self) -> Result<Self::Ok> {
        self.complete()
    }
}

impl<'a, 'w, W: Writer> serde::ser::SerializeSeq for SerializeCompound<'a, 'w, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
        self.extend(value)
    }

    fn end(self) -> Result<Self::Ok> {
        self.complete()
    }
}

pub fn to_writer<W: Writer, T: Serialize + ?Sized>(write: &mut W, value: &T) -> Result<()> {
    Ok(value.serialize(&mut Serializer::new(write))?)
}
