import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

from mower import __rootdir__
from mower.utils import typealias as tp
from mower.utils.image import cropimg


def generate_image(text: str, font_size: int) -> tp.GrayImage:
    font = ImageFont.truetype(
        f"{__rootdir__}/fonts/SourceHanSansCN-Medium.otf", size=font_size
    )
    img = Image.new(mode="L", size=(300, 70), color=(0,))
    draw = ImageDraw.Draw(img)
    draw.text((20, 0), text, fill=(255,), font=font)
    img = np.array(img, dtype=np.uint8)
    contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    rect = [cv2.boundingRect(c) for c in contours]
    left = min(x for x, y, w, h in rect)
    right = max(x + w for x, y, w, h in rect)
    top = min(y for x, y, w, h in rect)
    bottom = max(y + h for x, y, w, h in rect)
    return cropimg(img, ((left - 2, top - 2), (right + 2, bottom + 2)))


translate = {
    "PIONEER": "先锋",
    "WARRIOR": "近卫",
    "TANK": "重装",
    "SNIPER": "狙击",
    "CASTER": "术士",
    "MEDIC": "医疗",
    "SUPPORT": "辅助",
    "SPECIAL": "特种",
    "pioneer": "先锋",
    "warrior": "近卫",
    "tank": "重装",
    "sniper": "狙击",
    "caster": "术士",
    "medic": "医疗",
    "support": "辅助",
    "special": "特种",
    "vanguard": "先锋",
    "guard": "近卫",
    "defender": "重装",
    "supporter": "辅助",
    "specialist": "特种",
    "术师": "术士",
}
