# Copyright (C) 2020 Yusuf Usta.
#
# Licensed under the  GPL-3.0 License;
# you may not use this file except in compliance with the License.
#

# Asena UserBot - Yusuf Usta

import os
from telethon.tl.types import InputMessagesFilterDocument
from userbot.events import register
from userbot import BOT_USERNAME, PATTERNS, CMD_HELP, PLUGIN_CHANNEL_ID, ASENA_VERSION
import userbot.cmdhelp
from random import choice, sample
import importlib
import re
from userbot.main import extractCommands

# â–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆ LANGUAGE CONSTANTS â–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆ #

from userbot.language import get_value
LANG = get_value("__plugin")

# â–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆ #

# Plugin MaÄŸazasÄ±
@register(outgoing=True, pattern="^.store ?(.*)")
@register(outgoing=True, pattern="^.ma[gÄŸ]aza ?(.*)")
async def magaza(event):
    plugin = event.pattern_match.group(1)
    await event.edit('**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon ' + ASENA_VERSION + '__\n\n' + '`ğŸ”� Plugin\'i arÄ±yorum... LÃ¼tfen biraz bekle.`')
    split = plugin.split()
    if plugin == '':
        plugin = 'Son YÃ¼klenen'
        plugins = await event.client.get_messages('@asenaplugin', limit=15, filter=InputMessagesFilterDocument)
    elif len(split) >= 1 and (split[0] == 'random' or split[0] == 'rastgele'):
        plugin = 'Rastgele'
        plugins = await event.client.get_messages('@asenaplugin', limit=None, filter=InputMessagesFilterDocument)
        plugins = sample(plugins, int(split[1]) if len(split) == 2 else 5)
    else:
        plugins = await event.client.get_messages('@asenaplugin', limit=None, search=plugin, filter=InputMessagesFilterDocument)
        random = await event.client.get_messages('@asenaplugin', limit=None, filter=InputMessagesFilterDocument)
        random = choice(random)
        random_file = random.file.name

    result = f'**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon {ASENA_VERSION}__\n\n**ğŸ”� Arama:** `{plugin}`\n**ğŸ”¢ SonuÃ§lar: __({len(plugins)})__**\nâ�–â�–â�–â�–â�–\n\n'
    
    if len(plugins) == 0:
        result += f'**HiÃ§bir ÅŸey bulamadÄ±m...**\n`{random_file}` __pluginine ne dersin?__'
    else:
        for plugin in plugins:
            plugin_lines = plugin.raw_text.splitlines()
            result += f'**â¬‡ï¸� {plugin_lines[0]}** `({plugin.file.name})`**:** '
            if len(plugin_lines[2]) < 50:
                result += f'__{plugin_lines[2]}__'
            else:
                result += f'__{plugin_lines[2][:50]}...__'
            result += f'\n**â„¹ï¸� YÃ¼klemek iÃ§in:** `{PATTERNS[:1]}sinstall {plugin.id}`\nâ�–â�–â�–â�–â�–\n'
    return await event.edit(result)

