# -*- 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 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



global cmdCarac
cmdCarac = "$"

personnalizedCmd = {}
reponse = None 
pas_reponse = []
a_repondu = []

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

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



class Boooob(ircbot.SingleServerIRCBot):
    def __init__(self):
        ircbot.SingleServerIRCBot.__init__(self, [("irc.iiens.net", 6667)], "nardco", "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("#gynecoloc")
        serv.privmsg("NickServ", "IDENTIFY MotDePasse")  # 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_privmsg(self, serv, ev):  # msg privé
        personne = ev.source()
        canal = ""

        if "tichadou" in personne:
            msg = ev.arguments()[0]
            msg = msg.split(" ")
            a = 0
            for f in msg:
                a = a + 1
                if f[0] == "#":
                    canal = f
                    msg.pop(a - 1)
                    break
            msg = " ".join(msg)
            try:
                serv.privmsg(canal, msg)
            except:
                serv.privmsg("#nardco", "probleeeeme")

    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):
        serv.join("#nardco")
        print("kick")
        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 cmdCarac
        global personnalizedCmd
        global last_args
        global last_cmd
        global reponse
        global a_repondu
        global pas_reponse

        canal = ev.target()

        personne = ev.source()
        personne = couper(personne)
        message = ev.arguments()[0]
        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 'nardco' 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 "Titch" in personne and "goto" in message and "nardco" in message:
            f = 0
            for f in range(len(message) - 4):
                if message[f:f + 4] == "goto":
                    serv.join("#" + message[f + 5:])
                    break
        if "Titch" in personne and "leave" in message and "nardco" in message:
            serv.part(canal)

        if reponse is not None and 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 = []

        if reponse is not None and message in pas_reponse and personne not 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")


            # REDDIT // A COMPLETER
        if isCommande(message):
            args = message[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', 'sub', 'delsub', 'addsub', 'reddit']

            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 'spoil' in args or 'spoil' in cmd : 
                serv.privmsg(canal, "Le risque de spoil est present. je fais pas ça.")
            
            

            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(cmdCarac))
                else:
                    serv.privmsg(canal,
                                 ("Commandes disponibles :{0}").format(', '.join(cmds)))
                
            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" : 
                datas = quizz()
                reponse = datas['reponse'].lower()
                choix = datas['choix']
                question= datas['question']
                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)
                    print(rep)
                    serv.privmsg(canal, rep.encode('utf8'))
                except Exception  :
                    print str(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 'nardco' not in f :
                        cleanlist.append(no_hl(f))
                    elif 'nardco' 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('nardco')
                live_ = []
                dead_ = []
                for f in live :
                    live_.append(no_hl(f))
                for f in dead :
                    dead_.append(no_hl(f))
                serv.privmsg(canal, "Vivants : {0}".format(", ".join(live_) ))
                serv.privmsg(canal, "Morts : {0}".format(", ".join(dead_) ))
                #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(args)>1 :
                    if args[1] in personnalizedCmd.keys() :
                        serv.privmsg(canal, 'commande deja existante')
                    else :
                        newCmd = {}
                        newCmd['result'] = ' '.join(args[2:])
                        newCmd['author'] = personne
                        newCmd['channel'] = canal
                        personnalizedCmd[args[1]] = newCmd
                        print personnalizedCmd
                        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 == "getsub":
                res = red.get_new(self.fichier_reddit, canal)
                for f in res:
                    serv.privmsg(canal, f)

            elif cmd == "sub":
                bd = open(self.fichier_reddit, "r")
                for f in bd:
                    try:
                        if canal == f.split("|")[0]:
                            serv.privmsg(canal, "Liste des subs pour " + canal + " : " + f.split("|")[1])
                    except:
                        pass

            elif cmd == "delsub":
                sub = message.split(" ")[1]
                bd = open(self.fichier_reddit, "r")
                rem = 0
                tmp = []
                for f in bd:
                    tmp.append(f)
                    try:
                        if sub in f.split("|")[1] and canal == f.split("|")[0]:
                            rem = 1
                    except:
                        pass
                bd.close()
                if rem == 1:
                    bd = open(self.fichier_reddit, "w")
                    for f in tmp:
                        if canal == f.split("|")[0]:
                            h = f.split("|")[1]
                            h = h.split(",")
                            h.remove(sub)
                            g = f.split("|")[0] + "|" + ",".join(h)
                        else:
                            g = f
                        bd.write(g)
                    serv.privmsg(canal, "sub : " + sub + " enlevé de la bd pour " + canal)
                else:
                    serv.privmsg(canal, "Erreur, le sub n'est pas dans la bd")

            elif cmd == "addsub":
                sub = message.split(" ")[1]
                bd = open(self.fichier_reddit, "r")
                add = 1
                tmp = []
                for f in bd:
                    tmp.append(f)  # On ajoute la ligne -> tmpt est une image de la bd
                    try:
                        if sub in f.split("|")[1] and canal == f.split("|")[0]:
                            add = 0
                    except:
                        pass
                bd.close()
                if add == 1:
                    canalok = 0
                    bd = open(self.fichier_reddit, "w")
                    for f in tmp:
                        if canal == f.split("|")[0]:
                            g = f + sub + ","
                            canalok = 1
                        else:
                            g = f
                        bd.write(g)
                    if canalok == 0:
                        bd.write("\n" + canal + "|" + sub + ",")
                    bd.close()
                    serv.privmsg(canal, "Subreddit : " + sub + " ajouté a la bd pour " + canal)
                else:
                    serv.privmsg(canal, "Subreddit deja dans la bd...")

            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()