from operator import truediv
import discord, asyncio, os, datetime
from discord.ext import commands
from bakapi import BakapiUser
from time import sleep

from dblib.db import db

global group1_user
global group2_user

class Homework(commands.Cog):
	def __init__(self, client):
		self.client = client
	
	@commands.Cog.listener()
	async def on_ready(self):
		try:
			global group1_user
			group1_user = BakapiUser(url=os.getenv("SCHOOL_URL"), username=os.getenv("GROUP1_USER"), password=os.getenv("GROUP1_PASS"))
			global group2_user
			group2_user = BakapiUser(url=os.getenv("SCHOOL_URL"), username=os.getenv("GROUP2_USER"), password=os.getenv("GROUP2_PASS"))

		except:
			print("Error Logging in")
		print("Homework Cog Loaded!")
	

	@commands.command(aliases=['hw', 'du', 'dů', 'dú'])
	@commands.has_permissions(manage_messages=True)
	async def homework(self, ctx):
		monday = (datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday())).isoformat()
		sunday = (datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday()+6)).isoformat()

		homework_g1 = group1_user.query_api(f'{os.getenv("SCHOOL_URL")}api/3/homeworks?from={monday}&to={sunday}', method="GET")
		homework_g2 = group1_user.query_api(f'{os.getenv("SCHOOL_URL")}api/3/homeworks?from={monday}&to={sunday}', method="GET")
		homework_sources = [homework_g1, homework_g2]

		perm_tt_1 = group1_user.query_api(f'{os.getenv("SCHOOL_URL")}api/3/timetable/permanent', method="GET")
		perm_tt_2 = group2_user.query_api(f'{os.getenv("SCHOOL_URL")}api/3/timetable/permanent', method="GET")

		groups_g1 = []
		groups_g2 = []
		groups_langs = []

		try:
			lang_one = db.record(f"SELECT Lang1 FROM languages WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
			lang_two = db.record(f"SELECT Lang2 FROM languages WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
			lang_three = db.record(f"SELECT Lang3 FROM languages WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
		except TypeError:
			await ctx.send("**Setup has not been run yet! Please run the setup command!**", delete_after=5)
			return 404

		langs = [lang_one.lower(), lang_two.lower(), lang_three.lower()]

			
		for group in perm_tt_1.get('Groups'):
			lang_found = False
			if group not in groups_g1:
				for lang in langs:
					if lang in group.get('Abbrev').lower() or lang in group.get('Name').lower() and group not in groups_langs:
						groups_langs.append(group)
						lang_found = True
						break

				if lang_found == False and group not in groups_langs:
					groups_g1.append(group)
		
		for group in perm_tt_2.get('Groups'):
			lang_found = False
			if group not in groups_g2:
				for lang in langs:
					if lang in group.get('Abbrev').lower() or lang in group.get('Name').lower() and group not in groups_langs:
						groups_langs.append(group)
						lang_found = True
						break

				if lang_found == False and group not in groups_langs:
					groups_g2.append(group)
		

		#Creating a list of homeworks
		#['ID', 'Subject', 'StartDate', 'EndDate', 'Content', 'Closed', 'Class', 'Group', 'Hour']
		for source in homework_sources:
			for homework in source.get('Homeworks'):
				temp = []
				temp.append(homework.get('ID'))
				temp.append(homework.get('Subject'))
				temp.append(homework.get('DateStart'))
				temp.append(homework.get('DateEnd'))
				temp.append(homework.get('Content'))
				temp.append(homework.get('Closed'))
				temp.append(homework.get('Class'))
				temp.append(homework.get('Group'))
				temp.append(homework.get('Hour'))

				db.execute(f"INSERT or IGNORE INTO homework VALUES (?,?,?,?,?,?,?,?,?,?,?);", temp[0], temp[1].get('Name'), temp[2], temp[3], temp[4], temp[5], temp[6].get('Abbrev'), temp[7].get('Name'), temp[8], "0", "0",)
			db.commit()
		

		lastTwoWeeks = (datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday(), weeks=-1)).isoformat()
		db.execute("SELECT * FROM homework ORDER BY date(EndDate) asc;")
		table = db.fetchall()
		
		delete = []
		not_sent = []
		print("---TABLE---")
		for row in table:
			print(str(row[9]) + "|" + str(type(row[9])))
			if row[3] < lastTwoWeeks:
				print("Last Two Weeks detected")
				delete.append(row)

			elif row[9] == 0:
				print("notfound")
				not_sent.append(row)
		
		
		for row in delete:
			db.execute("DELETE FROM homework WHERE ID = (?)", row[0])
			db.commit()

		print(not_sent)

		for row in not_sent:
			print(f'{row[1]} | Group: {row[7]} in groups: {groups_langs} | {row[7] in groups_langs}')

			if row[7] in groups_g1 and row[7] not in groups_g2:
				group_channel_id = db.record(f"SELECT Group_One_Channel FROM homeworkManager WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
				sent_message = await self.client.get_guild(ctx.guild.id).get_channel(group_channel_id).send(content = row)
				db.execute(f"UPDATE homework SET MessageID = (?) WHERE ID = (?);", str(sent_message.id), str(row[0]))
				db.commit()
			elif row[7] in groups_g2 and row[7] not in groups_g1:
				group_channel_id = db.record(f"SELECT Group_Two_Channel FROM homeworkManager WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
				sent_message = await self.client.get_guild(ctx.guild.id).get_channel(group_channel_id).send(content = row)
				db.execute(f"UPDATE homework SET MessageID = (?) WHERE ID = (?);", str(sent_message.id), str(row[0]))
				db.commit()
			elif row[7] in groups_langs:
				group_channel_id = db.record(f"SELECT Language_Channel FROM homeworkManager WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
				sent_message = await self.client.get_guild(ctx.guild.id).get_channel(group_channel_id).send(content = row)
				db.execute(f"UPDATE homework SET MessageID = (?) WHERE ID = (?);", str(sent_message.id), str(row[0]))
				db.commit()
			else:
				group_one_channel_id = db.record(f"SELECT Group_One_Channel FROM homeworkManager WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
				group_two_channel_id = db.record(f"SELECT Group_Two_Channel FROM homeworkManager WHERE GuildID = (?);", str(ctx.message.guild.id))[0]
				sent_message = await self.client.get_guild(ctx.guild.id).get_channel(group_one_channel_id).send(content = row)
				sent_message_two = await self.client.get_guild(ctx.guild.id).get_channel(group_two_channel_id).send(content = row)
				db.execute(f"UPDATE homework SET MessageID = (?) WHERE ID = (?);", str(sent_message.id), str(row[0]))
				db.execute(f"UPDATE homework SET SecondMessageID = (?) WHERE ID = (?);", str(sent_message_two.id), str(row[0]))
				db.commit()
			
			sleep(1)


		print("DONEONONEONE")
	
		

def setup(client):
	client.add_cog(Homework(client))