#! /usr/bin/env python
#
# Generated by PAGE version 4.1
# In conjuction with Tcl version 8.6
#    Nov. 30, 2013 03:06:36 PM
import sys, os
#import PIL.Image as Image
#import PIL.ImageTk as ImageTk
import tkFileDialog
import wiringpi2
from pylab import *
import numpy
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import csv
from itertools import izip

try:
    from Tkinter import *

except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = 0

except ImportError:
    import tkinter.ttk as ttk
    py3 = 1


pin_base = 65
i2c_addr = 0x20
i2c_addr_2 = 0x21
wiringpi2.wiringPiSetup()
wiringpi2.mcp23017Setup(pin_base,i2c_addr)
wiringpi2.mcp23017Setup(pin_base+16,i2c_addr_2)


def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    root.title('Graphic Waterfall Project')
    root.geometry('900x610+358+26')
    w = New_Toplevel_1 (root)
    init()
    root.mainloop()

def init():
    pass

class New_Toplevel_1:
    def __init__(self, master=None):
        _bgcolor = '#FFFFFF' #'SystemButtonFace'  # X11 color: #ece9d8
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#FFFFFF'#'SystemButtonFace' # X11 color: #ece9d8
        _ana1color = '#FFFFFF' #'SystemButtonFace' # X11 color: #ece9d8 
        _ana2color = '#FFFFFF' #'SystemButtonFace' # X11 color: #ece9d8 
        self.style = ttk.Style()
        self.style.configure('.',background=_bgcolor)
        self.style.configure('.',foreground=_fgcolor)
        self.style.configure('.',font="TkDefaultFont")
        self.style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])
        master.configure(background="white",highlightcolor="black")

        #Logo image
        self.gwpro = PhotoImage(file="images/gwpro.gif") 
        self.logo = ttk.Label(master,image=self.gwpro)
        self.logo.place(y=0,height=135, width=500)

        self.gwproinfo = PhotoImage(file="images/gwproinfo.gif")
        self.info = ttk.Label(master, image=self.gwproinfo)
        self.info.place(x=576, y=80,height=46, width=324)

        #Frame1 includes Entry box for text input
        self.TFrame1 = ttk.Frame (master)
        self.TFrame1.place(relx=0.05,rely=0.23,relheight=0.2,relwidth=0.27)
        self.TFrame1.configure(relief=GROOVE)
        self.TFrame1.configure(borderwidth="2")
        self.TFrame1.configure(relief="groove")
        self.TFrame1.configure(width=225)

        self.txtinput = ttk.Entry (self.TFrame1)
        self.txtinput.place(relx=0.09,rely=0.38,relheight=0.17,relwidth=0.83)
        self.txtinput.configure(takefocus="")


        self.TLabel2 = ttk.Label (self.TFrame1)
        self.TLabel2.place(relx=0.04,rely=0.08,height=17,width=70)
        self.TLabel2.configure(background=_bgcolor)
        self.TLabel2.configure(foreground="#000000")
        self.TLabel2.configure(relief="flat")
        self.TLabel2.configure(text='''Text Input''')


        #Choose category for the input
        self.ctext = ttk.Label(self.TFrame1)
        self.ctext.place(x=10, y=80, height=25, width=60)
        self.ctext.configure(text='''Category:''')
        
        self.value = StringVar()
        self.cate1 = ttk.Combobox (self.TFrame1, textvariable=self.value)
        self.cate1.place(x=75,y=80,height=23,width=76)
        self.cate1['values'] = ['A','B','C']
        self.cate1.configure(takefocus="")

        #Add button(for text input)
        self.a1 = ttk.Button (self.TFrame1, command=self._addinput)
        self.a1.place(x=150,y=80,height=25,width=70)
        self.a1.configure(takefocus="")
        self.a1.configure(text='''Add''')


        #Frame2 includes Buttons for selecting pattern
        self.TFrame2 = ttk.Frame (master)
        self.TFrame2.place(relx=0.37,rely=0.23,relheight=0.25,relwidth=0.55)
        self.TFrame2.configure(relief=GROOVE)
        self.TFrame2.configure(borderwidth="2")
        self.TFrame2.configure(relief="groove")
        self.TFrame2.configure(width=465)

        self.TLabel1 = ttk.Label (self.TFrame2)
        self.TLabel1.place(relx=0.02,rely=0.07,height=17,width=50)
        self.TLabel1.configure(background=_bgcolor)
        self.TLabel1.configure(foreground="#000000")
        self.TLabel1.configure(relief="flat")
        self.TLabel1.configure(text='''Pattern''')


        #####Pre-made Patterns#####
        #Checkered
        self.img = PhotoImage(file="images/pat_checkered.gif")
        self.imgcheckered = self.img.subsample(10,10)
        self.Button1 = ttk.Button (self.TFrame2, command=self._patCheckered)
        self.Button1.place(relx=0.04,rely=0.2,height=63,width=66)
        self.Button1.configure(takefocus="")
        self.Button1.configure(text='''Checkered''')
        self.Button1.configure(image=self.imgcheckered)

        #Stripes
        self.img2 = PhotoImage(file="images/pat_stripe.gif")
        self.imgstripe = self.img2.subsample(9,7)
        self.Button2 = ttk.Button (self.TFrame2, command=self._patStripe)
        self.Button2.place(relx=0.2,rely=0.2,height=63,width=66)
        self.Button2.configure(takefocus="")
        self.Button2.configure(text='''Stripe''')
        self.Button2.configure(image=self.imgstripe)

        #Diagonal lines
        self.img3 = PhotoImage(file="images/pat_diagonal.gif")
        self.imgdiagonal = self.img3.subsample(9,7)
        self.Button3 = ttk.Button (self.TFrame2, command=self._patDiagonal)
        self.Button3.place(relx=0.36,rely=0.2,height=63,width=66)
        self.Button3.configure(takefocus="")
        self.Button3.configure(text='''Diagonal Lines''')
        self.Button3.configure(image=self.imgdiagonal)

        #Heart
        self.img4 = PhotoImage(file="images/pat_heart.gif")
        self.imgheart = self.img4.subsample(10, 10)
        self.Button4 = ttk.Button (self.TFrame2, command=self._patHeart)
        self.Button4.place(relx=0.52,rely=0.2,height=63,width=66)
        self.Button4.configure(takefocus="")
        self.Button4.configure(text='''Heart''')
        self.Button4.configure(image=self.imgheart)

        #Bubbles
        self.img5 = PhotoImage(file="images/pat_bubbles.gif")
        self.imgbubbles = self.img5.subsample(10,10)
        self.Button5 = ttk.Button (self.TFrame2, command=self._patBubbles)
        self.Button5.place(relx=0.68,rely=0.2,height=63,width=66)
        self.Button5.configure(takefocus="")
        self.Button5.configure(text='''Bubbles''')
        self.Button5.configure(image=self.imgbubbles)


        #Choose category for the input
        self.ctext1 = ttk.Label(self.TFrame2)
        self.ctext1.place(x=410, y=45, height=25, width=60)
        self.ctext1.configure(text='''Category:''')
        
        self.value = StringVar()
        self.cate2 = ttk.Combobox (self.TFrame2, textvariable=self.value)
        self.cate2.place(x=410,y=65,height=23,width=76)
        self.cate2['values'] = ['A','B','C']
        self.cate2.configure(takefocus="")


        #Browse
        self.browseb = ttk.Button(self.TFrame2, text="Browse...", command=self._openimg)
        self.browseb.place(x=80, y=110, width=70)
        
        self.browse = ttk.Entry(self.TFrame2)
        self.browse.place(x=155, y=110)

        self.a2 = ttk.Button(self.TFrame2, text="Add", command=self._addimg)
        self.a2.place(x=290, y=110, width=70)

        self.blabel = ttk.Label(self.TFrame2, text="Custom:")
        self.blabel.place(x=30, y=113)

        #####Listbox widgets#####
        #ListboxA
        self.listbox1 = ScrolledListBox(master)
        self.listbox1.place(x=40,y=350,relheight=0.23
                ,relwidth=0.27)
        self.listbox1.configure(disabledforeground="#b1afa2")
        self.listbox1.configure(font="TkFixedFont")
        self.listbox1.configure(foreground="black")


        #Delete selected item in the listbox
        self.rev1 = ttk.Button(master, text='''X''', command=self._remove1)
        self.rev1.place(x=290, y=470,height=20, width=20)
        
        #ListboxB
        self.listbox2 = ScrolledListBox(master)
        self.listbox2.place(x=325,y=350,relheight=0.23
                ,relwidth=0.27)
        self.listbox2.configure(disabledforeground="#b1afa2")
        self.listbox2.configure(font="TkFixedFont")
        self.listbox2.configure(foreground="black")


        #Delete selected item in the listbox
        self.rev2 = ttk.Button(master, text='''X''', command=self._remove2)
        self.rev2.place(x=575, y=470,height=20, width=20)
        
        #ListboxC
        self.listbox3 = ScrolledListBox(master)
        self.listbox3.place(x=610,y=350,relheight=0.23
                ,relwidth=0.27)
        self.listbox3.configure(background="white")
        self.listbox3.configure(disabledforeground="#b1afa2")
        self.listbox3.configure(font="TkFixedFont")
        self.listbox3.configure(foreground="black")


        #Delete selected item in the listbox
        self.rev3 = ttk.Button(master, text='''X''', command=self._remove3)
        self.rev3.place(x=860, y=470,height=20, width=20)


        #Radio Buttons
        self.v = IntVar()
        self.style.map('TRadiobutton',background=
            [('selected', _bgcolor), ('active',_ana2color)])
        self.chooseA = ttk.Radiobutton (master , text="A", variable=self.v, value=1)
        self.chooseA.place(x=130,y=510,relheight=0.03,relwidth=0.04)
        self.chooseA.configure(takefocus="")

        self.chooseB = ttk.Radiobutton (master, text="B", variable=self.v, value=2)
        self.chooseB.place(relx=0.47,y=510,relheight=0.03,relwidth=0.03)
        self.chooseB.configure(takefocus="")

        self.chooseC = ttk.Radiobutton (master, text="C", variable=self.v, value=3)
        self.chooseC.place(relx=0.80,y=510,relheight=0.03,relwidth=0.04)
        self.chooseC.configure(takefocus="")


        #Reset button
        self.reset = ttk.Button (master, command=self._reset)
        self.reset.place(relx=0.35,y=550,height=23,width=76)
        self.reset.configure(takefocus="")
        self.reset.configure(text='''Reset''')


        #Start/Stop button
        self.start = ttk.Button (master, command=self._startstop)
        self.start.place(relx=0.55,y=550,height=23,width=76)
        self.start.configure(takefocus="")
        self.start.configure(text='''Start''')

    def setGeometry(self):
        w, h = self.img.size
        self.parent.geometry(("%dx%d+300+300") %(w,h))

    #Add text input into the list
    def _addinput(self, event=None):
        if self.txtinput.get() != "":
            if self.cate1.current()==0:
                self.listbox1.insert(END, self.txtinput.get())
                self.txtinput.delete(0,END)
            elif self.cate1.current()==1:
                self.listbox2.insert(END, self.txtinput.get())
                self.txtinput.delete(0,END)
            elif self.cate1.current()==2:
                self.listbox3.insert(END, self.txtinput.get())
                self.txtinput.delete(0,END)
            else: pass

    #Add image path into the list
    def _addimg(self, event=None):
        if self.cate2.current()==0:
            self.listbox1.insert(END, self.browse.get())
            self.browse.delete(0,END)
            self.listbox1.itemconfig(END,fg="blue")
        elif self.cate2.current()==1:
            self.listbox2.insert(END, self.browse.get())
            self.browse.delete(0,END)
            self.listbox2.itemconfig(END,fg="blue")
        elif self.cate2.current()==2:
            self.listbox3.insert(END, self.browse.get())
            self.browse.delete(0,END)
            self.listbox3.itemconfig(END,fg="blue")
        else: pass

    def _patCheckered(self, event=None):

        if self.cate2.current()==0:
            self.listbox1.insert(END,"Checkered")
            self.listbox1.itemconfig(END,fg="blue")
        elif self.cate2.current()==1:
            self.listbox2.insert(END,"Checkered")
            self.listbox2.itemconfig(END,fg="blue")
        elif self.cate2.current()==2:
            self.listbox3.insert(END,"Checkered")
            self.listbox3.itemconfig(END,fg="blue")
        else: pass

    def _patStripe(self, event=None):

        if self.cate2.current()==0:
            self.listbox1.insert(END,"Stripe")
            self.listbox1.itemconfig(END,fg="blue")
        elif self.cate2.current()==1:
            self.listbox2.insert(END,"Stripe")
            self.listbox2.itemconfig(END,fg="blue")
        elif self.cate2.current()==2:
            self.listbox3.insert(END,"Stripe")
            self.listbox3.itemconfig(END,fg="blue")
        else: pass

    def _patDiagonal(self, event=None):

        if self.cate2.current()==0:
            self.listbox1.insert(END,"Diagonal")
            self.listbox1.itemconfig(END,fg="blue")
        elif self.cate2.current()==1:
            self.listbox2.insert(END,"Diagonal")
            self.listbox2.itemconfig(END,fg="blue")
        elif self.cate2.current()==2:
            self.listbox3.insert(END,"Diagonal")
            self.listbox3.itemconfig(END,fg="blue")
        else: pass
        
    def _patHeart(self, event=None):

        if self.cate2.current()==0:
            self.listbox1.insert(END,"Heart")
            self.listbox1.itemconfig(END,fg="blue")
        elif self.cate2.current()==1:
            self.listbox2.insert(END,"Heart")
            self.listbox2.itemconfig(END,fg="blue")
        elif self.cate2.current()==2:
            self.listbox3.insert(END,"Heart")
            self.listbox3.itemconfig(END,fg="blue")
        else: pass

    def _patBubbles(self, event=None):

        if self.cate2.current()==0:
            self.listbox1.insert(END,"Bubbles")
            self.listbox1.itemconfig(END,fg="blue")
        elif self.cate2.current()==1:
            self.listbox2.insert(END,"Bubbles")
            self.listbox2.itemconfig(END,fg="blue")
        elif self.cate2.current()==2:
            self.listbox3.insert(END,"Bubbles")
            self.listbox3.itemconfig(END,fg="blue")
        else: pass

    def _openimg(self): #open the file

        fname = tkFileDialog.askopenfilename()
        self.browse.insert(0,fname)

    #Remove all items in all listboxes
    def _reset(self, event=None):
        self.listbox1.delete(0,END)
        self.listbox2.delete(0,END)
        self.listbox3.delete(0,END)
        
    #Remove items in specified listbox
    def _remove1(self, event=None):
        try:
        # get selected line index
            index = self.listbox1.curselection()[0]
            self.listbox1.delete(index)
        except IndexError: pass

    def _remove2(self, event=None):
        try:
        # get selected line index
            index = self.listbox2.curselection()[0]
            self.listbox2.delete(index)
        except IndexError: pass

    def _remove3(self, event=None):
        try:
        # get selected line index
            index = self.listbox3.curselection()[0]
            self.listbox3.delete(index)
        except IndexError: pass

    #####Execute the inputs
    def _startstop(self, event=None):

        if self.start["text"]=="Start":
            selection = str(self.v.get())
        
            if selection=="1":
                for n in range(len(self.listbox1.get(0,END))):
                    if self.listbox1.itemcget(n,'fg')=="blue":
                        if self.listbox1.get(n)=='Checkered':
                            #Pass img path to function
                            path = 'images/chess.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox1.get(n)=='Stripe':
                            path = 'images/stripe.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox1.get(n)=='Diagonal':
                            path = 'images/diagonal_cmp.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox1.get(n)=='Heart':
                            path = 'images/heart_cmp.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox1.get(n)=='Bubbles':
                            path = 'images/bubbles.gif'
                            print path
                            self._genimage(path)
                        else: 
                            path = self.listbox1.get(n)
                            fname = os.path.split(path)[1]
                            print fname
                            self._genimage('gg/'+fname)
                    else:
                        item = self.listbox1.get(n)
                        self._gentext(item)
                        pass
                
            elif selection=="2":
                for n in range(len(self.listbox2.get(0,END))):
                    if self.listbox2.itemcget(n,'fg')=="blue":
                        if self.listbox2.get(n)=='Checkered':
                            #Pass img path to function
                            path = 'images/chess.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox2.get(n)=='Stripe':
                            path = 'images/stripe.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox2.get(n)=='Diagonal':
                            path = 'images/diagonal_cmp.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox2.get(n)=='Heart':
                            path = 'images/heart_cmp.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox2.get(n)=='Bubbles':
                            path = 'images/bubbles.gif'
                            print path
                            self._genimage(path)
                        else:
                            path = self.listbox1.get(n)
                            fname = os.path.split(path)[1]
                            print fname
                            self._genimage('gg/'+fname)
                    else:
                        item = self.listbox2.get(n)
                        self._gentext(item)
                        pass
                        
            elif selection=="3":
                for n in range(len(self.listbox3.get(0,END))):
                    if self.listbox3.itemcget(n,'fg')=="blue":
                        if self.listbox3.get(n)=='Checkered':
                            #Pass img path to function
                            path = 'images/chess.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox3.get(n)=='Stripe':
                            path = 'images/stripe.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox3.get(n)=='Diagonal':
                            path = 'images/diagonal_cmp.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox3.get(n)=='Heart':
                            path = 'images/heart_cmp.gif'
                            print path
                            self._genimage(path)
                        elif self.listbox3.get(n)=='Bubbles':
                            path = 'images/bubbles.gif'
                            print path
                            self._genimage(path)
                        else:
                            path = self.listbox1.get(n)
                            fname = os.path.split(path)[1]
                            print fname
                            self._genimage('gg/'+fname)
                    else:
                        item = self.listbox3.get(n)
                        self._gentext(item)
                        pass
                        
            else: pass

            self.start["text"]="Stop"
            
        elif self.start["text"]=="Stop":
            print "Stop" #Stop the process
            # reset all pins as outputs and turn off
            for pin in range(65,96):
                wiringpi2.pinMode(pin,1)
                wiringpi2.digitalWrite(pin,0)
            self.start["text"]="Start"
        else: pass

    def _gentext(*item):

        # reset all pins as outputs and turn off
        for pin in range(65,97):
            wiringpi2.pinMode(pin,1)
            wiringpi2.digitalWrite(pin,0)

        inputt = item[1]
        
        if ('-' in inputt) | (len(inputt) ==1) :
            texts = inputt.split('-')
        
            for i in range(0,len(inputt)):
                path='./TextfileWF/'+str.upper(inputt[i])
                print(str.upper(inputt[i]))
                x=file(path,'r+',255);
                a=x.readlines(255);
                flip_a= flipud(a);

                for i in range(0,len(a)):
                    pin=65;
                    for j in flip_a[i]:
                            if j!='\n':
                                    wiringpi2.digitalWrite(pin,(int(j)))		
                            pin+=1;
                    wiringpi2.delay(65)
                for pin in range(65,97):
                    wiringpi2.digitalWrite(pin,0)
                wiringpi2.delay(800)
        else:
            texts = inputt.strip()
            if len(texts)%2==0 :
                for i in range(0,len(texts)):
                    if i%2==0:
                        w1='./TextfileWF/'+texts[i]
                        w2='./TextfileWF/'+texts[i+1]
                        with open('./TextfileWF/output','w') as g, open(w1) as word1, open(w2) as word2:
                            lis=[x1.split() for x1 in word1]
                            lis2=[x2.split() for x2 in word2]
                            for x1,x2 in izip(lis,lis2):

                                for y in x1:
                                    for i in range(0,31):
                                        if i%2==0:
                                            g.write(y[i])
                                for n in x2:
                                    for i in range(0,31):
                                        if i%2==0:
                                            g.write(n[i])
                                g.write('\n')
                                

            else:
                texts=texts+'*'
                for i in range(0,len(texts)):
                    if i%2==0:
                        w1='./TextfileWF/'+texts[i]
                        w2='./TextfileWF/'+texts[i+1]
                        with open('./TextfileWF/output','w') as g, open(w1) as word1, open(w2) as word2:
                             lis=[x1.split() for x1 in word1]
                             lis2=[x2.split() for x2 in word2]
                             for x1,x2 in izip(lis,lis2):

                                for y in x1:
                                    for i in range(0,31):
                                        if i%2==0:
                                            g.write(y[i])

                                for n in x2:
                                    for i in range(0,31):
                                        if i%2==0:
                                            g.write(n[i])
                                g.write('\n')
                                


            for i in range(0,len(inputt)):
                path='./TextfileWF/output'
                x=file(path,'r+',255);
                a=x.readlines(255);
                flip_a= flipud(a);

                for i in range(0,len(a)):
                    pin=65;
                    for j in flip_a[i]:
                            if j!='\n':
                                    wiringpi2.digitalWrite(pin,(int(j)))		
                            pin+=1;
                    wiringpi2.delay(65)
                for pin in range(65,97):
                    wiringpi2.digitalWrite(pin,0)
                wiringpi2.delay(800)


