//! Arbitrary data serialization.
//!
//! The [`Serializer`] type is a [`serde::ser::Serializer`] implementation which can serialize arbitrary data types into [`WriteBuffer`]s.
//! It is compatible with the [`serde`] ecosystem.
use serde::Serialize;

use crate::encode::*;
use crate::*;

/// Serializer implementation for serializing `petra` from arbitrary data types.
pub struct Serializer<'a, 'b> {
    buf: &'b mut WriteBuffer<'a>,
}

impl<'a, 'b> Serializer<'a, 'b> {
    pub fn from_buffer(buf: &'b mut WriteBuffer<'a>) -> Self {
        Self { buf }
    }
}

impl<'a, 'b: 'a, 'c> serde::Serializer for &'a mut Serializer<'b, 'c> {
    type Ok = ();
    type Error = Error;

    type SerializeSeq = SerializeSeq<'a, 'b, 'c>;
    type SerializeTuple = SerializeTuple<'a, 'b, 'c>;
    type SerializeTupleStruct = SerializeTupleStruct<'a, 'b, 'c>;
    type SerializeTupleVariant = SerializeTupleVariant<'a, 'b, 'c>;
    type SerializeMap = SerializeMap<'a, 'b, 'c>;
    type SerializeStruct = SerializeStruct<'a, 'b, 'c>;
    type SerializeStructVariant = SerializeStructVariant<'a, 'b, 'c>;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        write_bool(self.buf, v).map(|_| ())
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        self.serialize_i64(v as _)
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        self.serialize_i64(v as _)
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        self.serialize_i64(v as _)
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        write_signed(self.buf, v as _).map(|_| ())
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        self.serialize_u64(v as _)
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        self.serialize_u64(v as _)
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        self.serialize_u64(v as _)
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        write_unsigned(self.buf, v as _).map(|_| ())
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        write_f32(self.buf, v).map(|_| ())
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        write_f64(self.buf, v).map(|_| ())
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        if !v.is_ascii() {
            return Err(Error::BadEncoding);
        }

        // ASCII range occupies one byte
        let mut tmp = [0u8; 1];
        write_str(self.buf, v.encode_utf8(&mut tmp)).map(|_| ())
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        write_str(self.buf, v).map(|_| ())
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
        write_bin(self.buf, v).map(|_| ())
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        self.serialize_unit()
    }

    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        write_null(self.buf).map(|_| ())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        write_array(self.buf, Some(0)).map(|_| ())
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        write_str(self.buf, variant).map(|_| ())
    }

    fn serialize_newtype_struct<T>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        write_map(self.buf, Some(1))?;
        write_str(self.buf, variant)?;
        value.serialize(self)
    }

    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        write_array(self.buf, len)?;

        Ok(SerializeSeq {
            ser: self,
            flex: len.is_none(),
        })
    }

    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        write_array(self.buf, Some(len))?;
        Ok(SerializeTuple { ser: self })
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        write_array(self.buf, Some(len))?;
        Ok(SerializeTupleStruct { ser: self })
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        write_map(self.buf, Some(1))?;
        write_str(self.buf, variant)?;
        write_array(self.buf, Some(len))?;
        Ok(SerializeTupleVariant { ser: self })
    }

    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        write_map(self.buf, len)?;

        Ok(SerializeMap {
            ser: self,
            flex: len.is_none(),
        })
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        write_map(self.buf, Some(len))?;
        Ok(SerializeStruct { ser: self })
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        write_map(self.buf, Some(1))?;
        write_str(self.buf, variant)?;
        write_map(self.buf, Some(len))?;
        Ok(SerializeStructVariant { ser: self })
    }

    fn collect_str<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + core::fmt::Display,
    {
        Err(Error::Internal)
    }
}

pub struct SerializeSeq<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
    flex: bool,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeSeq for SerializeSeq<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        if self.flex {
            write_terminator(self.ser.buf).map(|_| ())
        } else {
            Ok(())
        }
    }
}

pub struct SerializeTuple<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeTuple for SerializeTuple<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

pub struct SerializeTupleStruct<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeTupleStruct for SerializeTupleStruct<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

pub struct SerializeTupleVariant<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeTupleVariant for SerializeTupleVariant<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

pub struct SerializeMap<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
    flex: bool,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeMap for SerializeMap<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        key.serialize(&mut *self.ser)
    }

    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        if self.flex {
            write_terminator(self.ser.buf).map(|_| ())
        } else {
            Ok(())
        }
    }
}

pub struct SerializeStruct<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeStruct for SerializeStruct<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        key.serialize(&mut *self.ser)?;
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

pub struct SerializeStructVariant<'a, 'b: 'a, 'c> {
    ser: &'a mut Serializer<'b, 'c>,
}

impl<'a, 'b: 'a, 'c> serde::ser::SerializeStructVariant for SerializeStructVariant<'a, 'b, 'c> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        key.serialize(&mut *self.ser)?;
        value.serialize(&mut *self.ser)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

#[cfg(test)]
mod tests;
