use core::fmt;

use crate::alloc;
use crate::macros::{MacroContext, ToTokens, TokenStream};

type EncodeFn<'a> =
    dyn Fn(&mut MacroContext<'_, '_, '_>, &mut TokenStream) -> alloc::Result<()> + Send + Sync + 'a;

/// Construct a token stream from a function.
pub fn quote_fn<'a, T>(f: T) -> Quote<'a>
where
    T: 'a + Fn(&mut MacroContext<'_, '_, '_>, &mut TokenStream) -> alloc::Result<()> + Send + Sync,
{
    // TODO: somehow support CoerceUnsized.
    Quote(rust_alloc::boxed::Box::new(f))
}

/// [ToTokens] implementation generated by [quote_fn].
pub struct Quote<'a>(rust_alloc::boxed::Box<EncodeFn<'a>>);

impl Quote<'_> {
    /// Convert into token stream.
    ///
    /// # Panics
    ///
    /// This panics if called outside of a macro context.
    pub fn into_token_stream(
        self,
        cx: &mut MacroContext<'_, '_, '_>,
    ) -> alloc::Result<TokenStream> {
        let mut stream = TokenStream::new();
        self.to_tokens(cx, &mut stream)?;
        Ok(stream)
    }
}

impl ToTokens for Quote<'_> {
    fn to_tokens(
        &self,
        context: &mut MacroContext<'_, '_, '_>,
        stream: &mut TokenStream,
    ) -> alloc::Result<()> {
        (self.0)(context, stream)
    }
}

impl fmt::Debug for Quote<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Quote").finish()
    }
}
