# • Plugin of Friday Userbot •
# • Ported for Ultroid by @e3ris •

# < https://github.com/TeamUltroid/Ultroid >

"""
✘ **Zombie.exe** :
  ••  `{i}izombie <reply to photo>`
"""

import asyncio
import requests
from os import remove
from base64 import b64decode as b64d

from . import *


@ultroid_cmd(pattern="izombie$")
async def me_zombie(e):
    img_path = "izombie.png"
    reply = await e.get_reply_message()
    eris = await eor(e, "`Creating a zombie..`")
    if not reply and not reply.media:
        await eod(eris, "`Reply to a Photo, Master!`")
        return
    if reply.file.mime_type.split("/")[0] != "image":
        await eris.edit("`Not a Valid file 😟\nReply to a Photo instead!`")
        return
    dls = await e.client.download_media(reply)
    zomb = await mek_me_zombie(dls)
    if "face" in zomb.lower():
        await eris.edit("No Face detected in this Image.")
        return
    await eris.edit("Converting to Zombie now!")
    await asyncio.sleep(1)
    remove(img_path) if os.path.exists(img_path) else None
    try:
        xx = open(img_path, "wb+").write(b64d(str(zomb)))
    except Exception as ex:
        await eod(eris, str(ex), time=12)
        return
    try:
        await e.client.send_file(
            e.chat_id,
            img_path,
            force_document=False,
            reply_to=e.reply_to_msg_id,
            silent=True,
        )
        await eris.delete()
    except Exception as ex:
        await eod(eris, f"#ERROR : `{ex}`", time=10)
    finally:
        for c in [img_path, dls]:
            remove(c) if os.path.exists(c) else None


async def mek_me_zombie(img_path):
    # This plugin is ported from Friday!
    path_ = {"image": (img_path, open(img_path, "rb"))}
    req = requests.post(
        "https://deepgrave-image-processor-no7pxf7mmq-uc.a.run.app/transform",
        files=path_,
    )
    return req.text
