#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.25.1
#  in conjunction with Tcl version 8.6
#    Sep 29, 2019 04:54:59 PM CST  platform: Windows NT

import sys

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

import savetvseries_support
import tkinter.messagebox
from datetime import datetime
import sqlite3
import os

print(os.getcwd())
input()

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root, top
    root = tk.Tk()
    top = Toplevel1(root)
    savetvseries_support.init(root, top)
    populatedict()
    root.mainloop()

w = None
def create_Toplevel1(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = tk.Toplevel (root)
    top = Toplevel1 (w)
    savetvseries_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_Toplevel1():
    global w
    w.destroy()
    w = None

class Toplevel1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.',background=_bgcolor)
        self.style.configure('.',foreground=_fgcolor)
        self.style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])

        top.geometry("611x380+598+122")
        top.title("Save tv Series")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.Button1 = tk.Button(top)
        self.Button1.place(relx=1.555, rely=1.0, height=24, width=47)
        self.Button1.configure(activebackground="#ececec")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#d9d9d9")
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''Button''')

        self.deletebutton = tk.Button(top, command=delete)
        self.deletebutton.place(relx=0.769, rely=0.434, height=54, width=117)
        self.deletebutton.configure(activebackground="#ededed")
        self.deletebutton.configure(activeforeground="#000000")
        self.deletebutton.configure(background="#d9d9d9")
        self.deletebutton.configure(disabledforeground="#a3a3a3")
        self.deletebutton.configure(foreground="#000000")
        self.deletebutton.configure(highlightbackground="#d9d9d9")
        self.deletebutton.configure(highlightcolor="#000000")
        self.deletebutton.configure(pady="0")
        self.deletebutton.configure(text='''Delete''')

        self.Scrolledlistbox1 = ScrolledListBox(top)
        self.Scrolledlistbox1.place(relx=0.016, rely=0.026, relheight=0.934
                , relwidth=0.509)
        self.Scrolledlistbox1.configure(background="white")
        self.Scrolledlistbox1.configure(disabledforeground="#a3a3a3")
        self.Scrolledlistbox1.configure(font="TkFixedFont")
        self.Scrolledlistbox1.configure(foreground="black")
        self.Scrolledlistbox1.configure(highlightbackground="#d9d9d9")
        self.Scrolledlistbox1.configure(highlightcolor="#d9d9d9")
        self.Scrolledlistbox1.configure(selectbackground="#c4c4c4")
        self.Scrolledlistbox1.configure(selectforeground="black")

        self.viewbutton = tk.Button(top,command=view)
        self.viewbutton.place(relx=0.769, rely=0.053, height=54, width=117)
        self.viewbutton.configure(activebackground="#ececec")
        self.viewbutton.configure(activeforeground="#000000")
        self.viewbutton.configure(background="#d9d9d9")
        self.viewbutton.configure(disabledforeground="#a3a3a3")
        self.viewbutton.configure(foreground="#000000")
        self.viewbutton.configure(highlightbackground="#d9d9d9")
        self.viewbutton.configure(highlightcolor="black")
        self.viewbutton.configure(pady="0")
        self.viewbutton.configure(text='''View''')

        self.Label1 = tk.Label(top)
        self.Label1.place(relx=0.54, rely=0.039, height=31, width=85)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(font="-family {Segoe UI} -size 14 -weight bold")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''Ranking:''')

        self.Label2 = tk.Label(top)
        self.Label2.place(relx=0.532, rely=0.25, height=27, width=112)
        self.Label2.configure(activebackground="#f9f9f9")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(font="-family {Segoe UI} -size 12 -weight bold")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#d9d9d9")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text='''Last Watched:''')

        self.updatebutton = tk.Button(top,command=update)
        self.updatebutton.place(relx=0.769, rely=0.237, height=54, width=117)
        self.updatebutton.configure(activebackground="#ececec")
        self.updatebutton.configure(activeforeground="#000000")
        self.updatebutton.configure(background="#d9d9d9")
        self.updatebutton.configure(disabledforeground="#a3a3a3")
        self.updatebutton.configure(foreground="#000000")
        self.updatebutton.configure(highlightbackground="#d9d9d9")
        self.updatebutton.configure(highlightcolor="black")
        self.updatebutton.configure(pady="0")
        self.updatebutton.configure(text='''Update''')

        self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
        top.configure(menu = self.menubar)

        self.addbutton = tk.Button(top,command=add)
        self.addbutton.place(relx=0.769, rely=0.632, height=54, width=117)
        self.addbutton.configure(activebackground="#ededed")
        self.addbutton.configure(activeforeground="#000000")
        self.addbutton.configure(background="#d9d9d9")
        self.addbutton.configure(disabledforeground="#a3a3a3")
        self.addbutton.configure(foreground="#000000")
        self.addbutton.configure(highlightbackground="#d9d9d9")
        self.addbutton.configure(highlightcolor="#000000")
        self.addbutton.configure(pady="0")
        self.addbutton.configure(text='''Add''')

        self.Label1_2 = tk.Label(top)
        self.Label1_2.place(relx=0.532, rely=0.539, height=31, width=55)
        self.Label1_2.configure(activebackground="#f9f9f9")
        self.Label1_2.configure(activeforeground="black")
        self.Label1_2.configure(background="#d9d9d9")
        self.Label1_2.configure(disabledforeground="#a3a3a3")
        self.Label1_2.configure(font="-family {Segoe UI} -size 14 -weight bold")
        self.Label1_2.configure(foreground="#000000")
        self.Label1_2.configure(highlightbackground="#d9d9d9")
        self.Label1_2.configure(highlightcolor="black")
        self.Label1_2.configure(text='''Title:''')

        self.searchbutton = tk.Button(top,command=search)
        self.searchbutton.place(relx=0.769, rely=0.816, height=54, width=117)
        self.searchbutton.configure(activebackground="#ededed")
        self.searchbutton.configure(activeforeground="#000000")
        self.searchbutton.configure(background="#d9d9d9")
        self.searchbutton.configure(disabledforeground="#a3a3a3")
        self.searchbutton.configure(foreground="#000000")
        self.searchbutton.configure(highlightbackground="#d9d9d9")
        self.searchbutton.configure(highlightcolor="#000000")
        self.searchbutton.configure(pady="0")
        self.searchbutton.configure(text='''Search''')

        self.ranktext = tk.Text(top)
        self.ranktext.place(relx=0.54, rely=0.132, relheight=0.063
                , relwidth=0.203)
        self.ranktext.configure(background="white")
        self.ranktext.configure(font="TkTextFont")
        self.ranktext.configure(foreground="black")
        self.ranktext.configure(highlightbackground="#d9d9d9")
        self.ranktext.configure(highlightcolor="black")
        self.ranktext.configure(insertbackground="black")
        self.ranktext.configure(selectbackground="#c4c4c4")
        self.ranktext.configure(selectforeground="black")
        self.ranktext.configure(wrap="word")

        self.lastwatchtext = tk.Text(top)
        self.lastwatchtext.place(relx=0.54, rely=0.342, relheight=0.168
                , relwidth=0.203)
        self.lastwatchtext.configure(background="white")
        self.lastwatchtext.configure(font="TkTextFont")
        self.lastwatchtext.configure(foreground="black")
        self.lastwatchtext.configure(highlightbackground="#d9d9d9")
        self.lastwatchtext.configure(highlightcolor="black")
        self.lastwatchtext.configure(insertbackground="black")
        self.lastwatchtext.configure(selectbackground="#c4c4c4")
        self.lastwatchtext.configure(selectforeground="black")
        self.lastwatchtext.configure(wrap="word")

        self.titletext = tk.Text(top)
        self.titletext.place(relx=0.54, rely=0.632, relheight=0.116
                , relwidth=0.203)
        self.titletext.configure(background="white")
        self.titletext.configure(font="TkTextFont")
        self.titletext.configure(foreground="black")
        self.titletext.configure(highlightbackground="#d9d9d9")
        self.titletext.configure(highlightcolor="black")
        self.titletext.configure(insertbackground="black")
        self.titletext.configure(selectbackground="#c4c4c4")
        self.titletext.configure(selectforeground="black")
        self.titletext.configure(wrap="word")

        self.Label1_3 = tk.Label(top)
        self.Label1_3.place(relx=0.532, rely=0.763, height=31, width=135)
        self.Label1_3.configure(activebackground="#f9f9f9")
        self.Label1_3.configure(activeforeground="black")
        self.Label1_3.configure(background="#d9d9d9")
        self.Label1_3.configure(disabledforeground="#a3a3a3")
        self.Label1_3.configure(font="-family {Segoe UI} -size 14 -weight bold")
        self.Label1_3.configure(foreground="#000000")
        self.Label1_3.configure(highlightbackground="#d9d9d9")
        self.Label1_3.configure(highlightcolor="black")
        self.Label1_3.configure(text='''Last updated:''')

        self.lastupdatetext = tk.Text(top)
        self.lastupdatetext.place(relx=0.54, rely=0.855, relheight=0.116
                , relwidth=0.203)
        self.lastupdatetext.configure(background="white")
        self.lastupdatetext.configure(font="TkTextFont")
        self.lastupdatetext.configure(foreground="black")
        self.lastupdatetext.configure(highlightbackground="#d9d9d9")
        self.lastupdatetext.configure(highlightcolor="black")
        self.lastupdatetext.configure(insertbackground="black")
        self.lastupdatetext.configure(selectbackground="#c4c4c4")
        self.lastupdatetext.configure(selectforeground="black")
        self.lastupdatetext.configure(wrap="word")



        for t in (self.ranktext, self.lastwatchtext, self.titletext, self.lastupdatetext):
            t.bind('<Tab>', lambda e, t=t: focusNext(t))
            t.bind('<Shift-Tab>', lambda e, t=t: focusPrev(t))
        self.ranktext.focus_set()
        
      
