from discord.ext.commands import Bot
from discord.ext import commands
from discord import Game
import discord
import random
import requests
import json
import asyncio
from itertools import cycle
from googleapiclient.discovery import build

BOT_PREFIX = ("?", "!")
TOKEN = 'NDcyMTQ5MTA2MjgyODU2NDQ4.DjvMXg.XSt5iUUfBFVwzkSL38WS8tqORVA'

client = Bot(command_prefix=BOT_PREFIX)

### EVENTS ###
@client.event
async def on_ready():
    await client.change_presence(game=Game(name="with humans"))
    print("Logged in as " + client.user.name)

@client.event
async def on_message(message):
    author = message.author
    content = message.content
    print("{}: {}".format(author, content))
    # makes sure client still processes command (checks if it's a command)
    await client.process_commands(message)

@client.event
async def on_message_delete(message):
    author = message.author
    content = message.content
    channel = message.channel
    await client.send_message(channel, "{}: {}".format(author, content))

@client.event
async def on_member_join(member):
    role = discord.utils.get(member.server.roles, name='noob')
    await client.add_roles(member, role)


### COMMANDS ###
@client.command(name='8ball',
                description="Answers a yes/no question.",
                brief="Answers from the beyond.",
                aliases=['eight_ball', 'eightBall', '8-ball'],
                pass_context=True)
async def eight_ball(context):
    possible_responses = [
       'That is a resounding no',
       'It is not looking likely',
       'Too hard to tell',
       'It is quite possible',
       'Definitely',
    ] 
    await client.say(random.choice(possible_responses) + ", " + context.message.author.mention)

@client.command(description="Bot echoes message.")
async def echo(*args):
    output = ''
    for word in args:
        output += word
        output += ' '
    await client.say(output)

@client.command(description="Squares a number.")
async def square(number):
    squared_value = int(number) * int(number)
    await client.say(str(number) + " squared is " + str(squared_value))

@client.command(description="States the server rules.")
async def rules():
    await client.say("The Rules: \n"
                   + "1. No whining"
                   + "2. Don't be trash"
                   + "3. Arden is the Supreme Overlord of the serer and will be addressed as such.")

@client.command(description="Fetches the current price of bitcoin.")
async def bitcoin():
    url = "https://api.coindesk.com/v1/bpi/currentprice/BTC.json"
    response = requests.get(url)
    value = response.json()['bpi']['USD']['rate']
    await client.say("Bitcoin price is $" + value)

@client.command(description="Fetches a player's Fortnite stats.")
async def fortnite(nickname):
    url = "https://api.fortnitetracker.com/v1/profile/pc/"+ nickname
    key = {'TRN-Api-Key' : 'de6135b6-43cb-40af-9985-872ae3cd6464'}
    response = requests.get(url, headers=key)
    #jsonData = json.loads(response.text)

    #platform = response.json()['platformNameLong']
    userName = response.json()['epicUserHandle']
    top5s = response.json()['lifeTimeStats'][0]['value']
    top3s = response.json()['lifeTimeStats'][1]['value']
    top10s = response.json()['lifeTimeStats'][3]['value']
    numMatches = response.json()['lifeTimeStats'][7]['value']
    wins = response.json()['lifeTimeStats'][8]['value']
    winPct = response.json()['lifeTimeStats'][9]['value']
    kills = response.json()['lifeTimeStats'][10]['value']
    kd = response.json()['lifeTimeStats'][11]['value']

    await client.say(userName+"'s stats: " + "\n"
                     + "Number of matches: " + str(numMatches) + "\n"
                     + "Top 10s: " + str(top10s) + "\n"
                     + "Top 5s: " + str(top5s)  + "\n"
                     + "Top 3s: " + str(top3s) + "\n"
                     + "Wins: " + str(wins) + "\n"
                     + "Win percentage: " + str(winPct) + "\n"
                     + "Kills: " + str(kills) + "\n"
                     + "K/D: " + str(kd) + "\n"
        )

@client.command(description="Clears N messages from the chat log.",
                pass_context=True)
async def clear(ctx, amount=100):
    channel = ctx.message.channel
    messages = []
    async for message in client.logs_from(channel, limit=int(amount)):
        messages.append(message)
    await client.delete_messages(messages)
    await client.say("Messages deleted.")
    #TODO implement error checks

@client.command()
async def play(url):
    service = build('youtube', 'v3', 
                    developerKey="AIzaSyCKhNtn0JOlybiDsHN6IAP404aPuNBNEDE")
    pass

### OTHER STUFF ###
async def list_servers():
    await client.wait_until_ready()
    while not client.is_closed:
        print("Current servers:")
        for server in client.servers:
            print(server.name)
        await asyncio.sleep(600)

client.loop.create_task(list_servers())

# fortune cookie()
# weather(zipcode)
# dictionary(word)
# dice_roll()
# remind_me("string", delay)
# boot("UserName")

# handles event loop
client.run(TOKEN)
