import { VoiceState } from "discord.js";
import { v4 as uuid } from "uuid";
import { jellyfinHandler } from "../..";
import { UserUpsertResult } from "../jellyfin/handler";
import { logger } from "../logger";


export const name = 'voiceStateUpdate'

export async function execute(oldState: VoiceState, newState: VoiceState) {

	try {
		logger.info(JSON.stringify(newState, null, 2))
		//ignore events like mute/unmute
		if (newState.channel?.id === oldState.channel?.id) {
			logger.info("Not handling VoiceState event because channelid of old and new was the same (i.e. mute/unmute event)")
			return
		}

		const scheduledEvents = (await newState.guild.scheduledEvents.fetch())
			.filter((key) => key.description?.toLowerCase().includes("!wp") && key.isActive())
			.map((key) => key)

		const scheduledEventUsers = (await Promise.all(scheduledEvents.map(event => event.fetchSubscribers({ withMember: true }))))

		//Dont handle users, that are already subscribed to the event. We only want to handle unsubscribed users here
		let userFound = false;
		scheduledEventUsers.forEach(collection => {
			collection.each(key => {
				logger.info(JSON.stringify(key, null, 2))
				if (key.member.user.id === newState.member?.user.id)
					userFound = true;
			})
		})
		if (userFound) {
			logger.info(`Not handling VoiceState event because user was already subscribed and got an account from there. User: ${JSON.stringify(newState.member, null, 2)}`)
			return
		}


		if (scheduledEvents.find(event => event.channelId === newState.channelId)) {
			if (newState.member) {
				logger.info("YO! Da ist jemand dem Channel mit dem Event beigetreten, ich kümmer mich mal um nen Account!")
				const result = await jellyfinHandler.upsertUser(newState.member, "TEMPORARY", uuid())
				if (result === UserUpsertResult.created) {
					newState.member.createDM().then(channel => channel.send(`Hey! Du bist unserer Watchparty beigetreten, ich hab dir gerade die Zugangsdaten für den Mediaserver geschickt!`))
				} else {
					newState.member.createDM().then(channel => channel.send(`Hey! Du bist unserer Watchparty beigetreten aber du hast bereits einen Account. Falls du ein neues Passwort brauchst nutze /reset_passwort!`))
				}
			} else {
				logger.error("WTF? Expected Member?? When doing things")
			}
		} else {
			logger.info("VoiceState channelId was not the id of any channel with events")
		}
	} catch (error) {
		logger.error(error)
	}
}
