import discord
import os
import praw
import random
import re
import csv
import aiohttp

from dotenv import load_dotenv


load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
SECRET = os.getenv('REDDIT_SECRET')
REDDIT_ID = os.getenv('REDDIT_ID')
REDDIT_AGENT = os.getenv('REDDIT_AGENT')

PROXY = os.getenv('PROXY')
postLimit = int(os.getenv('POST_LIMIT'))

subreddits = dict()

class Entry:
    def __init__(self, name, subName):
        self.subreddit = praw.Reddit(   client_id=REDDIT_ID, \
                                        client_secret=SECRET, \
                                        user_agent=REDDIT_AGENT).subreddit(subName)
        self.name = name
        subreddit = None
        self.subName = subName
        self.posts = []
        self.authors = []
        self.posturls = []
        self.totalimgs = 0


with open('subreddits.csv', mode ='r') as file:
    csvFile = csv.reader(file)
    for lines in csvFile:
        if lines != []:
            subreddits[lines[0]] = Entry(lines[0], lines[1])


def refresh_posts(entry):
    print('Refreshing posts for ' + entry.name + '!')
    entry.posts.clear()
    entry.authors.clear()
    entry.posturls.clear()
    entry.totalimgs=0
    i=0
    for submission in entry.subreddit.hot(limit=postLimit):
        #_ = os.system('clear')
        i = i + 1
        entry.totalimgs = entry.totalimgs + 1
        print('Getting submission number '+ str(i) + ' / ' + str(postLimit) + '!')
        if ".jpg" not in submission.url and ".png" not in submission.url:
            print('Post is not a jpg or png --------------------------')
            print(str(submission.url))
            entry.totalimgs = entry.totalimgs - 1
            continue
        entry.posts.append(submission.url)
        entry.authors.append(submission.author)
        entry.posturls.append(submission.permalink)
    print('Total amount of images: '+str(entry.totalimgs))

def refresh_all_posts():
    for entry in subreddits.values():
        refresh_posts(entry)


def create_embed(post,author,posturl):
    embed = discord.Embed(
        color = discord.Colour.dark_orange()
        )
    embed.set_image(url=post)
    embed.description ='['+str(author)+'](https://www.reddit.com'+str(posturl)+')'
    return embed

refresh_all_posts()

if PROXY != "":
    client = discord.Client(proxy=PROXY)
else:
    client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    lower = message.content.lower()
    if lower == "show me an help" or lower == "show me a help":
        mess = "Usage : ``show me a xxxx`` or ``show me an xxxx`` or ``show me more xxxx``\nCurrently, I can show :```"
        for entry in subreddits.values():
            mess += entry.name + " with a picture from r/" + entry.subName + "\n"
        mess += "\n```"
        await message.channel.send(mess)
    if ("show me a" in lower) or ("show me more" in lower):
        name = re.search(r"show me (an?|more) ([\S]+)s?", lower)
        if name == None:
            return
        else:
            name = name.group(2)

        if name in subreddits.keys():
            print('asking for the following entry: ' + name)
            postnumber = random.randint(1,subreddits[name].totalimgs)
            await message.channel.send(embed = create_embed(subreddits[name].posts[postnumber], subreddits[name].authors[postnumber], subreddits[name].posturls[postnumber]))

    #if "refresh the kumikos" in message.content.lower():
    #    refresh_all_posts()

client.run(TOKEN)