import discord
from discord.ext import commands
from discord.ext.tasks import loop
from discord import HTTPException
from settings import token
import time
import datetime

client = discord.Client()
ignore_list = [846756271910158378]
#shit api. got switched like 1 year ago so like every single discusison about it is outdated. 

def get_suggestion_type(msg):
    suggestion_type = "GENERIC"
    if msg.startswith('!ze'):
        suggestion_type = "ZOMBIE ESCAPE"
        msg = msg.replace('!ze', '')
    elif msg.startswith('!mg'):
        suggestion_type = "MINIGAME"
        msg = msg.replace('!mg', '')
    elif msg.startswith('!zr'):
        suggestion_type = "ZOMBIE RIOT"
        msg = msg.replace('!zr', '')
    elif msg.startswith('!forum'):
        suggestion_type = "FORUM"
        msg = msg.replace('!forum', '')
    elif msg.startswith('!discord'):
        suggestion_type = "DISCORD"
        msg = msg.replace('!discord', '')
    elif msg.startswith('!meta'):
        suggestion_type = "META"
        msg = msg.replace('!meta', '')
    return suggestion_type, msg.strip()

@client.event
async def on_message(message):
    if message.author.bot:
        return
    if message.author.id in ignore_list:
        msg = f'{message.author.name} Your suggestion was ignored because you made too many shitty suggestions already. Do not post in this channel anymore because your retarded.'
        await message.channel.send()
        return
    if message.channel.name == 'suggestion-box': #suggestion-box
        channel = client.get_channel(872925751295504476) #872925751295504476
        message_content = message.content
        suggestion_type, message_content = get_suggestion_type(message_content)
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        send_msg = f"""```DISCORD USER ID: {message.author.id}\nUSERNAME: {message.author}\nTYPE: {suggestion_type}\nTIME: {now}\nSTATUS: No admin interested yet (mark with an emote to prevent suggestion deletion within 48 hours)\nSUGGESTION: {message_content}```"""
        send_channel_msg = f"""{message.author} your suggestion was sent to admins as type: {suggestion_type}. Specify Suggestion types by appending your message with one of the following commands: !ze !zr !mg !forum !discord !meta. \nSpamming the suggestion channel with useless crap will lead to ban."""
        await message.channel.send(send_channel_msg)
        await channel.send(send_msg)

@loop(seconds = 10)
async def check_suggestions_to_delete():
    global client
    for channel in client.get_all_channels():
        if channel.name == 'suggestion-admin':
            msgs_history = channel.history()
            j1 = await msgs_history.flatten()
            status_msg = "STATUS: No admin interested yet (mark with an emote to prevent suggestion deletion within 48 hours)"
            status = 'STATUS:' 
            suggestion = 'SUGGESTION:'
            for msg in j1:
                if len(msg.reactions) == 0:
                    created_at = msg.created_at
                    if created_at < datetime.datetime.now()-datetime.timedelta(days=2):
                        print('deleting message: ', msg.content)
                        await msg.delete()
                    else:
                        first_part = msg.content.split(status)[0]
                        last_part = msg.content.split(suggestion)[1]
                        final_msg = f'{first_part}{status_msg}\n{suggestion}{last_part}'
                        await msg.edit(content=final_msg)
                elif status in msg.content:
                    first_part = msg.content.split(status)[0]
                    last_part = msg.content.split(suggestion)[1]
                    user_reactions = []
                    for react in msg.reactions:
                        users = react.users()
                        j2 = await users.flatten()
                        for user in j2:
                            if user.name not in user_reactions:
                                user_reactions.append(user.name)
                    final_msg = f'{first_part}STATUS: Admins interested in topic:{user_reactions}\n{suggestion}{last_part}'
                    try:
                        await msg.edit(content=final_msg)
                    except HTTPException:
                        time.sleep(300)
                        client = discord.Client()
                        check_suggestions_to_delete.start()
                        client.run(token)

#the entire syntax that is visisble from python3 terminal is not very well displayed in the docs of discord.py and nobody has the current syntax in any suggestions anywhere on the internet. almost every single thing is out of date reee
if __name__ == '__main__':
    check_suggestions_to_delete.start()
    client.run(token)
