package plugins

import (
	"fmt"
	"kurumibot/database/psql"
	"kurumibot/utils"
	"strconv"
	"strings"
	"time"

	"kurumibot/laniakea"
)

func RegisterWaifus(bot *laniakea.Bot) {
	waifus := laniakea.NewPlugin("Waifus")

	waifus.Command(myWaifu, "mywaifu", "моивайфу")
	waifus.Command(sellWaifu, "sellwaifu")
	waifus.Command(waifuList, "wlist", "waifulist", "влист", "вайфулист")
	waifus.Command(waifuInfo, "winfo", "waifuinfo", "винфо")
	waifus.Command(waifuSearch, "wsearch", "waifusearch", "впоиск")

	bot.AddPlugins(waifus.Build())
}

func myWaifu(ctx *laniakea.MsgContext, _ *laniakea.DatabaseContext) {
	user, err := psql.GetUser(ctx.FromID)
	if err != nil {
		ctx.Answer(err.Error())
		return
	}

	out := []string{
		fmt.Sprintf("%s, %s!", user.Greeting, user.Name),
		"Список твоих вайфу:",
	}

	waifus, err := psql.GetUserWaifus(user.ID)
	if err != nil {
		ctx.Error(err)
		return
	}
	for _, w := range waifus {
		s := fmt.Sprintf("*%s* из \"*%s*\" (%d☆, ID: %d)", w.Name, w.Fandom, w.Rarity, w.ID)
		out = append(out, s)
	}

	ctx.Answer(strings.Join(out, "\n"))
}

func sellWaifu(ctx *laniakea.MsgContext, _ *laniakea.DatabaseContext) {

}

func waifuList(ctx *laniakea.MsgContext, _ *laniakea.DatabaseContext) {
	waifus, err := psql.GetAllWaifus()
	if err != nil {
		ctx.Answer(err.Error())
		return
	}
	var out []string

	for _, w := range waifus {
		var owner string
		if w.Owner == nil {
			owner = "нет"
		} else {
			owner = w.Owner.Name
		}
		s := fmt.Sprintf("*%s* из \"*%s*\" (%d☆, ID: %d) Владелец: %v", w.Name, w.Fandom, w.Rarity, w.ID, owner)
		out = append(out, s)
	}

	ctx.Answer(strings.Join(out, "\n"))
}

func waifuInfo(ctx *laniakea.MsgContext, _ *laniakea.DatabaseContext) {
	rawArgs := strings.TrimSpace(ctx.Text)
	args := strings.Split(rawArgs, " ")
	if len(args) != 1 {
		ctx.Answer("Не указан ID вайфу!")
		return
	}

	waifuId, err := strconv.Atoi(args[0])
	if err != nil {
		ctx.Answer("Во время выполнения команды произошла ошибка!")
		return
	}

	waifu, err := psql.GetWaifuById(waifuId)
	if err != nil {
		ctx.Error(err)
		return
	}

	out := []string{
		fmt.Sprintf("*%s* из \"*%s*\"", waifu.Name, waifu.Fandom),
		fmt.Sprintf("Редкость: %d☆", waifu.Rarity),
		fmt.Sprintf("Бонус к деньгам: x%.2f", waifu.MoneyBonus.InexactFloat64()),
		fmt.Sprintf("Бонус к опыту: x%.2f", waifu.ExpBonus.InexactFloat64()),
		fmt.Sprintf("Рыночная стоимость: %s¥", utils.DecimalComma(&waifu.MarketPrice)),
	}
	if len(waifu.Image) > 0 {
		ctx.AnswerPhoto(waifu.Image, strings.Join(out, "\n"))
	} else {
		ctx.Answer(strings.Join(out, "\n"))
	}
}

func waifuSearch(ctx *laniakea.MsgContext, _ *laniakea.DatabaseContext) {
	user, err := psql.GetOrCreateUser(ctx.FromID, ctx.Msg.From.FirstName)
	if err != nil {
		ctx.Error(err)
		return
	}

	if time.Now().Before(user.WaifuSearchTime.Add(time.Hour * 4)) {
		ctx.Answer("Вайфу можно искать раз в 4 часа.")
		return
	}

	count, err := psql.GetFreeWaifusCount()
	if err != nil {
		ctx.Error(err)
		return
	}
	if count == 0 {
		ctx.Answer("Не осталось свободных вайфу... :(\nПопробуй позже или купи на рынке!")
		return
	}

	rand := utils.RandRange(0, 100)
	if 10 < rand && rand < 90 {
		ctx.Answer("Ты ничего не нашел!")
		return
	}

	var freeWaifus []*psql.Waifu
	rarity := 3
	if rand == 0 {
		rarity = 5
	} else if rand > 0 && rand < 7 {
		rarity = 4
	}

	fmt.Println(rarity)

	freeWaifus, err = psql.GetFreeWaifusWithRarity(rarity)
	if err != nil {
		ctx.Error(err)
		return
	}

	if len(freeWaifus) == 0 {
		ctx.Answer("Ты ничего не нашел!")
		return
	}

	foundWaifuIndex := utils.RandRange(0, len(freeWaifus))
	waifu := freeWaifus[foundWaifuIndex]
	out := []string{
		"Ты нашел новую вайфу!",
		fmt.Sprintf("*%s* из \"*%s*\"", waifu.Name, waifu.Fandom),
		fmt.Sprintf("Редкость: %d☆", waifu.Rarity),
		fmt.Sprintf("Бонус к деньгам: x%.2f", waifu.MoneyBonus.InexactFloat64()),
		fmt.Sprintf("Бонус к опыту: x%.2f", waifu.ExpBonus.InexactFloat64()),
		fmt.Sprintf("Рыночная стоимость: %s¥", utils.DecimalComma(&waifu.MarketPrice)),
	}
	if len(waifu.Image) > 0 {
		ctx.AnswerPhoto(waifu.Image, strings.Join(out, "\n"))
	} else {
		ctx.Answer(strings.Join(out, "\n"))
	}
}
