use {
    crate::{
        client::{Client, ClientError},
        leaks::Tracker,
        object::{Object, Version},
        rect::Rect,
        state::State,
        tree::ToplevelOpt,
        wire::{XxForeignToplevelGeometryTrackerV1Id, xx_foreign_toplevel_geometry_tracker_v1::*},
    },
    std::rc::Rc,
    thiserror::Error,
};

pub struct XxForeignToplevelGeometryTrackerV1 {
    pub id: XxForeignToplevelGeometryTrackerV1Id,
    pub client: Rc<Client>,
    pub tracker: Tracker<Self>,
    pub toplevel: ToplevelOpt,
    pub version: Version,
}

impl XxForeignToplevelGeometryTrackerV1 {
    fn detach(&self) {
        if let Some(tl) = self.toplevel.get() {
            tl.tl_data()
                .geometry_trackers
                .remove(&(self.client.id, self.id));
        }
    }

    pub fn send_finished(&self) {
        self.client.event(Finished { self_id: self.id });
    }

    pub fn send_geometry_update(&self, rect: &Rect, state: &State) {
        if rect.is_empty() {
            self.client.event(Done { self_id: self.id });
            return;
        }
        for output in state.globals.outputs.lock().values() {
            let output_pos = output.pos.get();
            if !rect.intersects(&output_pos) {
                continue;
            }
            let scale = output.persistent.scale.get().to_f64();
            let rel_x = rect.x1() - output_pos.x1();
            let rel_y = rect.y1() - output_pos.y1();
            let hw_x = (rel_x as f64 * scale).round() as i32;
            let hw_y = (rel_y as f64 * scale).round() as i32;
            let hw_w = (rect.width() as f64 * scale).round() as u32;
            let hw_h = (rect.height() as f64 * scale).round() as u32;
            self.client.event(Geometry {
                self_id: self.id,
                output: output.name.raw(),
                x: hw_x,
                y: hw_y,
                width: hw_w,
                height: hw_h,
            });
        }
        self.client.event(Done { self_id: self.id });
    }
}

impl XxForeignToplevelGeometryTrackerV1RequestHandler for XxForeignToplevelGeometryTrackerV1 {
    type Error = XxForeignToplevelGeometryTrackerV1Error;

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

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

impl Object for XxForeignToplevelGeometryTrackerV1 {
    fn break_loops(&self) {
        self.detach();
    }
}

simple_add_obj!(XxForeignToplevelGeometryTrackerV1);

#[derive(Debug, Error)]
pub enum XxForeignToplevelGeometryTrackerV1Error {
    #[error(transparent)]
    ClientError(Box<ClientError>),
}
efrom!(XxForeignToplevelGeometryTrackerV1Error, ClientError);
