#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 7m
#  in conjunction with Tcl version 8.6
#    Aug 09, 2021 06:18:29 AM PDT  platform: Linux

import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *

import dual
from ScrolledCheckedListBox import ScrolledCheckedListBox
from ScrolledFrame import ScrolledFrame

WIDTH = 200
width = WIDTH
HEIGHT = 200
height = HEIGHT
pict = {}
id = {}
label = {}
num = 30

import tkinter.messagebox

def main(*args):
    '''Main entry point for the application.'''
    global root
    root = tk.Tk()
    root.protocol( 'WM_DELETE_WINDOW' , root.destroy)
    # Creates a toplevel widget.
    global _top39, _w39
    _top39 = root
    _w39 = dual.Toplevel1(_top39)
    init(_top39, _w39)
    root.mainloop()

def on_click(s=None):
    # ======================================================
    # On event, scrolled frame returns a list containing:
    #    item number selected
    #    text of checkbox selected
    # ======================================================
    update_label()
    print(w.Custom1_4.get())

def on_btnClearChecks():
    w.Custom1_4.clear()
    w.Message1.configure(text='')

def on_btnExit(*args):
    destroy_window()

def on_btnGetChecks(*args):
    lst = w.Custom1_4.get()
    print(lst)

def quit(*args):
    sys.exit()

def refresh(*args):
    clean_window()
    display_buttons()

def zoom(*args):
    global width, height
    p1 = args[0]
    if p1 == "in":
        width += 100
        height += 100
        refresh()
    elif p1 == "default":
        width = WIDTH
        height = HEIGHT
        refresh()
    elif p1 == "out":
        w = width - 200
        width = max(width-100, WIDTH)
        height = max(height-100, WIDTH)
        if w != 0:
            refresh()
    else:
        width = p1
        height = p1
        refresh()
        sys.stdout.flush()

def display_buttons():
   global pict, label
   from PIL import Image, ImageTk
   pict = {}
   label = {}
   root.update_idletasks()
   frame_width = w.Custom1.window_width()
   no_thumbnails_per_row = frame_width // width
   remainder = frame_width % width
   if remainder < 10 * no_thumbnails_per_row:
       no_thumbnails_per_row -= 1
   no_thumbnails_per_row = max(no_thumbnails_per_row, 1)
   row = 0
   bg_color = top_level.cget("background")
   # For this example I only use one image and one thumbnail image.
   image =  "pt-arena_hills.jpg"
   date = "9-24-2008"
   masterImg = Image.open(image)
   masterImg.thumbnail((width,height))
   thumbnail = masterImg.copy()
   original = ImageTk.PhotoImage(thumbnail)
   n = 2
   for i in range(num):
      row, col = divmod(i,no_thumbnails_per_row)
      # The expression n*rows is 2*rows, one for image and one date.
      pict[i] = tk.Button(w.Custom1.inner_frame, image=original,
                       background=bg_color)
      pict[i].image = original
      pict[i].grid(row=n*row, column=col, sticky=W+E+S+N)
      id[pict[i].winfo_id()] = i
      label[i] = tk.Label(w.Custom1.inner_frame, text=date, background=bg_color)
      label[i].grid(row=n*row+1, column=col, sticky=W+E+S+N)
      pict[i].bind('<Button-1>', message)
      pict[i].bind('<Button-3>', dual.popup1)

def message(event):
    selected = id[event.widget.winfo_id()]
    tkinter.messagebox.showinfo("Selection", "You selected image: " + str(selected))

def clean_window():
    # Remove images from the list.
    for i in reversed(range(30)):
        try:
            pict[i].destroy()
            label[i].destroy()
        except:
            pass

def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
    display_buttons()
    # ======================================================
    # Our init code
    # ======================================================
    global ListInfo, ListInfo2
    # =======================================================
    # Create the list of text items for the ScrolledCheckBox
    # =======================================================
    ListInfo = ['Appetizer', 'Snack', 'Barbecue', 'Cake', 'Candy', 'Beverages',
                'Breads', 'Canning & Freezing', 'Cookies', 'Desserts', 'Meats',
                'Main Dish', 'Snacks', 'Rice', 'Poultry', 'Sauces', 'Soups',
                'American', 'Mexican', 'Asian']
    ListInfo2 = [['Appetizer', 1], ['Snack', 2], ['Barbecue', 3], ['Cake', 4],
                 ['Candy', 5], ['Beverages', 6], ['Breads', 7],
                 ['Canning & Freezing', 8], ['Cookies', 9], ['Desserts', 10],
                 ['Eggs & Cheese', 11], ['Fish & Seafood', 12], ['Meats', 13],
                 ['Pies', 14], ['Poultry', 15], ['Rice', 16], ['Pasta', 17],
                 ['Cereal', 18], ['Salads & Dressings', 19], ['Sauces', 20]]

    initialize_custom_widget()

def initialize_custom_widget():
    w.Custom1_4.cback = on_click
    # To use a single list of item names comment out the next line and
    # uncomment the second line down.
    w.Custom1_4.load(ListInfo2)
    # w.Custom1_4.load(ListInfo)
    clear_label()
    set_labels()


# ======================================================
# function set_labels()
# ------------------------------------------------------
# This calls the .set() method of the ScrolledCheckBox
# class.  That method allows items selected on initialization
# of a form.  Useful when loading a list of items for editing or
# showing already selected items from a database.
# ======================================================
def set_labels():
    w.Custom1_4.set(['Appetizer', 'Candy', 'Breads'])
    update_label()


# ======================================================
# function UpdateLabel()
# ------------------------------------------------------
# This function will update the message widget with the
# text of each selected item for quick visual reference.
# Usually not needed.
# ======================================================
def update_label():
    print ('update_label starting')
    dat = w.Custom1_4.get()
    lst = []
    for x in dat:
        # print(len(x),x)
        if len(x) == 2:
            t = x[0]
            k = x[1]
            lst.append(t)
        else:
            lst.append(x)
    s = ", ".join(lst)
    w.Message1.configure(text=s)


# ======================================================
# function ClearLabel()
# ------------------------------------------------------
# simply clears the message widget
# ======================================================
def clear_label():
    w.Message1.configure(text="")

def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None

#Custom_d = Frame     # To be updated by user with name of custom widget.
Custom_d= ScrolledFrame

#Custom_g = Frame     # To be updated by user with name of custom widget.
Custom_g = ScrolledCheckedListBox

if __name__ == '__main__':
    dual.start_up()