# The following code is added to facilitate the Scrolled widgets you specified.
class AutoScroll(object):
    '''Configure the scrollbars for a widget.'''

    def __init__(self, master):
        #  Rozen. Added the try-except clauses so that this class
        #  could be used for scrolled entry widget for which vertical
        #  scrolling is not supported. 5/7/14.
        try:
            vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
        except:
            pass
        hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)

        #self.configure(yscrollcommand=_autoscroll(vsb),
        #    xscrollcommand=_autoscroll(hsb))
        try:
            self.configure(yscrollcommand=self._autoscroll(vsb))
        except:
            pass
        self.configure(xscrollcommand=self._autoscroll(hsb))

        self.grid(column=0, row=0, sticky='nsew')
        try:
            vsb.grid(column=1, row=0, sticky='ns')
        except:
            pass
        hsb.grid(column=0, row=1, sticky='ew')

        master.grid_columnconfigure(0, weight=1)
        master.grid_rowconfigure(0, weight=1)

        # Copy geometry methods of master  (taken from ScrolledText.py)
        if py3:
            methods = tk.Pack.__dict__.keys() | tk.Grid.__dict__.keys() \
                  | tk.Place.__dict__.keys()
        else:
            methods = tk.Pack.__dict__.keys() + tk.Grid.__dict__.keys() \
                  + tk.Place.__dict__.keys()

        for meth in methods:
            if meth[0] != '_' and meth not in ('config', 'configure'):
                setattr(self, meth, getattr(master, meth))

    @staticmethod
    def _autoscroll(sbar):
        '''Hide and show scrollbar as needed.'''
        def wrapped(first, last):
            first, last = float(first), float(last)
            if first <= 0 and last >= 1:
                sbar.grid_remove()
            else:
                sbar.grid()
            sbar.set(first, last)
        return wrapped

    def __str__(self):
        return str(self.master)

