package discord

import (
	"bytes"
	"fmt"
	"strings"

	"git.canopymc.net/Etzelia/stonebot/assets"
	"git.canopymc.net/Etzelia/stonebot/database"

	"github.com/bwmarrin/discordgo"
	"go.jolheiser.com/beaver"
)

func New(token, prefix string, db *database.Database) (*discordgo.Session, error) {
	bot, err := discordgo.New("Bot " + token)
	if err != nil {
		return nil, err
	}
	bot.Identify.Intents = discordgo.IntentsAllWithoutPrivileged

	bot.AddHandler(CommandHandler(prefix, db))
	bot.AddHandler(MessageHandler(prefix, db))

	return bot, nil
}

func CommandHandler(prefix string, db *database.Database) func(session *discordgo.Session, message *discordgo.MessageCreate) {
	return func(session *discordgo.Session, message *discordgo.MessageCreate) {
		// Ignore non-prefix
		if !strings.HasPrefix(message.Content, prefix) {
			return
		}

		// Ignore bots
		if message.Author.Bot {
			return
		}

		args := strings.Fields(message.Content[1:])
		switch strings.ToLower(args[0]) {
		case "rocks", "stones":
			rocks, err := db.Rocks()
			if err != nil {
				beaver.Errorf("could not count rocks: %v", err)
				return
			}
			if _, err := session.ChannelMessageSend(message.ChannelID, fmt.Sprintf("%d ROCKS", rocks)); err != nil {
				beaver.Errorf("could not send message: %v", err)
				return
			}
		}
	}
}

func MessageHandler(prefix string, db *database.Database) func(session *discordgo.Session, message *discordgo.MessageCreate) {
	return func(session *discordgo.Session, message *discordgo.MessageCreate) {
		// Ignore prefix
		if strings.HasPrefix(message.Content, prefix) {
			return
		}

		// Ignore bots
		if message.Author.Bot {
			return
		}

		rocks := strings.Count(message.Content, "rock")
		rocks += strings.Count(message.Content, "stone")
		if err := db.Rock(rocks); err != nil {
			beaver.Errorf("could not add rocks: %v", err)
		}

		if rocks > 0 {
			if _, err := session.ChannelMessageSendComplex(message.ChannelID, &discordgo.MessageSend{
				Files: []*discordgo.File{
					{
						Name:        "rocks.gif",
						ContentType: "multipart/form-data",
						Reader:      bytes.NewReader(assets.RocksGif),
					},
				},
			}); err != nil {
				beaver.Errorf("could not send rocks gif: %v", err)
			}
		}
	}
}
