import PySimpleGUI as sg
import csv
import pandas as pd
import helperFunctions as HF
from datetime import datetime, timedelta

def subHisWin(subRequestsArchiveFilename,defaultFont):

	history = pd.read_csv(subRequestsArchiveFilename,dtype=str)

	layout=[[sg.Text("TA Search Box: Type a substring of the name of a TA",key="-LABEL-")],
	[sg.Input()],[sg.Button("Find History"),sg.Button("Weekly Kudos"),sg.Button("Hall of Fame"),sg.Button("Close Window")],
	[sg.Button("+APP"),sg.Button("-APP"),sg.Button("+ACC"),sg.Button("-ACC"),sg.Button("+REJ"),sg.Button("-REJ"),sg.Button("+CAN"),sg.Button("-CAN"),sg.Button("+FUL"),sg.Button("-FUL")]
	,[sg.Text("",key="OUTPUT",expand_x=True,expand_y=True,size=(200, 20))]]

	# Create the Window
	window = sg.Window('Substitution History', layout, font=defaultFont,resizable=True)

	#Event Loop to process "events" and get the "values" of the inputs
	#Cease running if they close the window
	event=-1
	netID=-1
	while event != sg.WIN_CLOSED and event != "Close Window":
		event, values = window.read()
		
		#If event is the pressing of an incrementing button AND the textbox search returns exactly one name
		if event in ["+APP","-APP","+ACC","-ACC","+REJ","-REJ","+CAN","-CAN","+FUL","-FUL"] and netID != -1 and len(netIDs)<=1:
			if event[0]=="+":
				change = 1
			elif event[0]=="-":
				change = -1
			else:
				print("ERROR: button names in sub history window do not match!")
			HF.incrementSubCount(netID,event[1:],change)
			event = "Find History"
			
		if event=="Find History":
			window["-LABEL-"].update(value='TA Search Box: Type a substring of the name of a TA')
			name = values[0]
			netIDs=HF.nameToID(name,getAllMatches=True)
			if not hasattr(netIDs,'__len__') or len(netIDs)==0:
				netID=-1
				if name=="":
					name="_BLANK_"
				window['OUTPUT'].update(value=name+" was not found in any names in the staff database.")
			else:
				netID=netIDs[0]
				name=HF.IDToName(netID)#convert ID back to full name
				extraNamesStr=""
				if len(netIDs)>1:
					names = [HF.IDToName(i) for i in netIDs[:]]
					window['OUTPUT'].update(value="Multiple matches found: ["+", ".join(names)+"]")
				else:
					#Re-enable the incrementing buttons once a single valid name is found
					window['+APP'].Update(disabled=False)
					window['-APP'].Update(disabled=False)
					window['+ACC'].Update(disabled=False)
					window['-ACC'].Update(disabled=False)
					window['+REJ'].Update(disabled=False)
					window['-REJ'].Update(disabled=False)
					window['+CAN'].Update(disabled=False)
					window['-CAN'].Update(disabled=False)
					window['+FUL'].Update(disabled=False)
					window['-FUL'].Update(disabled=False)
					#Get the number of previous requests in each category for that ULA
					APP,ACC,REJ,CAN,FUL=HF.getSubCount(netID)
									
					#Printing options for the Pandas dataframe
					pd.set_option('display.min_rows', 20)
					pd.set_option('display.expand_frame_repr', False)
					pd.set_option('max_colwidth', 30)
					
					output=history[history['Requestor']==netID].fillna("NONE")
					if output.empty:
						output="No history"
					else:
						output=str(output.to_string(index=False))
					#Change the textbox to include the relevant data
					window['OUTPUT'].update(value=name+"; "+netID+"\n"+"APP:"+APP+"  ACC:"+ACC+"  REJ:"+REJ+"  CAN:"+CAN+"  FUL:"+FUL+"\n"+output)
					
		if event=="Hall of Fame":
			#Disable the incrementing buttons while in "Hall of Fame" mode since there is no single name attached.
			window['+APP'].Update(disabled=True)
			window['-APP'].Update(disabled=True)
			window['+ACC'].Update(disabled=True)
			window['-ACC'].Update(disabled=True)
			window['+REJ'].Update(disabled=True)
			window['-REJ'].Update(disabled=True)
			window['+CAN'].Update(disabled=True)
			window['-CAN'].Update(disabled=True)
			window['+FUL'].Update(disabled=True)
			window['-FUL'].Update(disabled=True)
			
			#Printing options for Pandas
			pd.set_option('display.expand_frame_repr', False)
			pd.set_option('max_colwidth', 30)
			
			#Display instructions while the inputStr is not a valid input for the Hall of Fame
			window["-LABEL-"].update(value='Hall of Fame: To customize which categories to add (App,Acc,Rej,Can,Ful):\nuse 0,1,2,3,4 or any combination thereof in the text box then click "Hall of Fame" again\n(e.g. "12" yields Accepted plus Rejected)')
			output=''
			inputStr=values[0]
			if inputStr=="" or not inputStr.isnumeric():
				inputStr=""
			output+=HF.getTopSubs(inputStr,num=15)
			window['OUTPUT'].update(value=output)
			
		if event=="Weekly Kudos":
			#Disable the incrementing buttons while in "Weekly Kudos" mode since there is no single name attached.			
			window['+APP'].Update(disabled=True)
			window['-APP'].Update(disabled=True)
			window['+ACC'].Update(disabled=True)
			window['-ACC'].Update(disabled=True)
			window['+REJ'].Update(disabled=True)
			window['-REJ'].Update(disabled=True)
			window['+CAN'].Update(disabled=True)
			window['-CAN'].Update(disabled=True)
			window['+FUL'].Update(disabled=True)
			window['-FUL'].Update(disabled=True)
			
			inputStr=values[0]
			try:
				numDays=int(inputStr)
			except:
				numDays=7	#default to 7 days if the input isn't valid
			timeStr=datetime.now()
			currDate=timeStr-timedelta(hours=4,minutes=0)
			pastDate=timeStr-timedelta(hours=4+24*numDays,minutes=0)
			currDate=currDate.strftime('%m')+"/"+currDate.strftime('%d')
			pastDate=pastDate.strftime('%m')+"/"+pastDate.strftime('%d')
			window["-LABEL-"].update(value='Kudos: Displaying most fulfilled sub requests between '+pastDate+' and '+currDate+"\nType a number to see that many days' worth (default is 7)")
			
			
			output=f'Name            : Hours subbed\n'
			output+='------------------------------\n'
			kudosList=HF.getNumFulfilledInDateRange(subRequestsArchiveFilename,pastDate,currDate)
			kudosList=sorted(kudosList.items(), key=lambda x:x[1], reverse=True)
			for person in kudosList:
				output+=f'{HF.IDToName(person[0])[:15]:15} : {person[1]*2.0}\n'
			window['OUTPUT'].update(value=output)
				
		
	window.close()