#sectionCSVHelper.py
#By Drew Murray murraydr@msu.edu

#This script is to assist with the creation of sectionsDatabase.csv
#In theory that CSV can be created manually and might need manual adjustment, but this should make it less tedious
#This code is not made to be especially robust as it is only a tool to assist manual creation/checking and should only need to be used once per semester
#Additionally the goal is to replace the entire function of this code (to convert pasted text from the website) with more direct input to the databases using interfaces yet to be developed
#DO NOT LINK/IMPORT THIS CODE TO THE MAIN SCRIPTS

#We want the headers to be in this order:
#	Section,Date,Time,Location,Staff1,Staff2,Staff3,Staff4,Staff5,Staff6,Staff7,Staff8,Staff9
#	Section is either "{M/T/W/T/F/S} Helproom (first half)" or "Sec {#}" e.g. "Tu Helproom" or "Sec 14"
#	Date is MM/DD
#	Time is just for recordkeeping, it is not used by the code
#   Location is just for recordkeeping, it is not used by the code
#	StaffX is each person associated with that section, order matters only for recordkeeping, the code treats them all the same


import helperFunctions as HF

#-------------------------------------------------------------------------------
#Parameters
leapYear=False
fridayHelproom=False

#-------------------------------------------------------------------------------
#list of dates MM/DD (I filled this out manually based on /admins/once per semester/edit classdays, maybe there's an easier way but it took me only 2 min)
#this code assumes that the first class is always a MW class
with open("startOfSemesterInputs/classDates.txt") as f:	
	text="".join(f.readlines())
	rawDates=text.split('\n')
	if '' in rawDates:
		rawDates.remove('')
for i in range(len(rawDates)):
	rawDates[i]=rawDates[i].split(',')
dates=[rawDates[::2],rawDates[1::2]]
#print("Dates found for MW:\n",dates[0],"\nDates found for TuTh:\n",dates[1])
#-------------------------------------------------------------------------------
#Create a dictionary to relate days of the week to assigned helproom staff
helproomHour1Staff={}
helproomHour2Staff={}
with open("startOfSemesterInputs/helproomHour1Staff.txt") as f:
	for line in f:
		vals=line.strip('\n').split(',')
		helproomHour1Staff[vals[0]]=vals[1:]
with open("startOfSemesterInputs/helproomHour2Staff.txt") as f:
	for line in f:
		vals=line.strip('\n').split(',')
		helproomHour2Staff[vals[0]]=vals[1:]

#-------------------------------------------------------------------------------
#Some code to generate dates and assignments for the helproom sessions
#Assumes that the helproom begins on the first day of class which will be a monday, skips saturdays, and ends 1 day after the last class period (Fri)
#Treats Saturdays as the END of the week (although assigns them to the next week number), and no classes or helprooms on Saturdays
daysOfWeek=['M','T','W','R','F','0','S']
daysPerMonth=[31,28,31,30,31,30,31,31,30,31,30,31]
if leapYear:
	daysPerMonth[1]=29
month=int(dates[0][0][0].split('/')[0])
day=int(dates[0][0][0].split('/')[1])
endMonth=int(dates[1][-1][0].split('/')[0])
endDay=int(dates[1][-1][0].split('/')[1])
if month>=10:
	endMonth+=12	#wrap around
helprooms=[]
weekday=0	#start with Monday
week=int(dates[0][0][1])
mostRecentDateIdx=0

lastClassElapsed=False
while not lastClassElapsed or weekday!=5:	#end on the Friday after the last class
	if month>=endMonth and day>=endDay:
		lastClassElapsed=True
	while month>=int(rawDates[mostRecentDateIdx][0].split('/')[0]) and day>=int(rawDates[mostRecentDateIdx][0].split('/')[1]) and mostRecentDateIdx<len(rawDates)-2:
		mostRecentDateIdx+=1
		
	if weekday==5:#if Saturday, update week number
		week=int(rawDates[mostRecentDateIdx][1])
	else:
		if fridayHelproom or weekday != 4:
			helprooms.append([daysOfWeek[weekday],str(week),f"{month:02}/{day:02}"])
	if weekday==6:#if Sunday, we need to loop back to Monday
		weekday=0
	else:
		weekday+=1
	
	day+=1
	if day>daysPerMonth[month-1]:
		day=1
		month+=1



