#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 7g
#  in conjunction with Tcl version 8.6
#    Jun 12, 2021 08:18:46 AM PDT  platform: Linux

import sys
import platform
import os

# Third party libraries
from tksheet import Sheet
import pandas as pd

import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
from tkinter import messagebox
from tkinter import filedialog

import tksheetGUI

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 _top44, _w44
    _top44 = root
    _w44 = tksheetGUI.Toplevel1(_top44)
    init(_top44, _w44)
    root.mainloop()

def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
    startup()
    init_custom()

def on_btnExit(*args):
    print("tksheet_support.on_btnExit")
    sys.stdout.flush()
    #destroy_window()
    top_level.destroy()


def on_btnLoad(*args):
    print("tksheetdemo1_support.on_btnLoadCSV")
    sys.stdout.flush()
    global headers, progpath
    filename = filedialog.askopenfilename(
        initialdir=progpath,
        title="Select file",
        filetypes=(("CSV files", "*.csv"), ("all files", "*.*")),
    )
    data = load_csv_file(filename)
    # print(headers)
    w.Custom1.headers(headers)
    # Now load data into sheet
    w.Custom1.set_sheet_data(data)
    # Get the number of rows and columns
    global totalrows, totalcols
    totalrows = w.Custom1.total_rows()
    totalcols = w.Custom1.total_columns()
    # Print the information to the terminal
    print(f"Total Rows: {totalrows}")
    print(f"Total Cols: {totalcols}")

def load_csv_file(filename):
    global headers
    # Load the local csv file into a pandas dataframe
    df = pd.read_csv(filename)
    headers = list(df.columns)
    # Convert it into a list
    dl = df.values.tolist()
    # Return it to the calling function
    return dl

def startup():
    global version
    pv = platform.python_version()
    print(f"Running under Python {pv}")
    # Set the path of the program
    global progpath
    progpath = os.getcwd()
    print(progpath)
    version = "0.0.1"
    print(f"Version: {version}")
    # ===================================================
    # Some default global values
    # ===================================================
    global defaultColumns, defaultRows, useBoldFont, defFont
    defaultColumns = 30
    defaultRows = 50
    useBoldFont = False
    defFont = "Arial"

def init_custom():
    w.Custom1.page_up_down_select_row = True
    w.Custom1.column_width = 120
    w.Custom1.startup_select = (0, 1, "rows")
    w.Custom1.theme = "dark blue"
    w.Custom1.insert_column(idx=0)
    w.Custom1.insert_columns(columns=5, idx=10, mod_column_positions=False)

    w.Custom1.enable_bindings(
        (
            "single_select",  # "single_select" or "toggle_select"
            # To support column/row select
            "column_select",
            "row_select",
            # To support column/row resize
            "column_width_resize",
            "double_click_column_resize",
            "row_width_resize",
            "column_height_resize",
            "arrowkeys",
            "row_height_resize",
            "double_click_row_resize",
            "right_click_popup_menu",
            "rc_select",
            "rc_insert_column",
            "rc_delete_column",
            "rc_insert_row",
            "rc_delete_row",
            "hide_columns",
            # The following 5 lines must be included for popup support
            "copy",
            "cut",
            "paste",
            "delete",
            "undo",
            "edit_cell",
        )
    )
    w.Custom1.bind("<3>", rc)
    w.Custom1.extra_bindings(
        [
            ("cell_select", on_cellSelect),
            ("column_select", on_columnSelect),
            ("row_select", on_rowSelect),
        ]
    )

def on_columnSelect(p1):
    print(f"on_columnSelect Triggered {p1}")
    print(p1)
    selcol = p1[1]
    colname = headers[p1[1]]
    disp = f"Column Selected - Col: {selcol}   ColName: {colname}"
    print(disp)

def on_rowSelect(p1):
    print(f"on_rowSelect Triggered {p1}")
    print(p1)
    selrow = p1[1]
    disp = f"Row Selected - {selrow}"
    print(disp)

def on_cellSelect(p1):
    global headers
    print(f"on_cellSelect triggered: {p1}")
    selrow = p1[1] + 1
    selcol = p1[2] + 1
    colname = headers[p1[2]]
    disp = f"Cell Selected - Row: {selrow}   Col: {selcol}   ColName: {colname}"
    print(disp)

def rc(event):
    print(event)

class sheet(Sheet):
    def __init__(self, parent, **kw):
        Sheet.__init__(
            self,
            parent,
            page_up_down_select_row=True,
            column_width=120,
            font=("Arial", 12, "bold"),
            theme="dark blue",
            height=500,  # height and width arguments are optional
            width=1200,  # For full startup arguments see DOCUMENTATION.md
        )

Custom = sheet

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




