# -*- coding: utf8 -*-


import irclib
import ircbot
import random
import time
import module_red as red
import rateau
from fuzzywuzzy import fuzz
import requests
from HTMLParser import HTMLParser
import philotron
import pipotron
import viieux
import codage
import nordpresse
import commit
import kohlanta
from ensiee import ensiee
from quizz import quizz
from useless import useless
from haddock import haddock
from manger import is_l_heure_de_manger, should_ban
from bdsm import bdsm

import config
# import rateau


def couper(pseudo):
    return pseudo.split("!")[0]


def aram():
    Champ = [" Aatrox ", " Ahri ", " Akali ", " Alistar ", " Amumu ", " Anivia ", " Annie ", " Ashe ", " Azir ",
             " Bard ", " Blitzcrank ", " Brand ", " Braum ", " Caitlyn ", " Cassiopeia ", " Cho'Gath ", " Corki ",
             " Darius ", " Diana ", " Dr.Mundo ", " Draven ", " Ekko ", " Elise ", " Evelynn ", " Ezreal ",
             " Fiddlesticks ", " Fiora ", " Fizz ", " Galio ", " Gangplank ", " Garen ", " Gnar ", " Gragas ",
             " Graves ", " Hecarim ", " Heimerdinger ", " Irelia ", " Janna ", " Jarvan IV ", " Jayce ", " Jax ",
             " Jinx ", " Kalista ", " Karma ", " Karthus ", " Kassadin ", " Katarina ", " Kayle ", " Kennen ",
             " Kha'Zix", " Kog'Maw ", " LeBlanc ", " Lee Sin ", " Leona ", " Lissandra ", " Lucian ", " Lulu ", " Lux ",
             " Maître Yi ", " Malphite ", " Malzahar ", " Maokai ", " Miss Fortune ", " Mordekaiser ", " Morgana ",
             " Nami ", " Nasus ", " Nautilus ", " Nidalee ", " Nocturne ", " Nunu ", " Olaf ", " Orianna ",
             " Pantheon ", " Poppy ", " Quinn ", " Rammus ", " Rek'Sai ", " Renekton ", " Rengar ", " Riven ",
             " Rumble ", " Ryze ", " Sejuani ", " Shaco ", " Shen ", " Shyvana ", " Singed ", " Sion ", " Sivir ",
             " Skarner ", " Sona ", " Soraka ", " Swain ", " Syndra ", " Tahm Kench ", " Talon ", " Taric ", " Teemo ",
             " Thresh ", " Tristana ", " Trundle ", " Tryndamere ", " Twisted Fate ", " Twitch ", " Udyr ", " Urgot ",
             " Varus ", " Vayne ", " Veigar ", " Vel'Koz ", " Vi ", " Viktor ", " Vladimir ", " Volibear ", " Warwick ",
             " Wukong ", " Xerath ", " Xin Zhao ", " Yasuo ", " Yorick ", " Zac ", " Zed ", " Ziggs ", " Zilean ",
             " Zyra"]
    return Champ[random.randint(0, len(Champ) - 1)]


last_args = None
last_cmd = None
global pour
pour = []
global suple
suple = -1


personnalizedCmd = {}


reponse = None
pas_reponse = []
a_repondu = []
scores = {}
tour = 0
total = 0

# Pacho 
pachoTime = time.time()


def convert_seconds_to_days(seconds) :
    seconds_in_day = 60 * 60 * 24
    seconds_in_hour = 60 * 60
    seconds_in_minute = 60
    days = seconds // seconds_in_day
    hours = (seconds - (days * seconds_in_day)) // seconds_in_hour
    minutes = (seconds - (days * seconds_in_day) - (hours * seconds_in_hour)) // seconds_in_minute
    secondes =  seconds - (days * seconds_in_day) - (hours * seconds_in_hour) - minutes * seconds_in_minute
    return str(days) + " jours, " + str(hours) + " heures, " + str(minutes) + " minutes, " + str(secondes) + " secondes. (total : " + str(seconds) + ")"


def isCommande(string):
    return string[0] == config.cmdCarac


