import json
import tkinter as tk


def fetch_mapping(fine_name, figer_nameset):
    window = tk.Tk()

    type_list_layer1 = figer_nameset['layer1']
    type_layer_mapping = figer_nameset['mapping']
    assert len(type_list_layer1) == 49

    def second_layer_button_handler(event, fine_name, first, second):
        with open(crowd_mapping_fn, 'r', encoding='utf8') as fp:
            crowd_mapping = json.load(fp)
        crowd_mapping[fine_name] = [first, second]
        with open(crowd_mapping_fn, 'w', encoding='utf8') as fp:
            json.dump(crowd_mapping, fp, ensure_ascii=False)

    def first_layer_button_handler(event, fine_name, text):
        designated_first_layer_type = text
        second_layer_candidates = type_layer_mapping[text]
        second_window = tk.Tk()
        name_label = tk.Label(master=second_window, text=fine_name)
        second_window.columnconfigure(i, weight=1, minsize=75)
        second_window.rowconfigure(i, weight=1, minsize=50)
        for a in range(5):
            if 5*a >= second_layer_candidates:
                break
            for b in range(5):
                if 5*a+b >= len(second_layer_candidates):
                    break
                frame = tk.Frame(
                    master=second_window,
                    relief=tk.RAISED,
                    borderwidth=1
                )
                frame.grid(row=a, column=b, padx=5, pady=5)
                button = tk.Button(master=frame, text=second_layer_candidates[5*a+b])
                button.bind("<Button-1>", lambda event, fine_name=name_label, first=designated_first_layer_type, second=second_layer_candidates[5*a+b]: second_layer_button_handler(event, fine_name, first, second))
        second_window.mainloop()

    name_label = tk.Label(master=window, text=fine_name)
    name_label.pack()
    for i in range(7):
        window.columnconfigure(i, weight=1, minsize=75)
        window.rowconfigure(i, weight=1, minsize=50)

        for j in range(7):
            frame = tk.Frame(
                master=window,
                relief=tk.RAISED,
                borderwidth=1
            )
            frame.grid(row=i, column=j, padx=5, pady=5)

            button = tk.Button(master=frame, text=type_list_layer1[7*i+j])
            button.bind("<Button-1>", lambda event, fine_name=fine_name, text=type_list_layer1[7*i+j]: first_layer_button_handler(event, fine_name, text))
            button.pack(padx=5, pady=5)
    window.mainloop()



