# -*- coding: utf-8 -*-

"""Main module."""
import discord
import random
import discord
import os
import requests
import aiocron
import asyncio
import giphy_client

from time import sleep
from discord.ext import tasks, commands
from subprocess import *
from sys import argv
from pathlib import Path
from giphy_client.rest import ApiException

class Mybot(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.sounds = []
        self.sounds_history = []
        self.play_next.start()

    @commands.command()
    async def join(self, ctx):
        channel = [x for x in self.bot.get_all_channels() if x.name == "Général"][0]
        await channel.connect()
        sleep(2)

    @commands.command()
    async def disconnect(self, ctx):
        await ctx.guild.voice_client.disconnect()

    @commands.guild_only()
    @commands.command()
    async def joke(self, ctx, folder=None):
        user = ctx.message.author.name
        if not folder or not ctx.message.content:
            audio_file = random.choice([f for f in Path('/home/mika/kabot/kabot/kabot/Audio/').glob('**/*.mp3')])
        else:
            folder = folder.lower()
            audio_file = random.choice([f for f in Path('/home/mika/kabot/kabot/kabot/Audio/').glob('**/*.mp3') if folder in str(f).lower()])
        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audio_file))
        self.sounds.append((source,ctx))

    @commands.command()
    async def repeat(self, ctx):
        #if ctx.message.author.name == self.bot.user.name:
        #    return
        user = ctx.message.author.name
        source = self.sounds_history[0]
        self.sounds.append((source,ctx))

    @commands.command(help='Gif me')
    async def gif(self, ctx):
        query = ctx.message.content
        api_instance = giphy_client.DefaultApi()
        api_key = "udhL9Rgdme3HpAoFhWVZoYM0l0XwkzLz"
        lang = 'fr'
        try:
            api_response = api_instance.gifs_search_get(api_key, query, lang=lang)
            api_response.to_dict()['data'][0]
            get_url = random.choice(api_response.to_dict()['data'])
            get_url['url']
            await ctx.channel.send(get_url['url'])
        except ApiException as e:
            await ctx.channel.send("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)

    @commands.command()
    async def welcome(self, ctx):
        #if ctx.message.author.name == self.bot.user.name:
        #    return
        user = ctx.message.author.name
        print(user)
        try:
            audio_file = random.choice([f for f in os.listdir('/home/mika/kabot/kabot/kabot/Audio/%s/' % user) if f.endswith('.mp3')])
            source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("/home/mika/kabot/kabot/kabot/Audio/%s/%s" % (user,audio_file)))
        except:
            audio_file = random.choice([f for f in Path('/home/mika/kabot/kabot/kabot/Audio/').glob('**/*.mp3')])
            source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audio_file))
        self.sounds.append((source,ctx))
        print(self.sounds)

    @commands.command(help='Update local repo')
    async def update(self, message):
        output = Popen('git pull'.split(), stdout=PIPE).communicate()[0]
        await message.channel.send(output.decode('utf-8'))

    @commands.command(help='Restart Bot')
    async def restart(self, ctx):
        await self.bot.logout()

    @commands.command(help='Restart Bot')
    async def restart_queue(self, ctx):
        self.play_next.restart()

    @commands.command(help='check if bot always online')
    async def ping(self, message):
        await message.channel.send('pong')

    @commands.command(help='count lines numbers in quote file')
    async def lines(self, ctx):
        path = '/home/mika/.kabot/%s.log' % ctx.channel
        with open(path, 'r') as f:
            lines = f.read().splitlines()
        nb_lines = len(lines)
        await ctx.channel.send("j'ai %s lignes dans mon stock" % nb_lines)

    @commands.command(help='slap this ass')
    async def slap(self, ctx, user=None):
        slap_multiple = [
                "%s prend un coup de pied au cul",
                "Descente du coude sur %s",
                "%s est propulsé par dessus la TROISIEME CORDE!",
                ]
        if not user or not ctx.message.mentions:
            online_members = []
            members = ctx.guild.members
            for member in members:
                if str(member.status) == "online":
                    online_members.append(member)
            user = random.choice(online_members)
            user = user.mention
        elif ctx.message.mentions:
            user = ctx.message.mentions[0]
            user = user.mention
        if user == self.bot.user.mention:
            await ctx.channel.send("je tribuche par terre et je sais pas comment")
        else:
            await ctx.channel.send(random.choice(slap_multiple) % user)

    @commands.command(help="optionnal args : [livre] [character]")
    async def kaamelott(self, ctx, *args):
        response = None
        url = 'https://kaamelott.chaudie.re/api/random'
        if args and ctx.message.content:
            args = list(args)
            if args[0].isdigit():
                livre = int(args[0])
                args.pop(0)
            elif args[-1].isdigit():
                livre = int(args[-1])
                args.pop(-1)
            else:
                livre = None
            if args:
                perso = ' '.join(args)
            if perso and livre:
                url = 'https://kaamelott.chaudie.re/api/random/livre/%s/personnage/%s' % (livre,perso)
            elif perso:
                url = 'https://kaamelott.chaudie.re/api/random/personnage/%s' % perso
            else:
                url = 'https://kaamelott.chaudie.re/api/random/livre/%s' % livre
        try:
            citation = requests.get(url).json()['citation']
            response = "%s :\n```\n%s\n```" % (citation['infos']['personnage'], citation['citation'])
        except:
            response = "Unknow error, try: !kaamelott [livre] [character]"
        await ctx.send(response)

    @tasks.loop(seconds=1.5)
    async def play_next(self):
        if self.sounds:
            source,ctx = self.sounds[0]
            if not ctx.voice_client.is_playing() and ctx.voice_client.is_connected():
                ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
                self.sounds.pop(0)
                self.sounds_history.insert(source,0)
                if len(self.sounds_history) >5:
                    self.sounds_history = self.sounds_history[:5]


