// 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::{ffi, FwNode, FwResp};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::boxed::Box as Box_;

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].
    ///
    /// ## Properties
    ///
    ///
    /// #### `is-bound`
    ///  Whether this protocol is bound to any instance of HinawaFwNode.
    ///
    /// Readable
    /// <details><summary><h4>FwResp</h4></summary>
    ///
    ///
    /// #### `is-reserved`
    ///  Whether a range of address is reserved or not.
    ///
    /// Readable
    ///
    ///
    /// #### `offset`
    ///  The start offset of reserved address range.
    ///
    /// Readable
    ///
    ///
    /// #### `width`
    ///  The width of reserved address range.
    ///
    /// Readable
    /// </details>
    ///
    /// ## Signals
    ///
    ///
    /// #### `responded`
    ///  Emitted when the node transfers asynchronous packet as response for FCP and the process
    /// successfully read the content of packet.
    ///
    /// The values of @tstamp is unsigned 16 bit integer including higher 3 bits for three low
    /// order bits of second field and the rest 13 bits for cycle field in the format of IEEE
    /// 1394 CYCLE_TIMER register.
    ///
    /// If the version of kernel ABI for Linux FireWire subsystem is less than 6, the value of
    /// @tstamp argument has invalid value (=G_MAXUINT).
    ///
    ///
    /// <details><summary><h4>FwResp</h4></summary>
    ///
    ///
    /// #### `requested`
    ///  Emitted when any node transfers request subaction to local nodes within the address
    /// range reserved in Linux system.
    ///
    /// The handler is expected to call [`FwRespExt::set_resp_frame()`][crate::prelude::FwRespExt::set_resp_frame()] with frame and return
    /// [`FwRcode`][crate::FwRcode] for response subaction.
    ///
    /// The value of @tstamp is unsigned 16 bit integer including higher 3 bits for three low
    /// order bits of second field and the rest 13 bits for cycle field in the format of IEEE
    /// 1394 CYCLE_TIMER register.
    ///
    /// If the version of kernel ABI for Linux FireWire subsystem is less than 6, the value of
    /// tstamp argument has invalid value (=G_MAXUINT). Furthermore, if the version is less than
    /// 4, the src, dst, card, generation arguments have invalid value (=G_MAXUINT).
    ///
    ///
    /// </details>
    ///
    /// # 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: IsA<FwFcp> + '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> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let is_ok = ffi::hinawa_fw_fcp_bind(
                self.as_ref().to_glib_none().0,
                node.as_ref().to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Transfer command frame for FCP. When receiving response frame for FCP, [`responded`][struct@crate::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> {
        let cmd_size = cmd.len() as _;
        unsafe {
            let mut error = std::ptr::null_mut();
            let is_ok = ffi::hinawa_fw_fcp_command(
                self.as_ref().to_glib_none().0,
                cmd.to_glib_none().0,
                cmd_size,
                timeout_ms,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Stop to listen to FCP responses. Any pending transactions are forced to be aborted.
    #[doc(alias = "hinawa_fw_fcp_unbind")]
    fn unbind(&self) {
        unsafe {
            ffi::hinawa_fw_fcp_unbind(self.as_ref().to_glib_none().0);
        }
    }

    /// Whether this protocol is bound to any instance of HinawaFwNode.
    #[doc(alias = "is-bound")]
    fn is_bound(&self) -> bool {
        ObjectExt::property(self.as_ref(), "is-bound")
    }

    #[doc(alias = "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 _,
                c"notify::is-bound".as_ptr() as *const _,
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    notify_is_bound_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl<O: IsA<FwFcp>> FwFcpExt for O {}
