import time

from nonebot import on_command, require
from nonebot.adapters import Message
from nonebot.matcher import Matcher
from nonebot.params import CommandArg
from nonebot.plugin import PluginMetadata
from nonebot.rule import to_me
from nonebot.log import logger
import json

require("nonebot_plugin_alconna")
from nonebot_plugin_alconna import UniMessage
from .data import *
from .data_utils import *
from .image_builder import *
from .text_utils import *

__plugin_meta__ = PluginMetadata(
    name="BF查询",
    description="战地3，4，1，5，2042，6",
    usage="",
    extra={

    },
)

query = on_command("bft", rule=to_me(), aliases={"bf3", "bf4", "bfv", "bf1", "bf2042", "bf6"}, block=True)
bind = on_command("bind", rule=to_me(), aliases={"绑定"}, block=True)

bf_dict = {
    "bf3": "战地3",
    "bf4": "战地4",
    "bf1": "战地1",
    "bfv": "战地5",
    "bf2042": "战地2042",
    "bf6": "战地6",
}


@query.handle()
async def handle_function(matcher: Matcher, msg: Message = CommandArg()):
    cmd = matcher.state["_prefix"]["command"][0]
    game = cmd
    content = msg.extract_plain_text()
    play_stat = ""
    if cmd == "bf3":
        play_stat = await get_data_bf3(content, "pc")
    elif cmd == "bf4":
        play_stat = await get_data_bf4(content, "pc")
    elif cmd == "bf1":
        play_stat = await get_data_bf1(content, "pc")
    elif cmd == "bfv":
        play_stat = await get_data_bfv(content, "pc")
    elif cmd == "bf2042":
        play_stat = await get_data_bfv(content, "pc")
    elif cmd == "bf6":
        flag, play_stat = await get_data_bf6(content, 0)
        if flag == 0:
            msg = '检测到多个同名用户\n' + '\n'.join(
                f'用户名:{info["name"]}-等级:{info["rank"]}-UID:{info["uid"]}' for info in play_stat)
            await UniMessage.text(msg).finish()
        elif flag == 2:
            msg = "未找到该玩家名"
            await UniMessage.text(msg).finish()
    else:
        await UniMessage.text("指令异常").finish()
    if "errors" in play_stat:
        logger.warning(play_stat['errors'][0])
        msg = play_stat['errors'][0]
    else:
        if cmd == "bf6":
            img = build_bf6_simple_card(play_stat)
        else:
            weapon, vehicle = await get_best_weapon_and_best_vehicle(play_stat)
            player = play_stat['userName']
            pid = play_stat['userId']
            kd = play_stat['killDeath']
            kpm = play_stat['killsPerMinute']
            spm = play_stat['scorePerMinute']
            acc = play_stat['accuracy']
            # 战地3 特化
            if cmd == 'bf3':
                head_shots = play_stat['headShots']
            else:
                head_shots = play_stat['headshots']

            rank = play_stat['rank']
            time_play = convert_to_hours(play_stat['timePlayed'])
            kills = int(play_stat['kills'])
            kill_assists = int(play_stat['killAssists'])
            revives = int(play_stat['revives'])
            wins = int(play_stat['wins'])
            loses = int(play_stat['loses'])
            best_weapon = weapon
            best_vehicle = vehicle
            best_class = play_stat['bestClass']
            longest_head_shot = play_stat['longestHeadShot']
            highest_ill_streak = play_stat['highestKillStreak']

            # await stats_calculator(play_stat)

            stat_data, level_designation = await stats_calculator(play_stat, cmd)
            destroyed = await get_vehicle_destroyed(play_stat["vehicles"])
            img = await build_stats_card(game, player, pid, kd, kpm, spm, acc, head_shots, rank, time_play, kills,
                                         kill_assists, revives, wins, loses, destroyed, best_weapon, best_vehicle,
                                         best_class,
                                         longest_head_shot, highest_ill_streak, stat_data, level_designation)
        await UniMessage.image(raw=img.getvalue()).finish()
    await UniMessage.text(f"\n玩家【{content}】的【{bf_dict[cmd]}】数据\n{msg}").send()


@bind.handle()
async def bind_user(matcher: Matcher, msg: Message = CommandArg()):
    matcher.state.get()
