#!/usr/bin/env python

import sys
import subprocess
import os
from Tkinter import *
from tkFileDialog import *

class MyCode(object):
	def __init__(self):
		root = Tk()
		root.title('Welcome to use VEP2!')
		screen_width = root.winfo_screenwidth()
		screen_height = root.winfo_screenheight() 
		#print screen_width,screen_height
		
		x = (screen_width/2) - (855/2) 
		y = (screen_height/2) - (1100/2)
		root.geometry('%dx%d+%d+%d' % (855, 810, x, y))

		#root.geometry("%dx%d%+d%+d" % (900, 750, 0, 0))
      
		self.species_name = StringVar()
		self.rpkm = StringVar()
		self.tsne = StringVar()
		self.color = StringVar()


######################## title ############################

		Label(root,width=10,text='VEP2',fg='blue',font=("Helvetica", 56)).place(x=258,y=30)
		Label(root,width=50,text='Visualzing Expression Platform',fg='blue',font=("Helvetica", 18)).place(x=169,y=121)
		Label(root,width=50,text='(Furtherspin included)',fg='blue',font=("Helvetica", 15)).place(x=221,y=149)

######################## load background ############################

#                image5 = PhotoImage(file="../figure/cloud.gif")
 #               panel_background= Label(root, image=image5)
  #              panel_background.place(x=546,y=1)

#########################load an entry####################      

                Label(root,text='Please select the species name',fg='green').place(x=319,y=179)
                self.species_name.set("Human")

                OptionMenu(root,self.species_name,
                "Human",
                "Mouse",
                "Rat",
                "Macaca"
                ).place(x = 375, y = 205)


                Label(root,text='Please upload your sequence matrix.',fg='green').place(x=301,y=255)
                self.e = Entry(root, width=18,textvariable=self.rpkm)
                self.e.place(x=325,y=285)

                B = Button(root,text='Upload',command=self.Onload)
                B.place(x=505,y=285)

                Label(root,text='Please upload your plot file.',fg='green').place(x=320,y=335)
                self.e1 = Entry(root, width=18,textvariable=self.tsne)
                self.e1.place(x=325,y=365)

                B = Button(root,text='Upload',command=self.Onload_1)
                B.place(x=505,y=365)

   
                Label(root,text='Please upload your plot color file.',fg='green').place(x=320,y=415)
                self.e2 = Entry(root, width=18,textvariable=self.color)
                self.e2.place(x=325,y=445)

                B = Button(root,text='Upload',command=self.Onload_2)
                B.place(x=505,y=445)
 
                Label(root,text='Please input the genes id (i.e. Rplp0, Actb, Cd55, Clec4f, Adgre1, Itgam )',fg='green').place(x=197,y=510)
                self.textfr_control(root, 240, 535)



#########################load run button##################

		button = Button(root,text='RUN',fg='red',command=self.Run)
		button.place(x=406,y=600)

	#########################upload image#####################     

                image2 = PhotoImage(file="../figure/ki.gif") ########### need change ############
                panel_2 = Label(root, image=image2)
                panel_2.image = image2
                panel_2.place(x=100,y=639)

                image3 = PhotoImage(file="../figure/az.gif")########### need change ############
                panel_3 = Label(root, image=image3)

                panel_3.image = image3
                panel_3.place(x=610,y=595)


######################load menu bar#######################      

		menubar = Menu(root)
		filemenu = Menu(menubar)      
		menubar.add_cascade(label='File', menu=filemenu)
		filemenu.add_command(label='New Project')
		filemenu.add_command(label='load...', command=self.Onload)
		filemenu.add_command(label='open...', command=self.open_as)
      
		helpmenu = Menu(menubar)
		menubar.add_cascade(label="Help", menu=helpmenu)
		helpmenu.add_command(label="About...", command=self.create_a_child_window_for_readme)
		filemenu.add_command(label='Exit', command=root.quit)      
		root.config(menu=menubar)

		root.mainloop()
      
