package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"ticket-pimp/bot/handler"
	discordbot "ticket-pimp/discord-bot"
	"ticket-pimp/internal/services"

	"github.com/bwmarrin/discordgo"
	"github.com/joho/godotenv"
	"github.com/mr-linch/go-tg"
	"github.com/mr-linch/go-tg/tgb"
)

func main() {
	log.Print("started")
	env("prod.env")

	if err := runDiscrodBot(); err != nil {
		log.Fatal("Discord bot cannot be runned;")
	}

	ctx := context.Background()

	ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, os.Kill, syscall.SIGTERM)
	defer cancel()

	if err := runBot(ctx); err != nil {
		fmt.Println(err)
		defer os.Exit(1)
	}
}

// env
// env function reads provided file and setup envirmental variables;
func env(envFilePath string) {
	err := godotenv.Load(envFilePath)
	if err != nil {
		log.Fatal("Error while loading env file")
	}
}

func runDiscrodBot() error {
	dbot, err := discordbot.NewDiscordBot(os.Getenv("DISCORD_TOKEN"))
	if err != nil {
		return err
	}

	dbot.AddHandler(
		func(s *discordgo.Session, m *discordgo.MessageCreate) {
			if strings.Contains(m.Content, "ping") {
				// if ch, err := s.State.Channel(m.ChannelID); err != nil || !ch.IsThread() {
				// 	thread, err := s.MessageThreadStartComplex(m.ChannelID, m.ID, &discordgo.ThreadStart{
				// 		Name:                "Pong game with " + m.Author.Username,
				// 		AutoArchiveDuration: 60,
				// 		Invitable:           false,
				// 		RateLimitPerUser:    10,
				// 	})
				// 	if err != nil {
				// 		panic(err)
				// 	}
				// 	_, _ = s.ChannelMessageSend(thread.ID, "pong")
				// 	m.ChannelID = thread.ID
				// } else {
				_, _ = s.ChannelMessageSendReply(m.ChannelID, "pong", m.Reference())
			}
			// }
		})

	err = dbot.Open()
	if err != nil {
		return err
	}

	defer dbot.Close()
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt)
	<-stop
	log.Println("Graceful shutdown")
	return nil
}

// runBot ...
// ..function creates new Telegram BOT instance
// ..throw env variables through bot's handlers
// ..setup tg bot router;
// and finally returns tgb.Poller
func runBot(ctx context.Context) error {

	client := tg.New(os.Getenv("TG_API"))

	gitService := services.NewGit(
		os.Getenv("GIT_BASE_URL"),
		os.Getenv("GIT_TOKEN"),
	)

	cloudService := services.NewCloud(
		os.Getenv("CLOUD_BASE_URL"),
		os.Getenv("CLOUD_USER"),
		os.Getenv("CLOUD_PASS"),
	)

	coda := services.NewCodaClient(
		os.Getenv("CODA_TOKEN1"),
	)

	h := handler.NewHandler(
		gitService,
		cloudService,
		coda,
	)

	router := tgb.NewRouter().
		Message(h.Init, tgb.Command("init")).
		Message(h.PingHandler, tgb.Command("ping")).
		Message(h.DevelopmentTaskHandler, tgb.TextHasPrefix("/new")).
		Message(h.NewRepoHandler, tgb.TextHasPrefix("/repo")).
		Message(h.NewFolderHandler, tgb.TextHasPrefix("/folder")).
		Message(h.FarmTaskHandler, tgb.TextHasPrefix("/task"))

	return tgb.NewPoller(
		router,
		client,
	).Run(ctx)
}
