import configparser
import discord
from discord.ext import commands
import json
import os.path
import sys
import httplib2
import logging


from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains

# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
YOUTUBE_READ_WRITE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
   %s
with information from the APIs Console
https://console.developers.google.com
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, message=MISSING_CLIENT_SECRETS_MESSAGE, scope=YOUTUBE_READ_WRITE_SCOPE)

storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()

if credentials is None or credentials.invalid:
    flags = argparser.parse_args()
    credentials = run_flow(flow, storage, flags)

youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http()))

parser = configparser.ConfigParser()
parser.read('userconfig.ini')

description = """A bot written by Kuenaimaku in order to offer various utilities."""
client = discord.Client()

discord_logger = logging.getLogger('discord')
discord_logger.setLevel(logging.CRITICAL)
log = logging.getLogger()
log.setLevel(logging.INFO)
handler = logging.FileHandler(filename='discordBot.log', encoding='utf-8', mode='w')
log.addHandler(handler)

bot = commands.Bot(command_prefix='!', description=description)

filepath = 'config/serverlist.json'
if not os.path.exists(os.path.dirname(filepath)):
    os.makedirs(os.path.dirname(filepath))
    temp = {"shards": [{"id":"0","name":"0","role":"0","playlistId":"0"}]}
    with open(filepath, 'w') as data_file:
        json.dump(temp, data_file)
        data_file.close()

with open('config/serverlist.json', 'r') as data_file:
    serverlist = json.load(data_file)
data_file.close()


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    await bot.change_presence(game=discord.Game(name='with a Toolkit'))


@bot.event
async def on_server_join(server):
    with open('config/serverlist.json', 'r') as data_file:
        serverlist = json.load(data_file)
    in_list = False
    player_role = await bot.create_role(server, name="Gambling Addict")
    manager_role = await bot.create_role(server, name="Salty Dealer")
    await bot.create_channel(server, 'Salty_Casino')
    await bot.add_roles(server.owner, manager_role)
    for x in serverlist["shards"]:
        if x["id"] == server.id:
            in_list = True
    if not in_list:
        walletpath = 'casino/' + server.name+ '/wallet.json'
        if not os.path.exists(os.path.dirname(walletpath)):
            os.makedirs(os.path.dirname(walletpath))
            temp = [{"points": 0, "server_id": "0", "user_id": "0"}]
            with open(walletpath, 'w') as data_file:
                json.dump(temp, data_file)
                data_file.close()
        betspath = 'casino/' + server.name + '/bets.json'
        temp = [{"points": 0, "server_id": "0", "user_id": "0", "name": "0", "type": "default"}]
        with open(betspath, 'w') as data_file:
            json.dump(temp, data_file)
        data_file.close()
        matchpath = 'casino/' + server.name + '/match.json'
        temp = {}
        with open(matchpath, 'w') as data_file:
            json.dump(temp, data_file)
        data_file.close()
        playlists_insert_response = youtube.playlists().insert(
            part="snippet,status",
            body=dict(
                snippet=dict(
                    title= server.name + " Discord Playlist",
                    description="A playlist whose videos are aggregated from comments on the " + server.name + " Discord server."
                ),
                status=dict(
                    privacyStatus="public"
                )
            )
        ).execute()
        shard = {'playlistId': playlists_insert_response["id"], 'name':server.name, 'role': '@everyone', 'id': server.id}
        serverlist["shards"].append(dict(shard))
        with open('config/serverlist.json', 'w') as data_file:
            json.dump(serverlist, data_file)
        data_file.close()
        with open('config/serverlist.json', 'r') as data_file:
            serverlist = json.load(data_file)
    else:
        print('server ' + server.name + ' is already in serverlist.json')


initial_extensions = [
    'cogs.stickers',
    'cogs.gifs',
    'cogs.youtube',
    'cogs.rng',
    'cogs.LoL',
    'cogs.twitch',
    'cogs.casino',
    'cogs.voice',
    'cogs.text',
]

if __name__ == '__main__':
    for extension in initial_extensions:
        try:
            bot.load_extension(extension)
        except Exception as e:
            print('Failed to load extension {}\n{}: {}'.format(extension, type(e).__name__, e))
    bot.run(parser.get('discord', 'token'))