#-------------------------------------------------------------------------------
#list of section assignments (I pasted the text directly from the web sheet at /admins/once per semester/edit sections)

with open("startOfSemesterInputs/sections.txt") as rf:
	with open("sectionsDatabase.csv","w") as wf:
		headers = "Section,Week,Date,Time,Location,Staff0,Staff1,Staff2,Staff3,Staff4,Staff5,Staff6,Staff7,Staff8,Staff9,Hours0,Hours1,Hours2,Hours3,Hours4,Hours5,Hours6,Hours7,Hours8,Hours9"
		wf.write(str(headers))
		
		for helproom in helprooms:
			wf.write("\n"+helproom[0]+"_HR1,"+helproom[1]+","+helproom[2]+","+"07:00 PM-08:00 PM,Zoom,"+','.join(helproomHour1Staff[helproom[0]])+','*(20-len(helproomHour1Staff[helproom[0]])))	#new line BEFORE each line since we already printed the header and don't want one at the end of the file
			wf.write("\n"+helproom[0]+"_HR2,"+helproom[1]+","+helproom[2]+","+"08:00 PM-09:00 PM,Zoom,"+','.join(helproomHour2Staff[helproom[0]])+','*(20-len(helproomHour2Staff[helproom[0]])))	#new line BEFORE each line since we already printed the header and don't want one at the end of the file
			
			
		#this block processes data from the Fall23 spreadsheet on onedrive ("Fall 2023 Staffing and Section Enrollment.xlsx" / "Section Enrollment" tab)
		#'''
		rf.readline()#skip first line
		for line in rf:
			vals=line.split('\t')[:-1]
			if "closed" in vals[1]:
				continue
			templateLineFront='\n'+'Sec '+vals[0]+','	#new line BEFORE each line since we already printed the header and don't want one at the end of the file
			if 'MW' in vals[4]:
				dateArrayIdx=0
			else:
				dateArrayIdx=1
				
			netIDs=[]
			for name in vals[10:]:
				netIDs.append(HF.nameToID(name.strip(' ')))
			if len(vals)>3:	#at least 1 staff assigned			
				templateLineBack=','+vals[5]+','+vals[6].strip(' ')+','+','.join(netIDs)+','*(20-len(netIDs))
				
				
				
				for dateIdx in range(len(dates[dateArrayIdx])):#for each date that that section meets
					wf.write(templateLineFront+str(dates[dateArrayIdx][dateIdx][1])+','+str(dates[dateArrayIdx][dateIdx][0])+templateLineBack)
		#'''
		#this block processes data from the website
		'''
		i=0
		for line in rf:	#For each section
		
			if "Grader 2" in line or "Grader 3" in line:
				continue
				
			else:
				line=line[:line.find("Grader")]
				vals=line.split('\t')
				while '' in vals: vals.remove('')	#remove empty string if present
				while 'None' in vals: vals.remove('None')	#remove empty string if present
				vals.remove('QL')
				templateLineFront='\n'+vals[0]+','	#new line BEFORE each line since we already printed the header and don't want one at the end of the file
				if 'MW' in vals[2]:
					dateArrayIdx=0
				else:
					dateArrayIdx=1
					
				netIDs=[]
				for name in vals[3:]:
					netIDs.append(HF.nameToID(name.strip(' ')))
				if len(vals)>3:	#at least 1 staff assigned
					templateLineBack=','+vals[2]+','+vals[1]+','+','.join(netIDs)+','*10
					
					for dateIdx in range(len(dates[dateArrayIdx])):#for each date that that section meets
						wf.write(templateLineFront+str(dates[dateArrayIdx][dateIdx][1])+','+str(dates[dateArrayIdx][dateIdx][0])+templateLineBack)
			i+=1
			'''
		
