package handlers

import (
	"github.com/bwmarrin/discordgo"
	"kleincordBot/services"
	"math"
	"strconv"
	"sync"
	"time"
)

func DeleteCommand(data discordgo.ApplicationCommandInteractionData, s *discordgo.Session, i *discordgo.InteractionCreate) {
	var messages []*discordgo.Message
	var Allmessages []*discordgo.Message
	var messagesToDelete []string
	var wg sync.WaitGroup
	var beforeID = ""

	OnlyWebhook, _ := strconv.ParseBool(data.Options[1].Value.(string))
	amount, _ := strconv.Atoi(data.Options[0].Value.(string))
	Webhooks, _ := s.ChannelWebhooks(i.ChannelID)
	modulo := amount % 100

	loops := math.Floor(float64(amount-modulo) / 100)

	err := s.InteractionRespond(
		i.Interaction,
		&discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "deleting messages",
			},
		},
	)
	if err != nil {
	}

	for x := 0; x < int(loops); x++ {
		messages, err = s.ChannelMessages(i.ChannelID, 100, beforeID, "", "")
		if err != nil {
			services.HandleError(err, s)
		}
		Allmessages = append(Allmessages, messages...)
		if len(messages) > 0 {
			beforeID = messages[len(messages)-1].ID
		}
	}
	if modulo > 0 {
		messages, err = s.ChannelMessages(i.ChannelID, modulo, beforeID, "", "")
		if err != nil {
			services.HandleError(err, s)
		}
		Allmessages = append(Allmessages, messages...)
		if len(messages) > 0 {
			beforeID = messages[len(messages)-1].ID
		}
	}

	for _, message := range Allmessages {
		wg.Add(1)
		if OnlyWebhook {
			for _, Webhook := range Webhooks {
				if message.Author.ID == Webhook.ID {
					if time.Now().After(message.Timestamp.Add((24 * time.Hour) * 14)) {
						s.ChannelMessageDelete(i.ChannelID, message.ID)
					} else {
						messagesToDelete = append(messagesToDelete, message.ID)
					}
				}
			}
		} else {
			if time.Now().After(message.Timestamp.Add((24 * time.Hour) * 14)) {
				s.ChannelMessageDelete(i.ChannelID, message.ID)
			} else {
				messagesToDelete = append(messagesToDelete, message.ID)
			}
		}
		wg.Done()
	}
	wg.Wait()

	modulo = len(messagesToDelete) % 100

	loops = math.Floor(float64(len(messagesToDelete)-modulo) / 100)

	for x := 0; x < int(loops); x++ {
		index := x * 100
		err = s.ChannelMessagesBulkDelete(i.ChannelID, messagesToDelete[index:index+100])
		if err != nil {
			services.HandleError(err, s)
		}
	}
	if modulo > 0 {
		index := int(loops) * 100
		err = s.ChannelMessagesBulkDelete(i.ChannelID, messagesToDelete[index:index+modulo])
		if err != nil {
			services.HandleError(err, s)
		}
	}

	_, err = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
		Content: strconv.Itoa(len(Allmessages)) + " Message deleted",
	})
	if err != nil {
		services.HandleError(err, s)
	}
}