def no_hl(pseudo):
    ins = u'\u200C'.encode("utf-8")
    return pseudo[0] + str(ins) + pseudo[1:]

def split_message(message) : 
    return [message[i:i+150] for i in range(0, len(message), 150)]


class Boooob(ircbot.SingleServerIRCBot):
    def __init__(self):
        ircbot.SingleServerIRCBot.__init__(
            self, [("irc.iiens.net", 6667)], config.nick, "Je suis un bot")
        self.temps = 0
        self.reddit_temps = 0
        self.fichier_reddit = "canaux_reddit.txt"
        self.clever = -1

    #
    def on_welcome(self, serv, ev):
        serv.join("#nardco")
        serv.join("#fokontest")
        serv.join("#Titch")
        serv.join("#reddit")
        serv.join("#senseo")
        serv.join("#spoil")
        # serv.join("#gynecoloc")
        serv.privmsg("NickServ", "IDENTIFY {0}".format(
            config.password))  # rejoint #nardco à sa connexion

    #
    def on_join(self, serv, ev):  # Quand qq entre dans le chann, le bot inclus
        auteur = str(irclib.nm_to_n(ev.source()))
        canal = ev.target()

    def on_invite(self, serv, ev):
        personne = ev.source()
        canal = ev.arguments()[0]
        serv.privmsg("Titch", couper(personne) + " m'a invité sur " + canal)
        serv.join(canal)

    def on_kick(self, serv, ev):
        personne = ev.source()
        personne = couper(personne)
        canal = ev.target()
        if canal == "#Titch" and personne != "Titch":
            serv.mode(canal, "-o " + personne)

    def on_pubmsg(self, serv, ev):  # quand qq ecrit dans le chat
        global suple
        global personnalizedCmd
        global last_args
        global last_cmd
        global reponse
        global a_repondu
        global pas_reponse
        global tour
        global scores
        global total
        global pachoTime

        canal = ev.target()

        personne = ev.source()


        personne = couper(personne)

        message = ev.arguments()[0]

        print personne
        if personne == "Senseo" : 
            serv.privmsg(canal, "<" + no_hl("Senseo") + "> : " + message)

        originalMessage = message
        message = message.lower()  # Passe le message en minuscules
        split = message.split(" ")
        if "op pls" in message or "op plz" in message:
            serv.mode(canal, "+o "+personne)
        if config.nick in split[0] and ' ou ' in message:
            splt = split[1:]
            idx = splt.index("ou")
            choice = random.randint(0, 1)
            if choice == 0:
                res = splt[:idx]
            else:
                if '?' in splt[-1]:
                    res = splt[idx+1:-1]
                else:
                    res = splt[idx+1:]
            serv.privmsg(canal, ' '.join(res) + "!")

        # lol of legends
        if " aram " in message:
            people = ["Jara", "Nami"]
            if personne in people:
                if "Jara" in personne:
                    serv.privmsg(canal, "TOURBILOL DEBILE MOUHAHAHA")
                if "Nami" in personne:
                    serv.privmsg(canal, "Non Nami, ton main n'est pas op ! <3")
            else:
                serv.privmsg(canal, "A l'evidence," + aram() + "est totalement op.")

            # les lignes suivantes sont pour le lol
        if "Titch" in personne and "tg" in message:
            #serv.privmsg(canal, "Oui maitre...")
            suple = -1

        if "Titch" in personne and "openbar" in message:
            serv.privmsg(canal, "OPEN BAAAAAAR")
            suple = 1
        if "souple" in message and suple == 1:
            serv.privmsg(canal, "et fruité")
        if "fruité" in message and suple == 1:
            serv.privmsg(canal, "et gouleyant")
        if "gouleyant" in message and suple == 1:
            serv.privmsg(canal, "et souple")

        if suple == 1 and ("dur" in message or "long" in message or "court" in message or "molle" in message):
            serv.privmsg(canal, "Comme ta bite " + personne + "! ")
        if suple == 1:
            if "aucun lien" in message:
                serv.privmsg(canal, "Je suis fils unique...")

                # fonctions de deplacement dans les chann

        if "Saltitch" in personne and "goto" in message and config.nick in message:
            f = 0
            for f in range(len(message) - 4):
                if message[f:f + 4] == "goto":
                    serv.join("#" + message[f + 5:])
                    break
        if "Saltitch" in personne and "leave" in message and config.nick in message:
            serv.part(canal)

        if reponse is not None:
            if fuzz.ratio(message, reponse) > 60 and personne not in a_repondu:
                serv.privmsg(canal, personne +
                             " a trouvé la reponse : {0} ! Bien joué !".format(reponse))
                reponse = None
                a_repondu = []
                pas_reponse = []
                tour += 1
                if personne in scores.keys():
                    scores[personne] += 1
                else:
                    scores[personne] = 1

                if tour == total:
                    maxScore = 0
                    gagnant = ''

                    for pseudo in scores.keys():
                        if scores[pseudo] > maxScore:
                            maxScore = scores[pseudo]
                            gagnant = pseudo
                    serv.privmsg(
                        canal, "{0} a gagné avec un score de {1}".format(gagnant, maxScore))
                    scores = {}
                    tour = 0
                    total = 0
                else:
                    datas = quizz()
                    reponse = datas['reponse'].lower()
                    choix = datas['choix']
                    question = datas['question']
                    pas_reponse = datas['pas_reponse']
                    serv.privmsg(canal, "Question : {0}".format(question.format('utf8')))
                    serv.privmsg(canal, "Choix: {0}".format(', '.join(choix).format('utf8')))
            else:
                for mot in pas_reponse:
                    if mot.lower() in message and not (personne in a_repondu):
                        serv.privmsg(canal, "WRONG, {0}".format(personne))
                        a_repondu.append(personne)

        if not is_l_heure_de_manger() and should_ban(message):
            serv.privmsg(canal, "PUTAIN ON A DIT NON")

        if "di" in message :
            splt = message.split('di')
            if len(splt) > 1 :
                reponse = splt[1]
                if reponse[0:1] == "s " :
                    reponse = reponse[2:]
                
                serv.privmsg(canal, reponse)

            # REDDIT // A COMPLETER
        if isCommande(message):
            serv.privmsg("Titch", "{0} : {1}".format(personne, message))
            args = message[1:].split(" ")
            originalArgs = originalMessage[1:].split(" ")
            cmd = args[0]
            if cmd == "$$" and last_args and last_cmd:
                args = last_args
                cmd = last_cmd
            if cmd == "$" and last_cmd:
                cmd = last_cmd

            if len(args) > 1 and args[1] == "!":
                args = last_args

            last_args = args
            last_cmd = cmd

            cmds = [
                'help', 'bdsm', 'haddock', 'useless', 'quizz', 'ecole', 'ffs', 'thanos', 'chuck', 'roll', 'rateau', 'viieux',               
                'kohlanta', 'new', 'del', 'get', 'debat', 'pipo', 'np', 'commit', 'zertyu', 'getsub', 'reddit', "gratuit", "pacho"
                ]

            most_likely = (cmd, 0)
            if cmd not in cmds:

                for f in cmds:
                    ratio = fuzz.ratio(cmd, f)
                    if ratio > 60 and ratio > most_likely[1]:
                        most_likely = (f, ratio)
                cmd = most_likely[0]
            
            if 'gratuit' in cmd and personne == "Titch" :
                canal2 = self.channels[canal]
                serv.privmsg(canal, "Et hop, on hl tout le monde !")
                result = ""
                for user in canal2.users() :
                    result = "{0}, {1}".format(result, user)
                serv.privmsg(canal, result)

            elif cmd == "help":
                if len(message.split(" ")) > 1:
                    if "reddit" in message.split(" ")[1]:
                        serv.privmsg(
                            canal,
                            ("Commandes : "
                             "{0}reddit <sub> ; "
                             "{0}addsub <sub> ; "
                             "{0}delsub <sub> ; "
                             "{0}getsub ."
                             "(getsub renvoie des infos sur "
                             "tous les subs enregistrés pour le chann) ").format(config.cmdCarac))
                else:
                    serv.privmsg(canal,
                                 ("Commandes disponibles :{0}").format(', '.join(cmds)))
            elif cmd == "pacho" : 
                difference = time.time() - pachoTime
                sent_message = "Wooow ! Ca fait deja " + convert_seconds_to_days(int(difference)) + " que Pacho n'est plus beauf"
                if len(args) > 2 and args[1] == "set" and int(args[2]):
                    pachoTime = time.time() - int(args[2])
                    sent_message = "Timer setté à " + args[2]

                if len(args) > 1 and args[1] == "reset" :
                    pachoTime = time.time()
                    sent_message = "Et dire que ca faisait seulement " + convert_seconds_to_days(int(difference)) + " que Pacho n'avait pas fait d'allusions"
                serv.privmsg(canal, sent_message)
                

            elif cmd == "haddock":
                serv.privmsg(canal, haddock())
            elif cmd == "bdsm":
                liste = self.channels[canal].users()
                chosen = liste[random.randint(0, len(liste) - 1)]
                c = 0
                while personne in chosen and c < 10:
                    chosen = liste[random.randint(0, len(liste) - 1)]
                    c += 1
                if chosen[0] in ["~", "&", "@", "%", "+"]:
                    chosen = chosen[1:]
                serv.privmsg(canal, bdsm(personne, chosen))

            elif cmd == "quizz":

                if len(args) > 1:
                    if int(args[1]):
                        total = int(args[1])
                    else:
                        total = 10
                else:
                    total = 10
                serv.privmsg(
                    canal, "{0} a commencé un quizz ! Jouez ! {1} questions ! ".format(personne, total))
                datas = quizz()
                reponse = datas['reponse'].lower()
                choix = datas['choix']
                question = datas['question']
                pas_reponse = datas['pas_reponse']
                serv.privmsg(canal, "Question : {0}".format(question.format('utf8')))
                serv.privmsg(canal, "Choix: {0}".format(', '.join(choix).format('utf8')))
            elif cmd == "useless":
                serv.privmsg(canal, useless())
            elif cmd == "ecole":
                try:

                    if len(args) > 1:
                        serv.privmsg(canal, "Oui, vous êtes bien à l'{}".format(
                            ensiee(''.join(args[1:]))))
                    else:
                        serv.privmsg(canal, "Oui, vous êtes bien à l'{}".format(ensiee()))
                except:
                    pass

            elif cmd == "ffs":
                serv.privmsg(
                    canal, "Nom de Dieu de putain de bordel de merde de saloperie de connard d'enculé de ta mère")
            elif cmd == "chuck":
                try:
                    parser = HTMLParser()
                    r = requests.get("http://www.chucknorrisfacts.fr/api/get?data=tri:alea;nb:1")
                    rep = r.json()[0]['fact']
                    rep = parser.unescape(rep)
                    serv.privmsg(canal, rep.encode('utf8'))
                except Exception:
                    serv.privmsg(canal, "erreur :(")
            elif cmd == "thanos" and personne == "Titch":
                liste = self.channels[canal].users()
                random.shuffle(liste)
                serv.privmsg(canal, "snap ! ")
                cleanlist = []
                for f in liste:
                    if f[0] in ["~", "&", "@", "%", "+"] and config.nick not in f:
                        cleanlist.append(no_hl(f))
                    elif config.nick not in f:
                        cleanlist.append(no_hl(f))
                live = cleanlist[:len(liste)//2]
                dead = cleanlist[len(liste)//2 + 1:]
                pp = dead[random.randint(0, len(dead) - 1)]
                ts = live[random.randint(0, len(live) - 1)]
                serv.nick('{0}_'.format(pp))
                serv.privmsg(canal, "I don't feel so good mr {0}".format(ts))
                serv.nick(config.nick)
                live_ = []
                dead_ = []
                for f in live:
                    live_.append(f)
                for f in dead:
                    dead_.append(f)
                vivants = "Vivants : {0}".format(", ".join(live_))
                morts = "Morts : {0}".format(", ".join(dead_))
                for msg in split_message(vivants) :
                    serv.privmsg(canal, msg)
                    time.sleep(0.2)
                for msg in split_message(morts) :
                    serv.privmsg(canal, msg)
                    time.sleep(0.2)
                #serv.mode(canal, "+" + len(live)*'v' + " "+" ".join(live))
                #serv.mode(canal, "+m")

            elif cmd == "roll" and len(split) > 1:
                content = split[1]
                if len(content.split('d')) == 2:
                    nbrDe = content.split('d')[0]
                    valDe = content.split('d')[1]
                    print(content, nbrDe, valDe)
                    res = ""
                    try:
                        for f in range(int(nbrDe)):
                            res = res + " {} ".format(random.randint(1, int(valDe)))
                        serv.privmsg(canal, res)
                    except:
                        pass

            elif cmd == "rateau":
                serv.privmsg(canal, "{0} : {1}".format(personne, rateau.getRateau()))

            elif cmd == "viieux":
                serv.privmsg(canal, viieux.get_viieux())

            elif cmd == "kohlanta":
                if (len(args) > 1):
                    serv.privmsg(canal, kohlanta.kohlanta(args[1], canal))

            elif cmd == "new":
                if len(originalArgs) > 1:
                    if args[1] in personnalizedCmd.keys():
                        serv.privmsg(canal, 'commande deja existante')
                    else:
                        newCmd = {}
                        newCmd['result'] = ' '.join(originalArgs[2:])
                        newCmd['author'] = personne
                        newCmd['channel'] = canal
                        personnalizedCmd[args[1]] = newCmd
                        serv.privmsg(canal, 'commande ajoutée : ${0}, par {1}, pour le chann {2}'.format(
                            args[1], personne, canal))
            elif cmd == "del":
                if len(args) > 1:
                    if args[1] in personnalizedCmd.keys():
                        if personne == personnalizedCmd[args[1]]['author']:
                            del personnalizedCmd[args[1]]
                            serv.privmsg(canal, 'done')
                        else:
                            serv.privmsg(canal, "vous n'etes pas l'auteur de cette commande !")
            elif cmd == "get":
                res = []
                for f in personnalizedCmd.keys():
                    if personnalizedCmd[f]["channel"] == canal:
                        res.append(f)
                serv.privmsg(canal, 'commandes pour {0} : {1}'.format(canal, ", ".join(res)))

            elif cmd == "debat":
                serv.privmsg(canal, philotron.genererSujet())
            elif cmd == "pipo":
                serv.privmsg(canal, pipotron.pipo())

            elif cmd == "np":
                res = nordpresse.nordpresse()
                serv.privmsg(canal, res)
            elif cmd == "commit":
                res = commit.commit()
                serv.privmsg(canal, res)
            elif cmd == "zertyu":
                if len(args) > 2:
                    if args[1] == "code":
                        serv.privmsg(canal, codage.encode(" ".join(args[2:])))
                    elif args[1] == "decode":
                        serv.privmsg(canal, codage.decode(" ".join(args[2:])))

            elif cmd == "reddit":
                full = False
                if len(args) > 1:
                    sub = args[1]
                else:
                    sub = "jokes"
                if len(args) > 2:
                    if "full" in args[2]:
                        full = True
                if time.time() - self.reddit_temps > 3:
                    self.reddit_temps = time.time()

                    try:
                        tmp = red.joke(sub, full)
                    except:
                        tmp = red.joke()
                    try:

                        for f in tmp:
                            serv.privmsg(canal, f)
                            time.sleep(0.5)
                        time.sleep(1)

                    except:
                        serv.privmsg(canal, "oups, c'est cassé...")
                else:
                    serv.privmsg(canal, personne + ": Merci de patienter :)")
            elif cmd in personnalizedCmd.keys():
                if personnalizedCmd[cmd]['channel'] == canal:
                    serv.privmsg(canal, personnalizedCmd[cmd]['result'])


if __name__ == "__main__":
    Boooob().start()