# Plugin MaÄŸazasÄ±
@register(outgoing=True, pattern="^.sy[Ã¼u]kle ?(.*)")
@register(outgoing=True, pattern="^.sinstall ?(.*)")
async def sinstall(event):
    plugin = event.pattern_match.group(1)
    try:
        plugin = int(plugin)
    except:
        return await event.edit('**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon ' + ASENA_VERSION + '__\n\n**âš ï¸� Hata:** `LÃ¼tfen sadece sayÄ± yazÄ±n. EÄŸer Plugin aramak istiyorsanÄ±z .store komutunu kullanÄ±n.`')
    
    await event.edit('**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon ' + ASENA_VERSION + '__\n\n`ğŸ”� Plugin\'i getiriyorum... LÃ¼tfen biraz bekle.`')
    plugin = await event.client.get_messages('@asenaplugin', ids=plugin)
    await event.edit(f'**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon {ASENA_VERSION}__\n\n`âœ… {plugin.file.name} plugini getirildi!`\n`â¬‡ï¸� Plugini indiriyorum... LÃ¼tfen bekleyiniz.`')
    dosya = await plugin.download_media('./userbot/modules/')
    await event.edit(f'**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon {ASENA_VERSION}__\n\n`âœ… {plugin.file.name} indirme baÅŸarÄ±lÄ±!`\n`â¬‡ï¸� Plugini yÃ¼klÃ¼yorum... LÃ¼tfen bekleyiniz.`')
    
    try:
        spec = importlib.util.spec_from_file_location(dosya, dosya)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
    except Exception as e:
        os.remove("./userbot/modules/" + dosya)
        return await event.edit(f'**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon {ASENA_VERSION}__\n\n**âš ï¸� Hata:** `Plugin hatalÄ±. {e}`\n**LÃœTFEN BUNU ADMÄ°NLERE BÄ°LDÄ°RÄ°N!**')

    dosy = open(dosya, "r").read()
    if re.search(r"@tgbot\.on\(.*pattern=(r|)\".*\".*\)", dosy):
        komu = re.findall(r"\(.*pattern=(r|)\"(.*)\".*\)", dosy)
        komutlar = ""
        i = 0
        while i < len(komu):
            komut = komu[i][1]
            CMD_HELP["tgbot_" + komut] = f"{LANG['PLUGIN_DESC']} {komut}"
            komutlar += komut + " "
            i += 1
        await event.edit(LANG['PLUGIN_DOWNLOADED'] % komutlar)
    else:
        Pattern = re.findall(r"@register\(.*pattern=(r|)\"(.*)\".*\)", dosy)

        if (not type(Pattern) == list) or (len(Pattern) < 1 or len(Pattern[0]) < 1):
            if re.search(r'CmdHelp\(.*\)', dosy):
                cmdhelp = re.findall(r"CmdHelp\([\"'](.*)[\"']\)", dosy)[0]
                await plugin.forward_to(PLUGIN_CHANNEL_ID)
                return await event.edit(f'**ModÃ¼l baÅŸarÄ±yla yÃ¼klendi!**\n__ModÃ¼lun komutlarÄ± ve kullanÄ±m hakkÄ±nda bilgi almak iÃ§in__ `.asena {cmdhelp}` __yazÄ±nÄ±z.__')
            else:
                await plugin.forward_to(PLUGIN_CHANNEL_ID)
                userbot.cmdhelp.CmdHelp(dosya).add_warning('Komutlar bulunamadÄ±!').add()
                return await event.edit(LANG['PLUGIN_DESCLESS'])
        else:
            if re.search(r'CmdHelp\(.*\)', dosy):
                cmdhelp = re.findall(r"CmdHelp\([\"'](.*)[\"']\)", dosy)[0]
                await plugin.forward_to(PLUGIN_CHANNEL_ID)
                return await event.edit(f'**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon {ASENA_VERSION}__\n\n**âœ… ModÃ¼l baÅŸarÄ±yla yÃ¼klendi!**\n__â„¹ï¸� ModÃ¼lun komutlarÄ± ve kullanÄ±m hakkÄ±nda bilgi almak iÃ§in__ `.asena {cmdhelp}` __yazÄ±nÄ±z.__')
            else:
                dosyaAdi = plugin.file.name.replace('.py', '')
                extractCommands(dosya)
                await plugin.forward_to(PLUGIN_CHANNEL_ID)
                return await event.edit(f'**ğŸ�º Asena Plugin MaÄŸazasÄ±**\n__Versiyon {ASENA_VERSION}__\n\n**âœ… ModÃ¼l baÅŸarÄ±yla yÃ¼klendi!**\n__â„¹ï¸� ModÃ¼lun komutlarÄ± ve kullanÄ±m hakkÄ±nda bilgi almak iÃ§in__ `.asena {dosyaAdi}` __yazÄ±nÄ±z.__')

userbot.cmdhelp.CmdHelp('store').add_command(
    'store', '<kelime>', 'Plugin kanalÄ±na son atÄ±lan Pluginleri getirir. EÄŸer kelime yazarsanÄ±z arama yapar.'
).add_command(
    'store random', '<sayÄ±>', 'Pluginden kanalÄ±ndan rastgele plugin getirir.', 'store random 10'
).add_command(
    'sinstall', '<sayÄ±>', 'Plugin kanalÄ±ndan direkt olarak Plugini yÃ¼kler.'
).add()