use objc2::{
    extern_class, extern_conformance, extern_methods, msg_send,
    rc::{Allocated, Retained},
};
use objc2_foundation::{CopyingHelper, NSCopying, NSObject, NSObjectProtocol, NSString};

use crate::*;

extern_class!(
    /// Serves as the base descriptor for creating a Metal library.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtl4librarydescriptor?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct MTL4LibraryDescriptor;
);

extern_conformance!(
    unsafe impl NSCopying for MTL4LibraryDescriptor {}
);

unsafe impl CopyingHelper for MTL4LibraryDescriptor {
    type Result = Self;
}

extern_conformance!(
    unsafe impl NSObjectProtocol for MTL4LibraryDescriptor {}
);

impl MTL4LibraryDescriptor {
    extern_methods!(
        /// Provides compile-time options for the Metal library.
        #[unsafe(method(options))]
        #[unsafe(method_family = none)]
        pub fn options(&self) -> Option<Retained<MTLCompileOptions>>;

        /// Setter for [`options`][Self::options].
        ///
        /// This is [copied][objc2_foundation::NSCopying::copy] when set.
        #[unsafe(method(setOptions:))]
        #[unsafe(method_family = none)]
        pub fn set_options(
            &self,
            options: Option<&MTLCompileOptions>,
        );
    );

    pub fn source(&self) -> Option<String> {
        let source: Option<Retained<NSString>> = unsafe { msg_send![self, source] };
        source.map(|value| value.to_string())
    }

    pub fn set_source(
        &self,
        source: Option<&str>,
    ) {
        unsafe {
            let _: () = msg_send![self, setSource: source.map(NSString::from_str).as_deref()];
        }
    }

    pub fn name(&self) -> Option<String> {
        let name: Option<Retained<NSString>> = unsafe { msg_send![self, name] };
        name.map(|value| value.to_string())
    }

    pub fn set_name(
        &self,
        name: Option<&str>,
    ) {
        unsafe {
            let _: () = msg_send![self, setName: name.map(NSString::from_str).as_deref()];
        }
    }
}

/// Methods declared on superclass `NSObject`.
impl MTL4LibraryDescriptor {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub fn new() -> Retained<Self>;
    );
}