def main():
    token = "NjI3MTM3NDY1MDA5ODMxOTQ2.XY4Raw.pw8sAen3bNR5aYsoTChQOudM0L8"
    bot = commands.Bot(command_prefix='!')

    test = False
    if "test" in argv[-1]:
        test=True

    @bot.event
    async def on_ready():
        print('yeah baby!')
        if test:
            await bot.logout()
        for channel in bot.get_all_channels():
            if channel.name == "général":
                current_chan = channel
        await current_chan.send('Le troll est dans la place !')
        ctx = await bot.get_context(current_chan.last_message)
        join = bot.get_command('join')
        await join.invoke(ctx)

    @aiocron.crontab('50 9-23/1 * * *')
    async def kron():
        kron_choice = random.choice(["kaamelott","slap","kaamelott",False])
        if kron_choice:
            await asyncio.sleep(random.choice(range(3550)))
            for channel in bot.get_all_channels():
                if channel.name == "général":
                    current_chan = channel
            ctx = await bot.get_context(current_chan.last_message)
            ctx.message.content = ""
            print(ctx.message.content)
            random_cmd = bot.get_command(kron_choice)
            await random_cmd.invoke(ctx)

    @aiocron.crontab('*/5 * * * *')
    async def pipelette():
        for channel in bot.get_all_channels():
            if channel.name == "Général" and\
                    len(channel.members) > 1 and\
                    random.choice([True,True,True]):
                for channel in bot.get_all_channels():
                    if channel.name == "général":
                        current_chan = channel
                await asyncio.sleep(random.choice(range(350)))
                ctx = await bot.get_context(current_chan.last_message)
                ctx.message.content = ""
                joke = bot.get_command('joke')
                await joke.invoke(ctx)

    @bot.event
    async def on_message(message):
        print(message.content)
        if message.author == bot.user:
            return
        else:
            if bot.user in message.mentions \
                    and len(message.mentions) < 3 \
                    and len(message.content.splitlines()) == 1:
                path = '/home/mika/.kabot/%s.log' % message.channel
                with open(path, 'r') as f :
                    lines = f.read().splitlines()
                if not message.content in lines:
                    with open(path, 'a') as f :
                        f.write(message.content + '\n')
                response = random.choice(lines).replace(str(bot.user.id), str(message.author.id))
                await message.channel.send(response)
        await bot.process_commands(message)

    @bot.event
    async def on_voice_state_update(member,before,after):
        if before.channel is None and after.channel:
            for channel in bot.get_all_channels():
                if channel.name == "général":
                    current_chan = channel
            ctx = await bot.get_context(current_chan.last_message)
            ctx.message.author = member
            welcome = bot.get_command('welcome')
            sleep(2)
            await welcome.invoke(ctx)

    bot.add_cog(Mybot(bot))
    bot.run(token)


if __name__ == "__main__":
    main()

