# -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Connet Information Technology Company, Shanghai.

from ctypes import c_void_p
from typing import Literal
from AppKit import (NSView, NSMakeRect, NSWindow, NSWindowCloseButton, NSWindowMiniaturizeButton, NSWindowZoomButton)
from Quartz.CoreGraphics import (CGEventCreateMouseEvent,
                                 kCGEventLeftMouseDown, kCGMouseButtonLeft)
import Cocoa
import objc
from qtpy.QtCore import QPointF, QSize
from qtpy.QtWidgets import QWidget


def ns_move_window(window: QWidget, pos: QPointF):
    """Move QNSWindow using CGMouseEvent"""
    # get the object-c pointer of QNSView and QNSWindow
    nsView = objc.objc_object(c_void_p=c_void_p(int(window.winId())))
    nsWindow = nsView.window()
    cgEvent = CGEventCreateMouseEvent(
        None,
        kCGEventLeftMouseDown,
        (pos.x(), pos.y()),
        kCGMouseButtonLeft
    )
    nsEvent = Cocoa.NSEvent.eventWithCGEvent_(cgEvent)
    nsWindow.performWindowDragWithEvent_(nsEvent)


def ns_set_window_button_visible(window: 'QWidget', button: Literal['close', 'miniaturize', 'zoom'], visible: bool):
    # get the object-c pointer of QNSView and QNSWindow
    nsView = objc.objc_object(c_void_p=c_void_p(int(window.winId())))
    nsWindow = nsView.window()
    if button == 'close':
        nsButton = nsWindow.standardWindowButton_(NSWindowCloseButton)
    elif button == 'miniaturize':
        nsButton = nsWindow.standardWindowButton_(NSWindowMiniaturizeButton)
    elif button == 'zoom':
        nsButton = nsWindow.standardWindowButton_(NSWindowZoomButton)
    else:
        raise ValueError('Invalid button')
    nsButton.setHidden_(not visible)


def ns_set_window_button_enabled(window: 'QWidget', button: Literal['close', 'miniaturize', 'zoom'], enable: bool):
    # get the object-c pointer of QNSView and QNSWindow
    nsView = objc.objc_object(c_void_p=c_void_p(int(window.winId())))
    nsWindow = nsView.window()
    if button == 'close':
        nsButton = nsWindow.standardWindowButton_(NSWindowCloseButton)
    elif button == 'miniaturize':
        nsButton = nsWindow.standardWindowButton_(NSWindowMiniaturizeButton)
    elif button == 'zoom':
        nsButton = nsWindow.standardWindowButton_(NSWindowZoomButton)
    else:
        raise ValueError('Invalid button')
    nsButton.setEnabled_(enable)