########### gen test image
    
    def _genimage(*img):

        inputt= img[1]
            
        a=mpimg.imread(inputt)
        a=1*(a>0)
   #     for i in range(0,len(a)):
   #         pin=65
   #         for j in range(0,32):
   #             print ( pin ,'=',a[i,j,1])
   #             pin+=1

       # print len(a)
        for i in range(0,len(a)):
            pin=65
            for j in range(0,32):
                wiringpi2.digitalWrite(pin,int(a[i,j,1]))
                pin=pin+1
            wiringpi2.delay(65)

        for pin in range(65,97):
                wiringpi2.digitalWrite(pin,0)
        wiringpi2.delay(800)
        

# 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):
        vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
        hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)

        self.configure(yscrollcommand=self._autoscroll(vsb),
            xscrollcommand=self._autoscroll(hsb))
        self.grid(column=0, row=0, sticky='nsew')
        vsb.grid(column=1, row=0, sticky='ns')
        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  (took from ScrolledText.py)
        if py3:
            methods = Pack.__dict__.keys() | Grid.__dict__.keys() \
                  | Place.__dict__.keys()
        else:
            methods = Pack.__dict__.keys() + Grid.__dict__.keys() \
                  + 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)
        return func(cls, container, **kw)
    return wrapped

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

if __name__ == '__main__':
    vp_start_gui()


