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

def subManualWin(subRequestsArchiveFilename,defaultFont):

	#Pull all names and section titles for the poopulation of the drop-down boxes
	allnames=['']+HF.getAllNames()
	sections=HF.getAllSectionTitles()

	#Define the window's layout
	layout=[[sg.Text("Email?| Sec   | Date   | Replacee                        | Replacement")],
		[sg.Checkbox('',size=(3,1),key='-EMAILCHECK-'),sg.Combo(sections,size=(7,1),key="-SECTION-",readonly=True, enable_events=True),sg.Combo([""],size=(6,1),key='-DATE-',readonly=True, enable_events=True),sg.Combo([""],size=(30,1),key="-REPLACEE-", enable_events=True,readonly=True),sg.Combo(allnames,size=(30,1),key="-REPLACEMENT-", enable_events=True,readonly=True)],
		[sg.Text("Reason for manual change: "),sg.Input(key='-REASON-')],
		[sg.Button("Close"),sg.Button("Make Change")]]

	# Create the Window
	window = sg.Window('Manual Substitution', 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
	while event != sg.WIN_CLOSED and event != "Close":
		event, values = window.read()
		
		#If the 'section' box is interacted with and is not blank (i.e. an option was selected from the dropdown box)
		if event=="-SECTION-" and values['-SECTION-']!="":
			sec=values['-SECTION-']
			dates=HF.getDatesFromSection(sec)
			window["-DATE-"].update(values=dates)#update the dropdown box of dates with the appropriate values for this section
			window["-REPLACEE-"].update(values=[""])
			
		#If the 'date' box is interacted with and is not blank (i.e. an option was selected from the dropdown box)
		if event=="-DATE-" and values['-DATE-']!="":
			date=values["-DATE-"]
			names=list(HF.getAllNamesFromSection(sec,date))[0]
			window["-REPLACEE-"].update(values=names)#update the dropdown box of names with the appropriate values for this section/date combo
			
		#Button was pressed to process the manual change
		if event == "Make Change":
			sec=values['-SECTION-']
			date=values["-DATE-"]
			replacee=HF.nameToID(values["-REPLACEE-"])
			replacement=HF.nameToID(values["-REPLACEMENT-"])
			
			timeStamp=str(datetime.now())#Consider the submission time to be right now, when the button was pressed.
			request=[timeStamp,replacee,sec,date,replacement,values["-REASON-"],"APP","MANUALLY CHANGED BY COURSE ADMINS"]#create a request in the style of the Google form, for archiving purposes
				
			HF.reassign(date,sec,replacee,replacement)#Actually perform the replacement
				
			#Send the email confirmations out to the relevant parties
			#NOTE: This is BEFORE the writing step so that if there's an error in emails (such as failed to authenticate) the code aborts BEFORE writing chnages to the database.
			if values['-EMAILCHECK-']:
				HF.generateEmails([request])
				
			#write to the archive database
			with open(subRequestsArchiveFilename,'a', newline='') as f:
				writer = csv.writer(f)
				writer.writerows([request])
				
			#Reset the dropdowns to the original options
			window["-SECTION-"].update(values=sections)
			window["-DATE-"].update(values=[""])
			window["-REPLACEE-"].update(values=[""])
			window["-REPLACEMENT-"].update(values=allnames)
		
		
		
	window.close()
