//! # DBus interface proxy for: `org.asuslinux.Daemon`
//!
//! This code was generated by `zbus-xmlgen` `1.0.0` from DBus introspection data.
//! Source: `Interface '/org/asuslinux/Led' from service 'org.asuslinux.Daemon' on system bus`.
//!
//! You may prefer to adapt it, instead of using it verbatim.
//!
//! More information can be found in the
//! [Writing a client proxy](https://zeenix.pages.freedesktop.org/zbus/client.html)
//! section of the zbus documentation.
//!
//! This DBus object implements
//! [standard DBus interfaces](https://dbus.freedesktop.org/doc/dbus-specification.html),
//! (`org.freedesktop.DBus.*`) for which the following zbus proxies can be used:
//!
//! * [`zbus::fdo::PeerProxy`]
//! * [`zbus::fdo::IntrospectableProxy`]
//! * [`zbus::fdo::PropertiesProxy`]
//!
//! …consequently `zbus-xmlgen` did not generate code for the above interfaces.

use std::sync::mpsc::Sender;

use zbus::{dbus_proxy, Connection, Result};

use rog_aura::{AuraEffect, KeyColourArray, LedBrightness, LedPowerStates};

const BLOCKING_TIME: u64 = 40; // 100ms = 10 FPS, max 50ms = 20 FPS, 40ms = 25 FPS

#[dbus_proxy(
    interface = "org.asuslinux.Daemon",
    default_path = "/org/asuslinux/Led"
)]
trait Daemon {
    /// NextLedMode method
    fn next_led_mode(&self) -> zbus::Result<()>;

    /// PrevLedMode method
    fn prev_led_mode(&self) -> zbus::Result<()>;

    /// Toggle to next led brightness
    fn next_led_brightness(&self) -> zbus::Result<()>;

    /// Toggle to previous led brightness
    fn prev_led_brightness(&self) -> zbus::Result<()>;

    /// SetBrightness method
    fn set_brightness(&self, brightness: LedBrightness) -> zbus::Result<()>;

    /// SetLedMode method
    fn set_led_mode(&self, effect: &AuraEffect) -> zbus::Result<()>;

    /// SetAwakeEnabled method
    fn set_awake_enabled(&self, enabled: bool) -> zbus::Result<()>;

    /// SetSleepEnabled method
    fn set_sleep_enabled(&self, enabled: bool) -> zbus::Result<()>;

    /// NotifyLed signal
    #[dbus_proxy(signal)]
    fn notify_led(&self, data: AuraEffect) -> zbus::Result<()>;

    #[dbus_proxy(signal)]
    fn notify_power_states(&self, data: LedPowerStates) -> zbus::Result<()>;

    /// LedBrightness property
    #[dbus_proxy(property)]
    fn led_brightness(&self) -> zbus::Result<i16>;

    /// LedMode property
    #[dbus_proxy(property)]
    fn led_mode(&self) -> zbus::Result<String>;

    /// LedModes property
    #[dbus_proxy(property)]
    fn led_modes(&self) -> zbus::Result<String>;

    #[dbus_proxy(property)]
    fn awake_enabled(&self) -> zbus::Result<bool>;

    #[dbus_proxy(property)]
    fn sleep_enabled(&self) -> zbus::Result<bool>;
}

pub struct LedProxy<'a>(DaemonProxy<'a>);

impl<'a> LedProxy<'a> {
    #[inline]
    pub fn new(conn: &Connection) -> Result<Self> {
        Ok(LedProxy(DaemonProxy::new(conn)?))
    }

    #[inline]
    pub fn proxy(&self) -> &DaemonProxy<'a> {
        &self.0
    }

    #[inline]
    pub fn get_led_brightness(&self) -> Result<i16> {
        self.0.led_brightness()
    }

    #[inline]
    pub fn set_led_brightness(&self, level: LedBrightness) -> Result<()> {
        self.0.set_brightness(level)?;
        Ok(())
    }

    /// Set the keyboard LED to enabled while the device is awake
    #[inline]
    pub fn set_awake_enabled(&self, enabled: bool) -> Result<()> {
        self.0.set_awake_enabled(enabled)?;
        Ok(())
    }

    /// Set the keyboard LED suspend animation to enabled while the device is suspended
    #[inline]
    pub fn set_sleep_enabled(&self, enabled: bool) -> Result<()> {
        self.0.set_sleep_enabled(enabled)?;
        Ok(())
    }

    #[inline]
    pub fn next_led_mode(&self) -> Result<()> {
        self.0.next_led_mode()
    }

    #[inline]
    pub fn prev_led_mode(&self) -> Result<()> {
        self.0.prev_led_mode()
    }

    #[inline]
    pub fn next_led_brightness(&self) -> Result<()> {
        self.0.next_led_brightness()
    }

    #[inline]
    pub fn prev_led_brightness(&self) -> Result<()> {
        self.0.prev_led_brightness()
    }

    #[inline]
    pub fn set_led_mode(&self, mode: &AuraEffect) -> Result<()> {
        self.0.set_led_mode(mode)
    }

    #[inline]
    pub fn awake_enabled(&self) -> Result<bool> {
        self.0.awake_enabled()
    }

    #[inline]
    pub fn sleep_enabled(&self) -> Result<bool> {
        self.0.sleep_enabled()
    }

    /// Write a single colour block.
    ///
    /// Intentionally blocks for 10ms after sending to allow the block to
    /// be written to the keyboard EC. This should not be async.
    #[inline]
    pub fn set_per_key(&self, key_colour_array: &KeyColourArray) -> Result<()> {
        let group = key_colour_array.get();
        let mut vecs = Vec::with_capacity(group.len());
        for v in group {
            vecs.push(v.to_vec());
        }
        // TODO: let mode = AuraModes::PerKey(vecs);
        // self.set_led_mode(&mode)?;

        std::thread::sleep(std::time::Duration::from_millis(BLOCKING_TIME));

        // if self.stop.load(Ordering::Relaxed) {
        //     println!("Keyboard backlight was changed, exiting");
        //     std::process::exit(1)
        // }
        Ok(())
    }

    /// This method must always be called before the very first write to initialise
    /// the keyboard LED EC in the correct mode
    #[inline]
    pub fn init_effect(&self) -> Result<()> {
        // TODO: let mode = AuraModes::PerKey(vec![vec![]]);
        // self.0.set_led_mode(&serde_json::to_string(&mode).unwrap())
        Ok(())
    }

    #[inline]
    pub fn connect_notify_led(&self, send: Sender<AuraEffect>) -> zbus::fdo::Result<()> {
        self.0.connect_notify_led(move |data| {
            send.send(data)
                .map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
            Ok(())
        })
    }

    #[inline]
    pub fn connect_notify_power_states(
        &self,
        send: Sender<LedPowerStates>,
    ) -> zbus::fdo::Result<()> {
        self.0.connect_notify_power_states(move |data| {
            send.send(data)
                .map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
            Ok(())
        })
    }
}
