#!/usr/bin/env python3
# encoding: utf-8

import tkinter as tk
from tkinter import messagebox

# Globals
frmFoot = None  # para acceder desde callback.


# STRINGS
txt = {
    0: "- Right click to auto-fill.\n- Left click to edit.\n- <Return> after edit updates auto-fill"
}


# CONSTANTS
SAMPLE_DATA = [ \
        ['-', '-X1', '1', '2-B4', 'E0.1', 'STANDARD', 'W2', '3'], \
        ['-', '-X1', 'GND', '2-B6', 'GND', 'GROUND', 'W2', 'GND'], \
        ['-', '-X1', '+2', '1-A2', '+2', 'STANDARD', 'W2', '1'], \
        ['-', '-X1', '-0', '1-A3', '-0', 'STANDARD', 'W2', '2'], \
        ['-', '-X1', 'GND', '2-B5', 'T', 'STANDARD', 'W1', 'GND'], \
        ['-', '-X1', 'R', '2-B5', 'R', 'STANDARD', 'W1', 'Black'], \
        ['-', '-X1', 'S', '2-B5', 'S', 'STANDARD', 'W1', 'Brown'], \
        ['-', '-X1', 'T', '2-B5', 'T', 'STANDARD', 'W1', 'Gray'], \
        ['-', '-X1', '+1', '1-A1', '+1', 'FUSE', '', ''], \
    ]

# GENERAL CONFIG
#font_grid_caption = Font(family="Courier", size=11, weight='bold')



def createGUI(root):
    """Create the main window
    @param root: main window"""
    # define main window

            
def right_on_filed(wdg_clicked, wdg_autofill):
    """establecemos el texto del campo auto-fill"""
    val = wdg_autofill['text']
   
    wdg_clicked.delete(0, "end")
    wdg_clicked.insert(0, val)
    if val.isdigit():
        wdg_autofill['text'] = str( int(wdg_autofill['text']) + 1)


def return_on_filed(wdg_clicked, wdg_autofill):
    """actualizamos auto-fill tras edicion"""
    val = wdg_clicked.get()
    if val.isdigit():
        wdg_autofill['text'] = str( int(val) + 1)
    else:
        wdg_autofill['text'] = str(val)


def right_on_pos(event):
    right_on_filed ( event.widget, frmFoot.winfo_children()[0] )


def right_on_type(event):
    right_on_filed ( event.widget, frmFoot.winfo_children()[5] )


def right_on_cable(event):
    right_on_filed ( event.widget, frmFoot.winfo_children()[6] )


def right_on_cond(event):
    right_on_filed ( event.widget, frmFoot.winfo_children()[7] )

            
def return_on_pos(event):
    return_on_filed( event.widget, frmFoot.winfo_children()[0])


def return_on_type(event):
    return_on_filed( event.widget, frmFoot.winfo_children()[5])


def return_on_cable(event):
    return_on_filed( event.widget, frmFoot.winfo_children()[6])


def return_on_cond(event):
    return_on_filed( event.widget, frmFoot.winfo_children()[7])


def click_on_save(event):
    messagebox.showinfo("QET", \
    "This will save the table to the QET project !!")


def click_on_draw(event):
    messagebox.showinfo("QET", \
            "This will generate the Terminal Blocks\n as new element!!")


def click_on_reorder(event):
    messagebox.showinfo("QET", \
            "This will redraw the table according the POS. column values.")
    
    
def main():
    global frmFoot
    
    GRID_CONFIG = [
    {'TITLE':'POS.', 'WIDTH': 8, 'AUTOFILL': '1', \
        'right':right_on_pos,'return':return_on_pos}, \
    {'TITLE':'TERM.BLOCK', 'WIDTH': 13, 'AUTOFILL': '', \
        'right':'','return':''}, \
    {'TITLE':'ID', 'WIDTH': 8, 'AUTOFILL': '', \
        'right':'','return':''}, \
    {'TITLE':'XREF', 'WIDTH': 8, 'AUTOFILL': '', \
        'right':'','return':''}, \
    {'TITLE':'CONDUCTOR', 'WIDTH': 12, 'AUTOFILL': '', \
        'right':'','return':''}, \
    {'TITLE':'TYPE', 'WIDTH': 10, 'AUTOFILL': 'GROUND', \
        'right':right_on_type,'return':return_on_type}, \
    {'TITLE':'CABLE', 'WIDTH': 10, 'AUTOFILL': '-W1', \
        'right':right_on_cable,'return':return_on_cable}, \
    {'TITLE':'CABLE COND.', 'WIDTH': 13, 'AUTOFILL': '1', \
        'right':right_on_cond,'return':return_on_cond} \
]
    
    # root window
    root = tk.Tk(  )
    root.title("QET - Terminal block generator")
    root.resizable(True, True)  # width, height
    #root.config(bg="green")
    #img = tk.PhotoImage(file='qet.png')
    #root.tk.call('wm', 'iconphoto', root._w, img)
    #~ root.iconbitmap("qet.ico")  # only b/n ico for linux

    ## frame header
    frmHeader = tk.Frame(root, borderwidth=1, relief='solid')
    frmHeader.pack(anchor='n', fill='x', expand='True')
    tk.Label(frmHeader, text=txt[0], justify='left').pack(side='left')
    
    b1 = tk.Button(frmHeader,text='SAVE')
    b1.pack(side='right')
    b1.bind("<Button-1>", click_on_save)
    
    b2 = tk.Button(frmHeader,text='DRAW')
    b2.pack(side='right')
    b2.bind("<Button-1>", click_on_draw)
    
    b3 = tk.Button(frmHeader,text='REORDER')
    b3.pack(side='right')
    b3.bind("<Button-1>", click_on_reorder)

    ## frame data
    frmData = tk.Frame(root)
    frmData.pack(fill='x', expand='True',pady=10)

    for c in range(len(GRID_CONFIG)):
        tk.Label(frmData, text=GRID_CONFIG[c]['TITLE'], \
                 width = GRID_CONFIG[c]['WIDTH'], \
                 font=('Helvetica', 10, 'bold underline')).grid(row=0, column=c)

    offset = 1
    for r in range(len(SAMPLE_DATA)):
        for c in range(len(GRID_CONFIG)):
            lbl = tk.Entry(frmData, borderwidth=0, \
                    width = GRID_CONFIG[c]['WIDTH']-1, \
                    justify = 'center', fg='blue')
            lbl.insert(0,SAMPLE_DATA[r][c])
            lbl.grid(row=r+offset,column=c)
            
            if GRID_CONFIG[c]['AUTOFILL'] == '':
                lbl.config(state='disabled', disabledforeground = 'black')
                
            if GRID_CONFIG[c]['right'] != '':
                lbl.bind("<Button-3>",GRID_CONFIG[c]['right'])
                lbl.bind("<Return>",GRID_CONFIG[c]['return'])


    ## frame foot
    frmFoot = tk.Frame(root, borderwidth=1, relief='solid')
    frmFoot.pack(anchor='s', fill='x', expand='True')
    for c in range(len(GRID_CONFIG)):
        t = GRID_CONFIG[c]['AUTOFILL']
        tk.Label(frmFoot, text=t, \
                 width = GRID_CONFIG[c]['WIDTH'], \
                 font=('Helvetica', 10, 'bold'), fg='gray').grid(row=0, column=c)


    ## main loop
    root.mainloop(  )

if __name__ == '__main__':
    main()
