package com.yutou.tools.utils;

import com.yutou.tools.ToolsApplication;
import kotlin.coroutines.CoroutineContext;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactoryJvm;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.Events;
import net.mamoe.mirai.event.ListeningStatus;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.MessageEvent;
import net.mamoe.mirai.message.MessageReceipt;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageUtils;
import net.mamoe.mirai.utils.BotConfiguration;
import org.jetbrains.annotations.NotNull;

import java.io.File;

public class QQBotManager {
    private static QQBotManager botManager = null;
    private Bot bot;
    private static final long qqGroup = 891655174L;
    private boolean isLogin = false;

    private QQBotManager() {
        Object isRun = ConfigTools.load(ConfigTools.CONFIG, "qq_bot");
        if (isRun != null && (boolean) isRun) {
            init();
            isLogin = true;
        }
    }

    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long qq = 2476945931L;
                String password = "zhang34864394";
                if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("dev")) {
                    qq = 3620756944L;
                    password = "UAs6YBYMyxJU";
                }

                bot = BotFactoryJvm.newBot(qq, password, new BotConfiguration() {
                    {
                        fileBasedDeviceInfo("qq_bot_devices_info.json");
                        if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("nas")) {
                            noBotLog();
                            noNetworkLog();
                        }
                    }
                });
                Events.registerEvents(bot, new MessageListener());

                bot.login();
                sendMessage("姬妻酱上线拉~");
                bot.join();

            }
        }).start();

    }

    public static QQBotManager getInstance() {
        if (botManager == null) {
            botManager = new QQBotManager();
        }
        return botManager;
    }

    public boolean isLogin() {
        return isLogin;
    }

    private String getNotLoginQQ() {
        return "没有登录QQ";
    }

    public String sendMessage(String text) {
        if (bot != null) {
            try {
                MessageReceipt<Contact> receipt = bot.getGroup(qqGroup).sendMessage(text);
                return receipt.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getNotLoginQQ();
    }

    public String sendMessage(File imageFile, String text) {
        if (bot != null) {
            Image image = bot.getGroup(qqGroup).uploadImage(imageFile);
            MessageChain chain = MessageUtils.newImage(image.getImageId()).plus(text);
            MessageReceipt<Contact> receipt = bot.getGroup(qqGroup).sendMessage(chain);
            return receipt.toString();
        }
        return getNotLoginQQ();
    }

    public static void main(String[] args) {
        getInstance();
    }

    private static class MessageListener extends SimpleListenerHost {
        @Override
        public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception) {
            super.handleException(context, exception);
            System.out.println("error: " + exception.getLocalizedMessage());
        }

        @EventHandler
        public ListeningStatus onGroupMessage(GroupMessageEvent event) {
            if (event.getGroup().getId() == qqGroup) {
                String msg = event.getMessage().contentToString();
                msg = msg.replace("！", "!").toLowerCase();
                switch (msg) {
                    case "!开机":
                        RedisTools.Consumer.system("openPC", null);
                        break;
                    case "!更新ip":
                        RedisTools.Consumer.system("updateIP", null);
                        break;
                    case "!ip":
                        RedisTools.Consumer.bot("getip");
                        break;
                    case "!version":
                        sendVersion();
                        break;
                    default:
                        if (msg.startsWith("!cmd")) {
                            RedisTools.Consumer.system("cmd", msg.replace("!cmd", ""));
                        }
                }
            }/*else{
                sendMessage("群："+event.getGroup().getId()+" 发来消息：\n"+event.getMessage().contentToString());
            }*/
            return ListeningStatus.LISTENING;
        }

        private void sendVersion() {
            String localVersion= ToolsApplication.version;
            String serverVersion=HttpTools.get("http://tools.yutou233.cn:8000/public/version.do?token=zIrsh9TUZP2lfRW753PannG49E7VJvor");
            String msg="本地版本："+localVersion+"\n"+"服务器版本："+serverVersion;
            QQBotManager.getInstance().sendMessage(msg);
            Tools.sendServer("服务版本查询",msg);
        }

        @EventHandler
        public void onMessage(@NotNull MessageEvent event) throws Exception {
            // sendMessage("个人："+event.getSender().getNick()+" 发来消息:"+event.getMessage().contentToString());
        }
    }
}
