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

use crate::{
    AsyncResult, Cancellable, SocketConnectable, TlsCertificate, TlsCertificateFlags,
    TlsDatabaseLookupFlags, TlsDatabaseVerifyFlags, TlsInteraction,
};
use glib::{prelude::*, translate::*};
use std::{boxed::Box as Box_, fmt, pin::Pin, ptr};

glib::wrapper! {
    #[doc(alias = "GTlsDatabase")]
    pub struct TlsDatabase(Object<ffi::GTlsDatabase, ffi::GTlsDatabaseClass>);

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

impl TlsDatabase {
    pub const NONE: Option<&'static TlsDatabase> = None;
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::TlsDatabase>> Sealed for T {}
}

pub trait TlsDatabaseExt: IsA<TlsDatabase> + sealed::Sealed + 'static {
    #[doc(alias = "g_tls_database_create_certificate_handle")]
    fn create_certificate_handle(
        &self,
        certificate: &impl IsA<TlsCertificate>,
    ) -> Option<glib::GString> {
        unsafe {
            from_glib_full(ffi::g_tls_database_create_certificate_handle(
                self.as_ref().to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
            ))
        }
    }

    #[doc(alias = "g_tls_database_lookup_certificate_for_handle")]
    fn lookup_certificate_for_handle(
        &self,
        handle: &str,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<Option<TlsCertificate>, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_for_handle(
                self.as_ref().to_glib_none().0,
                handle.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "g_tls_database_lookup_certificate_for_handle_async")]
    fn lookup_certificate_for_handle_async<
        P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static,
    >(
        &self,
        handle: &str,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<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 lookup_certificate_for_handle_async_trampoline<
            P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_for_handle_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 = lookup_certificate_for_handle_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_lookup_certificate_for_handle_async(
                self.as_ref().to_glib_none().0,
                handle.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn lookup_certificate_for_handle_future(
        &self,
        handle: &str,
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseLookupFlags,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<TlsCertificate, glib::Error>> + 'static>>
    {
        let handle = String::from(handle);
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.lookup_certificate_for_handle_async(
                    &handle,
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    #[doc(alias = "g_tls_database_lookup_certificate_issuer")]
    fn lookup_certificate_issuer(
        &self,
        certificate: &impl IsA<TlsCertificate>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<TlsCertificate, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_issuer(
                self.as_ref().to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "g_tls_database_lookup_certificate_issuer_async")]
    fn lookup_certificate_issuer_async<P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static>(
        &self,
        certificate: &impl IsA<TlsCertificate>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<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 lookup_certificate_issuer_async_trampoline<
            P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_issuer_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 = lookup_certificate_issuer_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_lookup_certificate_issuer_async(
                self.as_ref().to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn lookup_certificate_issuer_future(
        &self,
        certificate: &(impl IsA<TlsCertificate> + Clone + 'static),
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseLookupFlags,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<TlsCertificate, glib::Error>> + 'static>>
    {
        let certificate = certificate.clone();
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.lookup_certificate_issuer_async(
                    &certificate,
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    #[doc(alias = "g_tls_database_lookup_certificates_issued_by")]
    fn lookup_certificates_issued_by(
        &self,
        issuer_raw_dn: &glib::ByteArray,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<Vec<TlsCertificate>, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificates_issued_by(
                self.as_ref().to_glib_none().0,
                issuer_raw_dn.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(FromGlibPtrContainer::from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "g_tls_database_lookup_certificates_issued_by_async")]
    fn lookup_certificates_issued_by_async<
        P: FnOnce(Result<Vec<TlsCertificate>, glib::Error>) + 'static,
    >(
        &self,
        issuer_raw_dn: &glib::ByteArray,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<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 lookup_certificates_issued_by_async_trampoline<
            P: FnOnce(Result<Vec<TlsCertificate>, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificates_issued_by_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(FromGlibPtrContainer::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 = lookup_certificates_issued_by_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_lookup_certificates_issued_by_async(
                self.as_ref().to_glib_none().0,
                issuer_raw_dn.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn lookup_certificates_issued_by_future(
        &self,
        issuer_raw_dn: &glib::ByteArray,
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseLookupFlags,
    ) -> Pin<
        Box_<dyn std::future::Future<Output = Result<Vec<TlsCertificate>, glib::Error>> + 'static>,
    > {
        let issuer_raw_dn = issuer_raw_dn.clone();
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.lookup_certificates_issued_by_async(
                    &issuer_raw_dn,
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    #[doc(alias = "g_tls_database_verify_chain")]
    fn verify_chain(
        &self,
        chain: &impl IsA<TlsCertificate>,
        purpose: &str,
        identity: Option<&impl IsA<SocketConnectable>>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseVerifyFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<TlsCertificateFlags, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_database_verify_chain(
                self.as_ref().to_glib_none().0,
                chain.as_ref().to_glib_none().0,
                purpose.to_glib_none().0,
                identity.map(|p| p.as_ref()).to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "g_tls_database_verify_chain_async")]
    fn verify_chain_async<P: FnOnce(Result<TlsCertificateFlags, glib::Error>) + 'static>(
        &self,
        chain: &impl IsA<TlsCertificate>,
        purpose: &str,
        identity: Option<&impl IsA<SocketConnectable>>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseVerifyFlags,
        cancellable: Option<&impl IsA<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 verify_chain_async_trampoline<
            P: FnOnce(Result<TlsCertificateFlags, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret =
                ffi::g_tls_database_verify_chain_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(from_glib(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 = verify_chain_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_verify_chain_async(
                self.as_ref().to_glib_none().0,
                chain.as_ref().to_glib_none().0,
                purpose.to_glib_none().0,
                identity.map(|p| p.as_ref()).to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn verify_chain_future(
        &self,
        chain: &(impl IsA<TlsCertificate> + Clone + 'static),
        purpose: &str,
        identity: Option<&(impl IsA<SocketConnectable> + Clone + 'static)>,
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseVerifyFlags,
    ) -> Pin<
        Box_<dyn std::future::Future<Output = Result<TlsCertificateFlags, glib::Error>> + 'static>,
    > {
        let chain = chain.clone();
        let purpose = String::from(purpose);
        let identity = identity.map(ToOwned::to_owned);
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.verify_chain_async(
                    &chain,
                    &purpose,
                    identity.as_ref().map(::std::borrow::Borrow::borrow),
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }
}

impl<O: IsA<TlsDatabase>> TlsDatabaseExt for O {}

impl fmt::Display for TlsDatabase {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("TlsDatabase")
    }
}
