use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::Token;

use super::{
    common::{Attributes, TypeRepr},
    document::DocumentItemAttributes,
};

#[derive(Clone)]
pub struct NewType {
    pub attributes: Attributes,
    pub name: syn::Ident,
    // No need for a full type, since only certain primitives are allowed
    pub repr: TypeRepr,
}

impl DocumentItemAttributes for NewType {
    fn extend_attributes<I: IntoIterator<Item = syn::Attribute>>(&mut self, attrs: I) {
        self.attributes.extend(attrs);
    }
}

impl syn::parse::Parse for NewType {
    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
        let attributes = input.parse()?;
        let name = input.parse()?;
        let repr = input.parse()?;
        input.parse::<Token![;]>()?;
        Ok(Self {
            attributes,
            name,
            repr,
        })
    }
}

impl ToTokens for NewType {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            attributes,
            name,
            repr,
        } = self;
        tokens.extend(quote! {
            #attributes
            newtype #name #repr;
        })
    }
}
