"""
nntpPyClient main window
Here is main window definition in Tkinter

author: Miroslav Slivka
"""

import sysconfig
import threading

from tkinter import *
from nntplib import *
from idlelib.IOBinding import encoding

class TGetGrps(threading.Thread):
    
    def __init__(self,container,lst):
        threading.Thread.__init__(self)
        self.container = container
        self.list = lst
        
    def run(self):
        for group, last, first, flag in self.list:
            self.container.insert(END,group)
            
class TGetMsgs(threading.Thread):
    def __init__(self,container,client,grp):
        threading.Thread.__init__(self)
        self.container = container
        self.client = client
        self.grp = grp
    
    def run(self):
        response, count, first, last, name = self.client.group(self.grp)
        self.container.tag_configure("blue",foreground="blue")
        for i in range(first,last):
            hResp, hInfo = self.client.head(i)
            bResp, bInfo = self.client.body(i)
            self.container.insert(END, "\n")
            for line in filter(lambda x: 'From' in str(x,encoding='utf-8') or 'Subject' in str(x,encoding='utf-8'),hInfo.lines):
                self.container.insert(END, line, "blue")
                self.container.insert(END, "\n")
            
            for line in bInfo.lines:
                self.container.insert(END, line)
                self.container.insert(END, "\n")

class Application:
    
    def __init__(self):
        self.root = Tk()
        
        self.USER = ""
        self.PWD = ""
        self.HOST = ""
        
        self.group = IntVar()
        
        self.user = StringVar()
        self.pwd = StringVar()
        self.host = StringVar()
        
        self.initComponents()
        self.root.title("nntp PyClient")
        
    def initComponents(self):
        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)
        
        newMenu = Menu(self.menu)
        newMenu.add_command(label="Account",command=self.editAccount)
        newMenu.add_command(label="NNTP host",command=self.editHost)
        
        self.menu.add_cascade(menu=newMenu,label="New")
        self.menu.add_command(label="Connect!",command=self.connectClient)   
        
        #self.testText = Text(self.root,width=30,height=5)
        #self.testText.pack()  
        grpFrame = Frame(self.root)
        scrollbar = Scrollbar(grpFrame,orient=VERTICAL)
        self.groups = Listbox(grpFrame,yscrollcommand=scrollbar.set,width=35,selectmode=SINGLE)
        scrollbar.config(command=self.groups.yview)
        self.groups.pack(side=LEFT,fill=BOTH)
        scrollbar.pack(side=LEFT,fill=Y)
        Button(grpFrame,text="Enter",command=self.groupSelected).pack(side=RIGHT)
        grpFrame.pack(side=LEFT,fill=Y)
        
        articlesFrame = Frame(self.root)
        scrollbar = Scrollbar(articlesFrame,orient=VERTICAL)
        self.articles = Text(articlesFrame,yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.articles.yview)
        scrollbar.pack(side=RIGHT,fill=Y)
        self.articles.pack(side=LEFT,fill=BOTH)
        articlesFrame.pack(side=RIGHT,fill=BOTH)
        
        
    
    """
    Edit account callback
    """   
    def eAccOk(self):
        self.USER = self.user.get()
        self.PWD = self.pwd.get()
        self.wEditAcc.destroy()
        
        
    """
    Edit account menu selected.
    """
    def editAccount(self):
        
        self.user.set(self.USER)
        self.pwd.set(self.PWD)
        
        self.wEditAcc = Toplevel(self.root)
        self.wEditAcc.title("Account details")
        Entry(self.wEditAcc,textvariable=self.user).grid(row=0,column=1)
        Label(self.wEditAcc,text="Username:").grid(row=0,column=0)
        Entry(self.wEditAcc,textvariable=self.pwd).grid(row=1,column=1)
        Label(self.wEditAcc,text="Password:").grid(row=1,column=0)
        Button(self.wEditAcc,text="OK",command=self.eAccOk).grid(row=2,column=0)
        Button(self.wEditAcc,text="Cancel",command=self.wEditAcc.destroy).grid(row=2,column=1)
        
        self.root.wait_window(self.wEditAcc)
        
    """
    Edit host callback
    """
    def eHostOk(self):
        self.HOST = self.host.get()
        self.wEditHost.destroy()
        
    """
    Edit host menu selected.
    """
    def editHost(self):
        
        self.host.set(self.HOST)
        
        self.wEditHost = Toplevel(self.root)
        Entry(self.wEditHost,textvariable=self.host).grid(row=0,column=1)
        Label(self.wEditHost,text="Host:").grid(row=0,column=0)
        Button(self.wEditHost,text="OK",command=self.eHostOk).grid(row=1,column=0)
        Button(self.wEditHost,text="Cancel",command=self.wEditHost.destroy).grid(row=1,column=1)
        
        self.root.wait_window(self.wEditHost)
    
    def getGroups(self):
        response, list = self.client.list()
        
        thread = TGetGrps(self.groups,list)
        thread.start()
        
    """
    Enter group callback
    """
    def groupSelected(self):
        
        self.articles.delete(1.0, END)
        
        name = self.groups.get(self.groups.curselection())
        thread = TGetMsgs(self.articles,self.client,name)
        thread.start()
            
            
    def connectClient(self):
        print(self.HOST)
        try:
            self.client = NNTP(self.HOST,user=self.USER,password=self.PWD)
            msg = self.client.getwelcome()
            #self.testText.insert(END, msg)
            
            self.getGroups()
        except:
            print("Some error")        
        
    def runApp(self):
        self.root.mainloop()
        

def main():
    app = Application()
    app.runApp()

if __name__ == '__main__':
    main()
