// This file was generated by gir (https://github.com/gtk-rs/gir)
// from
// from gir-files
// DO NOT EDIT

use std::boxed::Box as Box_;
use std::pin::Pin;

use glib::prelude::*;
use glib::signal::{SignalHandlerId, connect_raw};
use glib::translate::*;

use crate::{EncodedImage, MemoryFormat, NewFrame, SandboxSelector, ffi};

glib::wrapper! {
    #[doc(alias = "GlyCreator")]
    pub struct Creator(Object<ffi::GlyCreator, ffi::GlyCreatorClass>);

    match fn {
        type_ => || ffi::gly_creator_get_type(),
    }
}

impl Creator {
    #[doc(alias = "gly_creator_new")]
    pub fn new(mime_type: &str) -> Result<Creator, glib::Error> {
        assert_initialized_main_thread!();
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::gly_creator_new(mime_type.to_glib_none().0, &mut error);
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new builder-pattern struct instance to construct [`Creator`]
    /// objects.
    ///
    /// This method returns an instance of
    /// [`CreatorBuilder`](crate::builders::CreatorBuilder) which can be used to
    /// create [`Creator`] objects.
    pub fn builder() -> CreatorBuilder {
        CreatorBuilder::new()
    }

    #[doc(alias = "gly_creator_add_frame")]
    pub fn add_frame(
        &self,
        width: u32,
        height: u32,
        memory_format: MemoryFormat,
        texture: &glib::Bytes,
    ) -> Result<NewFrame, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::gly_creator_add_frame(
                self.to_glib_none().0,
                width,
                height,
                memory_format.into_glib(),
                texture.to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "gly_creator_add_frame_with_stride")]
    pub fn add_frame_with_stride(
        &self,
        width: u32,
        height: u32,
        stride: u32,
        memory_format: MemoryFormat,
        texture: &glib::Bytes,
    ) -> Result<NewFrame, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::gly_creator_add_frame_with_stride(
                self.to_glib_none().0,
                width,
                height,
                stride,
                memory_format.into_glib(),
                texture.to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "gly_creator_add_metadata_key_value")]
    pub fn add_metadata_key_value(&self, key: &str, value: &str) -> bool {
        unsafe {
            from_glib(ffi::gly_creator_add_metadata_key_value(
                self.to_glib_none().0,
                key.to_glib_none().0,
                value.to_glib_none().0,
            ))
        }
    }

    #[doc(alias = "gly_creator_create")]
    pub fn create(&self) -> Result<Option<EncodedImage>, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::gly_creator_create(self.to_glib_none().0, &mut error);
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "gly_creator_create_async")]
    pub fn create_async<P: FnOnce(Result<EncodedImage, glib::Error>) + 'static>(
        &self,
        cancellable: Option<&impl IsA<gio::Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn create_async_trampoline<
            P: FnOnce(Result<EncodedImage, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut gio::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            unsafe {
                let mut error = std::ptr::null_mut();
                let ret = ffi::gly_creator_create_finish(_source_object as *mut _, res, &mut error);
                let result = if error.is_null() {
                    Ok(from_glib_full(ret))
                } else {
                    Err(from_glib_full(error))
                };
                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                    Box_::from_raw(user_data as *mut _);
                let callback: P = callback.into_inner();
                callback(result);
            }
        }
        let callback = create_async_trampoline::<P>;
        unsafe {
            ffi::gly_creator_create_async(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn create_future(
        &self,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<EncodedImage, glib::Error>> + 'static>>
    {
        Box_::pin(gio::GioFuture::new(self, move |obj, cancellable, send| {
            obj.create_async(Some(cancellable), move |res| {
                send.resolve(res);
            });
        }))
    }

    #[doc(alias = "gly_creator_set_encoding_compression")]
    pub fn set_encoding_compression(&self, compression: u8) -> bool {
        unsafe {
            from_glib(ffi::gly_creator_set_encoding_compression(
                self.to_glib_none().0,
                compression,
            ))
        }
    }

    #[doc(alias = "gly_creator_set_encoding_quality")]
    pub fn set_encoding_quality(&self, quality: u8) -> bool {
        unsafe {
            from_glib(ffi::gly_creator_set_encoding_quality(
                self.to_glib_none().0,
                quality,
            ))
        }
    }

    #[doc(alias = "gly_creator_set_sandbox_selector")]
    #[doc(alias = "sandbox-selector")]
    pub fn set_sandbox_selector(&self, sandbox_selector: SandboxSelector) -> bool {
        unsafe {
            from_glib(ffi::gly_creator_set_sandbox_selector(
                self.to_glib_none().0,
                sandbox_selector.into_glib(),
            ))
        }
    }

    #[doc(alias = "mime-type")]
    pub fn mime_type(&self) -> Option<glib::GString> {
        ObjectExt::property(self, "mime-type")
    }

    #[doc(alias = "sandbox-selector")]
    pub fn sandbox_selector(&self) -> SandboxSelector {
        ObjectExt::property(self, "sandbox-selector")
    }

    #[doc(alias = "sandbox-selector")]
    pub fn connect_sandbox_selector_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_sandbox_selector_trampoline<
            F: Fn(&Creator) + Send + Sync + 'static,
        >(
            this: *mut ffi::GlyCreator,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            unsafe {
                let f: &F = &*(f as *const F);
                f(&from_glib_borrow(this))
            }
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                c"notify::sandbox-selector".as_ptr(),
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    notify_sandbox_selector_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

// rustdoc-stripper-ignore-next
/// A [builder-pattern] type to construct [`Creator`] objects.
///
/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
#[must_use = "The builder must be built to be used"]
pub struct CreatorBuilder {
    builder: glib::object::ObjectBuilder<'static, Creator>,
}

impl CreatorBuilder {
    fn new() -> Self {
        Self {
            builder: glib::object::Object::builder(),
        }
    }

    pub fn mime_type(self, mime_type: impl Into<glib::GString>) -> Self {
        Self {
            builder: self.builder.property("mime-type", mime_type.into()),
        }
    }

    pub fn sandbox_selector(self, sandbox_selector: SandboxSelector) -> Self {
        Self {
            builder: self.builder.property("sandbox-selector", sandbox_selector),
        }
    }

    // rustdoc-stripper-ignore-next
    /// Build the [`Creator`].
    #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
    pub fn build(self) -> Creator {
        assert_initialized_main_thread!();
        self.builder.build()
    }
}

unsafe impl Send for Creator {}
unsafe impl Sync for Creator {}
