use {
    crate::{
        client::{Client, ClientError},
        globals::{Global, GlobalName},
        ifs::hyprland_focus_grab_v1::HyprlandFocusGrabV1,
        leaks::Tracker,
        object::{Object, Version},
        wire::{HyprlandFocusGrabManagerV1Id, hyprland_focus_grab_manager_v1::*},
    },
    std::rc::Rc,
    thiserror::Error,
};

pub struct HyprlandFocusGrabManagerV1Global {
    pub name: GlobalName,
}

impl HyprlandFocusGrabManagerV1Global {
    pub fn new(name: GlobalName) -> Self {
        Self { name }
    }

    fn bind_(
        self: Rc<Self>,
        id: HyprlandFocusGrabManagerV1Id,
        client: &Rc<Client>,
        version: Version,
    ) -> Result<(), HyprlandFocusGrabManagerV1Error> {
        let obj = Rc::new(HyprlandFocusGrabManagerV1 {
            id,
            client: client.clone(),
            tracker: Default::default(),
            version,
        });
        track!(client, obj);
        client.add_client_obj(&obj)?;
        Ok(())
    }
}

pub struct HyprlandFocusGrabManagerV1 {
    pub id: HyprlandFocusGrabManagerV1Id,
    pub client: Rc<Client>,
    pub tracker: Tracker<Self>,
    pub version: Version,
}

impl HyprlandFocusGrabManagerV1RequestHandler for HyprlandFocusGrabManagerV1 {
    type Error = HyprlandFocusGrabManagerV1Error;

    fn destroy(&self, _req: Destroy, _slf: &Rc<Self>) -> Result<(), Self::Error> {
        self.client.remove_obj(self)?;
        Ok(())
    }

    fn create_grab(&self, req: CreateGrab, _slf: &Rc<Self>) -> Result<(), Self::Error> {
        let grab = Rc::new(HyprlandFocusGrabV1::new(
            req.grab,
            &self.client,
            self.version,
        ));
        track!(self.client, grab);
        self.client.add_client_obj(&grab)?;
        Ok(())
    }
}

global_base!(
    HyprlandFocusGrabManagerV1Global,
    HyprlandFocusGrabManagerV1,
    HyprlandFocusGrabManagerV1Error
);

impl Global for HyprlandFocusGrabManagerV1Global {
    fn version(&self) -> u32 {
        1
    }
}

simple_add_global!(HyprlandFocusGrabManagerV1Global);

object_base! {
    self = HyprlandFocusGrabManagerV1;
    version = self.version;
}

impl Object for HyprlandFocusGrabManagerV1 {}

simple_add_obj!(HyprlandFocusGrabManagerV1);

#[derive(Debug, Error)]
pub enum HyprlandFocusGrabManagerV1Error {
    #[error(transparent)]
    ClientError(Box<ClientError>),
}

efrom!(HyprlandFocusGrabManagerV1Error, ClientError);
