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

use crate::FwNode;
use crate::FwResp;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use std::ptr;

glib::wrapper! {
    /// A FCP transaction executor to node in IEEE 1394 bus.
    /// [`FwFcp`][crate::FwFcp] supports Function Control Protocol (FCP) in IEC 61883-1. FCP transaction consists
    /// of a pair of asynchronous transactions for command and response, while the protocol has no
    /// mechanism to match them. In AV/C Digital Interface Command Set General Specification Version 4.2
    /// (Sep 1 2004, 1394TA), they are loosely matched by the content of their frames, and this class
    /// employs the way.
    ///
    /// Any of transaction frames should be aligned to 8 bit (1 byte). This class is an application of
    /// [`FwReq`][crate::FwReq] / [`FwResp`][crate::FwResp].
    ///
    /// # Implements
    ///
    /// [`FwFcpExt`][trait@crate::prelude::FwFcpExt], [`FwRespExt`][trait@crate::prelude::FwRespExt], [`FwFcpExtManual`][trait@crate::prelude::FwFcpExtManual], [`FwRespExtManual`][trait@crate::prelude::FwRespExtManual]
    #[doc(alias = "HinawaFwFcp")]
    pub struct FwFcp(Object<ffi::HinawaFwFcp, ffi::HinawaFwFcpClass>) @extends FwResp;

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

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

    /// Instantiate [`FwFcp`][crate::FwFcp] object and return the instance.
    ///
    /// # Returns
    ///
    /// an instance of [`FwFcp`][crate::FwFcp].
    #[doc(alias = "hinawa_fw_fcp_new")]
    pub fn new() -> FwFcp {
        unsafe { from_glib_full(ffi::hinawa_fw_fcp_new()) }
    }
}

impl Default for FwFcp {
    fn default() -> Self {
        Self::new()
    }
}

/// Trait containing the part of [`struct@FwFcp`] methods.
///
/// # Implementors
///
/// [`FwFcp`][struct@crate::FwFcp]
pub trait FwFcpExt: 'static {
    /// Start to listen to FCP responses.
    /// ## `node`
    /// A [`FwNode`][crate::FwNode].
    ///
    /// # Returns
    ///
    /// TRUE if the overall operation finishes successfully, otherwise FALSE.
    #[doc(alias = "hinawa_fw_fcp_bind")]
    fn bind(&self, node: &impl IsA<FwNode>) -> Result<(), glib::Error>;

    /// Transfer command frame for FCP. When receiving response frame for FCP, `signal::FwFcp::responded`
    /// signal is emitted.
    /// ## `cmd`
    /// An array with elements for request byte data. The value of this
    ///  argument should point to the array and immutable.
    /// ## `timeout_ms`
    /// The timeout to wait for response subaction of transaction for command frame.
    ///
    /// # Returns
    ///
    /// TRUE if the overall operation finishes successfully, otherwise FALSE.
    #[doc(alias = "hinawa_fw_fcp_command")]
    fn command(&self, cmd: &[u8], timeout_ms: u32) -> Result<(), glib::Error>;

    /// Stop to listen to FCP responses. Any pending transactions are forced to be aborted.
    #[doc(alias = "hinawa_fw_fcp_unbind")]
    fn unbind(&self);

    /// Whether this protocol is bound to any instance of HinawaFwNode.
    #[doc(alias = "is-bound")]
    fn is_bound(&self) -> bool;

    #[doc(alias = "is-bound")]
    fn connect_is_bound_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}

impl<O: IsA<FwFcp>> FwFcpExt for O {
    fn bind(&self, node: &impl IsA<FwNode>) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let _ = ffi::hinawa_fw_fcp_bind(
                self.as_ref().to_glib_none().0,
                node.as_ref().to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn command(&self, cmd: &[u8], timeout_ms: u32) -> Result<(), glib::Error> {
        let cmd_size = cmd.len() as usize;
        unsafe {
            let mut error = ptr::null_mut();
            let _ = ffi::hinawa_fw_fcp_command(
                self.as_ref().to_glib_none().0,
                cmd.to_glib_none().0,
                cmd_size,
                timeout_ms,
                &mut error,
            );
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn unbind(&self) {
        unsafe {
            ffi::hinawa_fw_fcp_unbind(self.as_ref().to_glib_none().0);
        }
    }

    fn is_bound(&self) -> bool {
        glib::ObjectExt::property(self.as_ref(), "is-bound")
    }

    fn connect_is_bound_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_is_bound_trampoline<P: IsA<FwFcp>, F: Fn(&P) + 'static>(
            this: *mut ffi::HinawaFwFcp,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(FwFcp::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::is-bound\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_is_bound_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

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