#!/usr/bin/python3

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

clientI = 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()

@clientI.event
async def on_message(message):
    if message.author.bot:
        return
    if message.channel.name == 'suggestion-box': #suggestion-box
        message_content = message.content
        global clientI
        channel_suggestion_admin = clientI.get_channel(872925751295504476)
        #print('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."""
        print('send_channel_msg: ', send_channel_msg)
        print('send_msg: ', send_msg)
        await message.channel.send(send_channel_msg)
        await channel_suggestion_admin.send(send_msg)

j = None
@loop(seconds = 10)
async def check_suggestions_to_delete():
    global j
    global clientI
    for channel in clientI.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:'
            j = j1
            for msg in j1:
                if not msg.author.bot:
                    continue
                #print('msg: ', msg)
                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:
                        #print('react: ', react)
                        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 Exception:
                        err = traceback.format_exc()
                        print("err traceback: ", err)
                        """
                        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()
    clientI.run(token)
