import tkinter as tk
from PIL import ImageGrab, ImageTk
import wanguo_config

class RegionSelection:
    def __init__(self, root, screenshot):
        self.root = root
        self.start_x = None
        self.start_y = None
        self.end_x = None
        self.end_y = None
        self.rectangle = None
        
        # 创建截图显示窗口
        self.screenshot_window = tk.Toplevel(self.root)
        self.screenshot_window.attributes('-fullscreen', True)
        self.screenshot_window.attributes('-alpha', 0.3)
        self.screenshot_canvas = tk.Canvas(self.screenshot_window, bg="white")
        self.screenshot_canvas.pack(fill=tk.BOTH, expand=True)
        self.screenshot_photo = ImageTk.PhotoImage(screenshot)
        self.screenshot_canvas.create_image(0, 0, image=self.screenshot_photo, anchor=tk.NW)
        
        # 绑定鼠标事件
        self.screenshot_canvas.bind("<ButtonPress-1>", self.on_button_press)
        self.screenshot_canvas.bind("<B1-Motion>", self.on_button_motion)
        self.screenshot_canvas.bind("<ButtonRelease-1>", self.on_button_release)
        
    def on_button_press(self, event):
        self.start_x = event.x
        self.start_y = event.y
        
    def on_button_motion(self, event):
        if self.rectangle is not None:
            self.screenshot_canvas.delete(self.rectangle)
        
        self.end_x = event.x
        self.end_y = event.y
        
        self.rectangle = self.screenshot_canvas.create_rectangle(self.start_x, self.start_y, self.end_x, self.end_y, outline="red")
        
    def on_button_release(self, event):
        if self.rectangle is not None:
            self.screenshot_canvas.delete(self.rectangle)
        
        # 返回区域坐标（相对于全屏）
        x1 = min(self.start_x, self.end_x)
        y1 = min(self.start_y, self.end_y)
        x2 = max(self.start_x, self.end_x)
        y2 = max(self.start_y, self.end_y)
        
        # 转换为相对于屏幕左上角的坐标
        x1 += self.screenshot_window.winfo_rootx()
        y1 += self.screenshot_window.winfo_rooty()
        x2 += self.screenshot_window.winfo_rootx()
        y2 += self.screenshot_window.winfo_rooty()
        
        # 返回具体坐标
        print("选择的区域坐标：", (x1, y1, x2, y2))
        wanguo_config.g_region = (x1, y1, x2, y2)
        
        # 关闭截图显示窗口
        self.screenshot_window.destroy()
        
if __name__ == "__main__":
    # 初始化Tkinter窗口
    root = tk.Tk()
    
    
    # 获取全屏截图
    screenshot = ImageGrab.grab()
    
    # 创建区域选择对象
    region_selection = RegionSelection(root, screenshot)
    
    # 运行Tkinter窗口主
    root.mainloop()