import { Collection, GuildScheduledEvent, GuildScheduledEventStatus, Message } from "discord.js";
import { v4 as uuid } from "uuid";
import { client } from "../..";
import { logger } from "../logger";
import { isInitialAnnouncement } from "../helper/messageIdentifiers";


export const name = 'guildScheduledEventUpdate'

export async function execute(oldEvent: GuildScheduledEvent, newEvent: GuildScheduledEvent) {
	const requestId = uuid()
	try {
		if (!newEvent.guild) {
			logger.error("Event has no guild, aborting.", { guildId: newEvent.guildId, requestId })
			return
		}
		const guildId = newEvent.guildId

		if (newEvent.description?.toLowerCase().includes("!wp") && newEvent.status === GuildScheduledEventStatus.Completed) {
			logger.info("A watchparty ended. Cleaning up announcements!", { guildId, requestId })
			const announcementChannel = client.getAnnouncementChannelForGuild(newEvent.guild.id)
			if (!announcementChannel) {
				logger.error("Could not find announcement channel. Aborting", { guildId: newEvent.guild.id, requestId })
				return
			}

			const events = await newEvent.guild.scheduledEvents.fetch()

			const wpAnnouncements = (await announcementChannel.messages.fetch()).filter(message => !isInitialAnnouncement(message))
			const announcementsWithoutEvent = filterAnnouncementsByPendingWPs(wpAnnouncements, events)
			logger.info(`Deleting ${announcementsWithoutEvent.length} announcements.`, { guildId, requestId })
			announcementsWithoutEvent.forEach(message => message.delete())
		}
	} catch (error) {
		logger.error(<string>error, { guildId: newEvent.guildId, requestId })
	}
}

function filterAnnouncementsByPendingWPs(messages: Collection<string, Message<true>>, events: Collection<string, GuildScheduledEvent<GuildScheduledEventStatus>>): Message<true>[] {
	const filteredMessages: Message<true>[] = []
	for (const message of messages.values()) {
		let foundEventForMessage = false
		for (const event of events.values()) {
			if (message.cleanContent.includes(event.id)) { //announcement always has eventid because of eventbox
				foundEventForMessage = true
			}
		}
		if (!foundEventForMessage) {
			filteredMessages.push(message)
		}
	}
	return filteredMessages
}
