from cairocffi.test_xcb import xcffib
from libqtile import hook
from libqtile.window import Window, Static


class KuroStatic(Static):

    @staticmethod
    def create(window: Window, screen, x=None, y=None, width=None, height=None):
        """Makes this window a static window, attached to a Screen

        If any of the arguments are left unspecified, the values given by the
        window itself are used instead. So, for a window that's aware of its
        appropriate size and location (like dzen), you don't have to specify
        anything.
        """
        window.defunct = True
        if isinstance(screen, int):
            screen = window.qtile.screens[screen]
        if window.group:
            window.group.remove(window)
        s = KuroStatic(window.window, window.qtile, screen, x, y, width, height)
        window.qtile.windowMap[window.window.wid] = s
        hook.fire("client_managed", s)
        return s

    def __init__(self, win, qtile, screen, x=None, y=None, width=None, height=None):
        Static.__init__(self, win, qtile, screen, x=x, y=y, width=width, height=height)
        self.above = True
        self.placed_x = x
        self.placed_y = y
        if None not in (x, y, width, height):
            self.place(x, y, width, height, 0, 0, above=self.above)

    def set_above(self, above: bool):
        self.above = above
        self.reposition(self.placed_x, self.placed_y)

    def reposition(self, x, y, above=None):
        self.placed_x = x
        self.placed_y = y
        if above is not None:
            self.above = above
        self.place(x, y, self.width, self.height, 0, 0, above=self.above)

    def handle_ConfigureRequest(self, e):
        cw = xcffib.xproto.ConfigWindow
        if self.conf_x is None and e.value_mask & cw.X:
            self.x = e.x
        if self.conf_y is None and e.value_mask & cw.Y:
            self.y = e.y
        if self.conf_width is None and e.value_mask & cw.Width:
            self.width = e.width
        if self.conf_height is None and e.value_mask & cw.Height:
            self.height = e.height

        self.place(
            self.screen.x + self.x,
            self.screen.y + self.y,
            self.width,
            self.height,
            self.borderwidth,
            self.bordercolor,
            above=self.above
        )
        return False

    def __repr__(self):
        return "KuroStatic(%r)" % self.name