#!/usr/bin/env python3
# # -*- coding: utf-8 -*-

import json
import re
import io
from db import *
from PIL import Image

with open("../../extraction/raw-31-2/data.cdb.json") as f:
    raw = json.load(f)
with open("../../clean/31-2/main.zh.mo.json") as f:
    trans = json.load(f)
with open("../../clean/31-2/main.en.mo.json") as f:
    trans_en = json.load(f)
img = Image.open("../../extraction/raw-31-2/cardIcons.png")

db.bind(provider="sqlite", filename="../../clean/31-2/data.sqlite3")
db.generate_mapping()

lines = raw["sheets"][1]["lines"]

with db_session:
    for i in lines:
        if i["group"] == 13:
            if not i["name"]:
                continue
            if i["id"] == "KingsHandBoss":
                continue
            raw_name = i["name"].strip()
            i["name"] = trans[raw_name]["msgstr"][0]
            i["name"] = re.sub(r"。", r"", i["name"])
            i["name_en"] = trans_en[raw_name]["msgstr"][0]
            i["name_en"] = re.sub(r"outfit", r"Outfit", i["name_en"])
            i["gameplayDesc"] = trans[i["gameplayDesc"].strip()]["msgstr"][0]
            x = i["icon"]["x"] * 24
            y = i["icon"]["y"] * 24
            box = (x, y, x + 24, y + 24)
            region = img.crop(box)
            region_arr = io.BytesIO()
            region.save(region_arr, format="PNG")

            Outfit(
                name=i["name"],
                name_en=i["name_en"],
                description=i["gameplayDesc"],
                icon=region_arr.getbuffer().tobytes(),
                cell_cost=i["cellCost"],
            )
