# 👍 https://github.com/D3vd for his awesome API
#
# Copyright (C) 2020 BY - GitHub.com/code-rgb [TG - @DeletedUser420]
# All rights reserved.
# Ported to Ultroid by @e3ris.

"""
> Get a Image Post from Reddit.
> CMD: `{i}reddit (subreddit_name)`
"""

import requests
import json

from . import *


@ultroid_cmd(pattern="reddit ?(.*)")
async def reddit_fetch(event):
    if event.fwd_from:
    	return
    API = "https://meme-api.herokuapp.com/gimme"
    eris = await eor(event, "`...`")
    args = event.pattern_match.group(1)
    subreddit = f"{API}/{args}" if args else API
    try:
        cn = requests.get(subreddit)
        r = cn.json()
    except ValueError:
        return await eod(eris, "`Value error...`")
    if "code" in r:
        code = r["code"]
        code_message = r["message"]
        await asst.send_message(
            int(Redis("LOG_CHANNEL")), f"Error [Reddit.py]:\n{code}\n`{code_message}`"
        )
        return await eod(eris, f"`Error Occurred! {code}`")
    else:
        if "url" not in r:
            return await eod(eris, "`e3rror, try again` 🤷🏻‍♀️")
        postlink = r["postLink"]
        subreddit = r["subreddit"]
        title = r["title"]
        media_url = r["url"]
        author = r["author"]
        upvote = r["ups"]
        captionx = f"**{title}**\n"
        captionx += f"`Posted by u/{author}`\n"
        captionx += f"↕️ `{upvote}`\n"
        if r["spoiler"]:
            captionx += "⚠️ Post marked as SPOILER\n"
        if r["nsfw"]:
            captionx += "🔞 Post marked Adult \n"

        await eris.delete()
        captionx += f"Source: [r/{subreddit}]({postlink})"
        sandy = await ultroid.send_file(
            event.chat_id, media_url, caption=captionx, reply_to=event.reply_to_msg_id if event.is_reply else None,
        )


HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})


