package org.jebot.config;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.BotCommand;
import com.pengrad.telegrambot.request.SetMyCommands;
import com.pengrad.telegrambot.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.jebot.handler.HandlerManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Configuration
public class BotConfig {

    private final AtomicReference<TelegramBot> botReference = new AtomicReference<>();

    @Value("${telegram.bot.token}")
    private String botToken;

    @Bean
    public TelegramBot telegramBot(@Qualifier("handlerManager") HandlerManager handlerManager) {
        TelegramBot telegramBot = new TelegramBot(botToken);
        botReference.set(telegramBot);
        BotCommand command = new BotCommand("/help", "获取帮助");
        BaseResponse execute = telegramBot.execute(new SetMyCommands(command));
        if (!execute.isOk()) {
            log.error("设置命令失败: {}", execute.description());
        } else {
            log.info("设置命令成功");
        }
        telegramBot.setUpdatesListener(updates -> {
            handlerManager.handle(telegramBot, updates);
            return UpdatesListener.CONFIRMED_UPDATES_ALL;
        }, e -> {
            if (!e.response().isOk()) {
                log.error(e.toString());
                telegramBot.removeGetUpdatesListener();
            }
        });
        return telegramBot;
    }

    /// 重载 Bot
    public void reloadBot(String newToken, HandlerManager handlerManager) {
        TelegramBot telegramBot = botReference.get();
        if (telegramBot != null) {
            telegramBot.shutdown();
            telegramBot.removeGetUpdatesListener();
            log.info("TelegramBot 已成功停止");
        }
        TelegramBot newBot = new TelegramBot(newToken);
        BotCommand command = new BotCommand("/help", "获取帮助");
        BaseResponse execute = telegramBot.execute(new SetMyCommands(command));
        if (!execute.isOk()) {
            log.error("设置命令失败: {}", execute.description());
        } else {
            log.info("设置命令成功");
        }
        botReference.set(newBot);
        newBot.setUpdatesListener(updates -> {
            handlerManager.handle(newBot, updates);
            return UpdatesListener.CONFIRMED_UPDATES_ALL;
        }, e -> {
            if (!e.response().isOk()) {
                log.error("监听器错误: {}", e.toString());
            }
        });
        log.info("TelegramBot 已成功重载");
    }

    public TelegramBot getCurrentBot() {
        return botReference.get();
    }

    @PreDestroy
    public void destroy() {
        TelegramBot telegramBot = botReference.get();
        if (telegramBot != null) {
            telegramBot.shutdown();
            log.info("TelegramBot 已成功停止");
        }
    }
}