def _create_container(func):
    '''Creates a ttk Frame with a given master, and use this new frame to
    place the scrollbars and the widget.'''
    def wrapped(cls, master, **kw):
        container = ttk.Frame(master)
        container.bind('<Enter>', lambda e: _bound_to_mousewheel(e, container))
        container.bind('<Leave>', lambda e: _unbound_to_mousewheel(e, container))
        return func(cls, container, **kw)
    return wrapped

class ScrolledListBox(AutoScroll, tk.Listbox):
    '''A standard Tkinter Listbox widget with scrollbars that will
    automatically show/hide as needed.'''
    @_create_container
    def __init__(self, master, **kw):
        tk.Listbox.__init__(self, master, **kw)
        AutoScroll.__init__(self, master)
    def size_(self):
        sz = tk.Listbox.size(self)
        return sz

import platform
def _bound_to_mousewheel(event, widget):
    child = widget.winfo_children()[0]
    if platform.system() == 'Windows' or platform.system() == 'Darwin':
        child.bind_all('<MouseWheel>', lambda e: _on_mousewheel(e, child))
        child.bind_all('<Shift-MouseWheel>', lambda e: _on_shiftmouse(e, child))
    else:
        child.bind_all('<Button-4>', lambda e: _on_mousewheel(e, child))
        child.bind_all('<Button-5>', lambda e: _on_mousewheel(e, child))
        child.bind_all('<Shift-Button-4>', lambda e: _on_shiftmouse(e, child))
        child.bind_all('<Shift-Button-5>', lambda e: _on_shiftmouse(e, child))

def _unbound_to_mousewheel(event, widget):
    if platform.system() == 'Windows' or platform.system() == 'Darwin':
        widget.unbind_all('<MouseWheel>')
        widget.unbind_all('<Shift-MouseWheel>')
    else:
        widget.unbind_all('<Button-4>')
        widget.unbind_all('<Button-5>')
        widget.unbind_all('<Shift-Button-4>')
        widget.unbind_all('<Shift-Button-5>')

def _on_mousewheel(event, widget):
    if platform.system() == 'Windows':
        widget.yview_scroll(-1*int(event.delta/120),'units')
    elif platform.system() == 'Darwin':
        widget.yview_scroll(-1*int(event.delta),'units')
    else:
        if event.num == 4:
            widget.yview_scroll(-1, 'units')
        elif event.num == 5:
            widget.yview_scroll(1, 'units')

