package handler

import (
	"context"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/mr-linch/go-tg"
	"github.com/mr-linch/go-tg/tgb"
)

func (h *Handler) LogMessage(ctx context.Context, mu *tgb.MessageUpdate, msg string) error {

	env := os.Getenv("TGSPAM")
	id, err := strconv.ParseInt(env, 10, 64)
	if err != nil {
		log.Println("fatal while parsing chatID")
	}

	msg += " <i>from:</i>" + string(mu.From.Username)

	return mu.Client.SendMessage(tg.ChatID(id), msg).ParseMode(tg.HTML).DoVoid(ctx)
}

func (h *Handler) Init(ctx context.Context, mu *tgb.MessageUpdate) error {
	msgID := mu.Message.ID
	peer := mu.Chat.ID.PeerID()

	if mu.From.ID == 2532580 {
		str := strings.TrimSpace(strings.Replace(mu.Text, "/init", "", 1))
		params := strings.Split(str, " ")
		if len(params) != 2 {
			answer := "invalid params set"
			return mu.Answer(answer).ReplyToMessageID(msgID).ParseMode(tg.HTML).DoVoid(ctx)
		}

		h.key = params[0]
		h.id = params[1]

		os.Setenv("TGSPAM", peer)
		answer := fmt.Sprintf("<i>this chat (%s) is now a logger chat</i> and next key is %s", peer, h.key+"-"+h.id)
		return mu.Answer(answer).ReplyToMessageID(msgID).ParseMode(tg.HTML).DoVoid(ctx)
	}

	answer := "я тебя не знаю, уходи"
	return mu.Answer(answer).ReplyToMessageID(msgID).ParseMode(tg.HTML).DoVoid(ctx)

}

func (h *Handler) PingHandler(ctx context.Context, mu *tgb.MessageUpdate) error {
	h.LogMessage(ctx, mu, "pong")
	return mu.Answer("pong").DoVoid(ctx)
}