####################################################################################################   
	
	def textfr_control (self, master, x_coordinate, y_coordinate):

                textfr = Frame(master)
                self.text_control = Text(textfr,height = 2,width = 50, borderwidth=2,relief = RIDGE)
                scroll = Scrollbar(textfr)


                self.text_control.configure(yscrollcommand = scroll.set)
                self.text_control.pack(side = LEFT)
                scroll.pack(side = RIGHT,fill = Y)

                textfr.place(x=x_coordinate, y=y_coordinate)
 
        def Onload(self):
		self.e.delete(0, END)
		fileName = askopenfilename(filetypes=[("Text files", "*.txt"), ("Fasta files", "*.fa"), ("Fasta files", "*.fa"), ("All Files","*.*")])
		self.e.insert(0, fileName)

        def Onload_1(self):

                self.e1.delete(0, END)

                fileName = askopenfilename(filetypes=[("Text files", "*.txt"), ("SNPs files", "*.vcf"), ("Fasta files", "*.fa"), ("All Files","*.*")])
                self.e1.insert(0, fileName)

        def Onload_2(self):

                self.e2.delete(0, END)

                fileName = askopenfilename(filetypes=[("Text files", "*.txt"), ("SNPs files", "*.vcf"), ("Fasta files", "*.fa"),("All Files","*.*")])
                self.e2.insert(0, fileName)



	def create_a_child_window_for_readme(self):

		# create the root window
		root_3 = Tk()
		text = Text(root_3)

		# modify the window
		root_3.title("READ ME")
		root_3.geometry("1000x1000")
      
		myTextWidget= Text(root_3) # set up a text widget as a root (window) child

		myFile= file("../README") # get a file handle
		myText=myFile.read() # read the file to variable
		myFile.close() # close file handle

		myTextWidget.insert(0.0,myText) # insert the file's text into the text widget
      
		myTextWidget.pack(expand=1, fill=BOTH) # show the widget

		root_3.mainloop()

	def create_a_child_window_for_result(self):

		root_2 = Tk()
		text = Text(root_2)

		root_2.title("WRONG GENE LIST")
		root_2.geometry("900x200")
      
		myTextWidget= Text(root_2) # set up a text widget as a root (window) child

		myFile=file("../result/wrong_genes.txt") # get a file handle ########### need change ############
		myText= myFile.read() # read the file to variable
		myFile.close() # close file handle

		myTextWidget.insert(0.0,myText) # insert the file's text into the text widget
      
		myTextWidget.pack(expand=1, fill=BOTH) # show the widget

		root_2.mainloop()
	
	def create_a_child_window(self,filename):
		root_local = Tk()
		text = Text(root_local)

		root_local.title(filename)
		root_local.geometry("900x900")
      
		myTextWidget= Text(root_local) # set up a text widget as a root (window) child

		myFile=file(filename) # get a file handle
		myText= myFile.read() # read the file to variable
		myFile.close() # close file handle

		myTextWidget.insert(0.0,myText) # insert the file's text into the text widget
      
		myTextWidget.pack(expand=1, fill=BOTH) # show the widget
		
		menubar_local = Menu(root_local)
	#	root_local.config(menu=menubar_local)
		
		filemenu_local = Menu(menubar_local)      
		menubar_local.add_cascade(label="File", menu=filemenu_local)		
		filemenu_local.add_command(label="Save...", command=self.file_save)
		filemenu_local.add_command(label="Exit...", command=root_local.quit)
        
		helpmenu_local = Menu(menubar_local)		
		menubar_local.add_cascade(label="Help", menu=helpmenu_local)
		helpmenu_local.add_command(label="About...", command=self.create_a_child_window_for_readme)
	
		root_local.config(menu=menubar_local)
		
		root_local.mainloop()

	
	def Run(self):
		print
       		print "######################################################################################"
		print "                           Welcome to using VRP!				             "
		print "######################################################################################"
		print 

                os.system("rm ../source/* >> ../source/log.txt 2>&1") ########### need change ############
                os.system("rm ../result/* >> ../source/log.txt 2>&1") ########### need change ############

		print self.species_name.get()	
		self.genes_group = re.sub("\s+","",self.text_control.get('1.0','end-1c'))
	
                out = open("../source/marker_genes_pre.txt",'w') ########### need change ############

                print >> out, self.genes_group

                out.close()


		os.system("python pipeline.py %s %s %s %s" %(self.species_name.get(), self.rpkm.get(), self.tsne.get(), self.color.get())) ########### need change ############
                try:
                        self.create_a_child_window_for_result()

                except IOError as e:
                        print 'Everything is all right!'


   	def open_as(self):
		fileName_2 = askopenfilename(filetypes=[("Text and Python files","*.fa *.txt *.py *.pyw"), 
		     ("HTML files","*.htm"), 
		     ("All files","*.*")])
		
		try:
		
			self.create_a_child_window(fileName_2)
		
		except IOError:
		
			from tkMessageBox import showwarning
			showwarning("Open", "Cannot open the file.")	
			raise Cancel
		 
	def file_save(self):

		fout = asksaveasfile(mode='w', defaultextension=".txt")
		text2save = str(self.text.get(1.0,END))
		fout.write(text2save)
		fout.close()

 
if __name__=='__main__':    

	myApp = MyCode()