def _on_shiftmouse(event, widget):
    if platform.system() == 'Windows':
        widget.xview_scroll(-1*int(event.delta/120), 'units')
    elif platform.system() == 'Darwin':
        widget.xview_scroll(-1*int(event.delta), 'units')
    else:
        if event.num == 4:
            widget.xview_scroll(-1, 'units')
        elif event.num == 5:
            widget.xview_scroll(1, 'units')


def focusNext(widget):
    widget.tk_focusNext().focus_set()
    return 'break'

def focusPrev(widget):
    widget.tk_focusPrev().focus_set()
    return 'break'


#---------------------------------------------------------------------

dblocation = os.path.join(os.getcwd(), 'tvseriesapp.db')
      
def startdb():
    global conn,cur
    conn = sqlite3.connect(dblocation)
    cur = conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS tvseriesapp(title,lastwatch,rank,lastupdate)")

def clearlist():
    #empty the list box
    for i in range(len(menu)):
        top.Scrolledlistbox1.delete(0, tk.END)

def populateTvList(series):
    global tvList
    global menu
    menu = list()
    tvList = {}
    
    for item in series:
        #print(item)

        top.Scrolledlistbox1.insert(tk.END, item[0])
        tvList[item[0]] = {"LAST":item[1], "RANK":item[2], "DATE":item[3]}
        menu.append(item[0])

def populatedict():
    cur.execute("select * from tvseriesapp order by rank, title")
    series = cur.fetchall()
    populateTvList(series)
    

def view():
    selected = top.Scrolledlistbox1.curselection()
    text = menu[selected[0]]
    
    top.ranktext.delete(1.0, tk.END)
    top.ranktext.insert(tk.END, tvList[text]["RANK"])
    
    top.lastwatchtext.delete(1.0, tk.END)
    top.lastwatchtext.insert(tk.END, tvList[text]["LAST"])
    
    top.titletext.delete(1.0, tk.END)
    top.titletext.insert(tk.END, text)
    
    top.lastupdatetext.delete(1.0, tk.END)
    top.lastupdatetext.insert(tk.END, tvList[text]["DATE"])

        
def update():
    
    ranktext = top.ranktext.get("1.0",tk.END).replace('\n','')
    lastwatchtext = top.lastwatchtext.get("1.0",tk.END).replace('\n','')
    titletext=top.titletext.get("1.0",tk.END).replace('\n','')

    if titletext != "" and titletext in tvList.keys():
        if tkinter.messagebox.askokcancel('Update?', 'Update ' +titletext):
            selected = top.Scrolledlistbox1.curselection()
            cur.execute("update tvseriesapp set lastwatch=?,rank=?,lastupdate=? where title = ?",(lastwatchtext, ranktext,datetime.now().strftime('%Y-%m-%d %H:%M:%S'),titletext))
            conn.commit()
            clearlist()
            populatedict()
            
def delete():
    selected = top.Scrolledlistbox1.curselection()
    text = menu[selected[0]]
    if tkinter.messagebox.askokcancel('Confirm delete?', 'Confirm delete ' +text):

        for i in selected:
            top.Scrolledlistbox1.delete(i)
        cur.execute("delete from tvseriesapp where title = ?",(text,))
        conn.commit()
        tkinter.messagebox.showinfo('Success!',text+" deleted!")
        clearlist()
        populatedict()
        
def add():
    ranktext = top.ranktext.get("1.0",tk.END).replace('\n','')
    lastwatchtext = top.lastwatchtext.get("1.0",tk.END).replace('\n','')
    titletext=top.titletext.get("1.0",tk.END).replace('\n','')

    ranktext = ranktext.strip()
    lastwatchtext= lastwatchtext.strip()
    titletext = titletext.strip()
    
    if ranktext=="\n" or ranktext == "" or lastwatchtext == "\n" or lastwatchtext == "" or titletext == "\n" or titletext == "":
       tkinter.messagebox.showinfo('Required',"Title, last watched and ranking required!")
    elif titletext in tvList.keys():
        tkinter.messagebox.showinfo('Error',"Title in list")
        print('title in list')

    else:
        print(titletext)
        print(lastwatchtext)
        print(ranktext)
        print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        print()
        
        cur.execute("INSERT INTO tvseriesapp(title,lastwatch,rank,lastupdate) VALUES(?,?,?,?)", (titletext,lastwatchtext,ranktext,datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        conn.commit()
        #top.Scrolledlistbox1.insert(tk.END,titletext)
        clearlist()
        populatedict()
        
def search():
    textToFind = top.titletext.get("1.0",tk.END).replace('\n','')
    cur.execute("select * from tvseriesapp where title like ? order by rank, title", ("%"+textToFind+"%",))
    series = cur.fetchall()
    clearlist()
    populateTvList(series)

    
def main(): 
    #conn,cur = startdb()
    pass        




if __name__ == '__main__':
    startdb()
    vp_start_gui()
    conn.close()
    



