#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

# pour des exemples d'utilisation de ce bot :
# https://bitbucket.org/Zopieux/pypeul/src/402ec37221a3/examples/simple_bot/main.py
# ou plus généralement : https://bitbucket.org/Zopieux/pypeul/src

import codecs
from pypeul import *
import sys
from algos import *
import Levenshtein
import random
from itertools import cycle

with codecs.open('words.txt', encoding='UTF-8') as file:
    WORDS = file.read().split('\n')

scores = {} # joueurs -> scores
bonjour = ['cc','slt','bonjour','o/','\o','bsr','bjr','salut']

class SimpleBot(IRC):
    def __init__(self):
        super(SimpleBot, self).__init__()
        self.players = {} # joueurs courants -> scores courants
        self.reset()
          
    def reset(self):
        self.start = 0
        self.play = False
        self.letters = ''
        self.player_cycle = None
        self.current = None
        self.test = False
        self.count = 10
        self.boolword = []
        self.mysterword = ''
        refresh_scores(scores, self.players)
        self.players = {}
    
    def next_player(self):
        self.current = next(self.player_cycle)
    
    def on_ready(self):
        self.join("##dieses-pendu")
    
    def on_self_join(self,target):
        self.message(target, "Salut les pd")
    
    def on_channel_message(self, umask, target, msg):
        msg = msg.lower()
        mots = msg.split()
        if msg == "!help":
            self.message(target, help_())
        
        if msg == "!play" and not self.play and self.start == 0:
            self.mysteryword = random.choice(WORDS)
            self.play = True
            self.boolword = [False]*len(self.mysteryword)
            if str(umask) not in scores:
                scores[str(umask)] = 0
            if str(umask) not in self.players:
                self.players[str(umask)] = 0
                self.message(target, "%s veut jouer, qui d'autre ?"  %umask)
        
        if (msg == "!start" or 'personne' in msg ) and self.play \
        and str(umask) in self.players:
            self.start += 1
            self.play = False
            self.message(target, "The game's just started !")
            keys = list(self.players.keys())
            random.shuffle(keys)
            self.player_cycle = cycle(keys)
            self.next_player()
        
        if msg == "!scores":
            self.message(target, print_scores(scores))
        
        if any(Levenshtein.distance(i, "moi") <= 1 for i in mots) and self.play\
        and self.start == 0 and str(umask) not in self.players:
            self.message(target, "OK %s, qui d'autre ?" %umask)
            if str(umask) not in scores:
                scores[str(umask)] = 0
            if str(umask) not in self.players:
                self.players[str(umask)] = 0
        
        if (self.count > 0 or any(x == False for x in self.boolword)) and self.start == 1:
            self.message(target, printword(self.mysteryword, self.boolword))
            self.message(target, "À toi %s" %self.current)
            self.start += 1
        
        if self.count > 0 and self.start == 2 and str(umask) == self.current:
            if len(msg) == 1:
                (self.test, n_occur, self.boolword) = \
                                checkin(self.mysteryword, msg, self.boolword)

                if self.test and msg not in self.letters and not won(self.boolword):
                    self.letters += msg
                    self.message(target, 'Bien joué %s ! '\
                                 'Tu gagnes %d points et il vous reste '\
                                 '%d coups (%s)' %(self.current, 2 + n_occur, self.count, self.letters))
                    self.players[self.current] += 2 + n_occur
                    self.next_player()
                    self.message(target, printword(self.mysteryword, \
                                                   self.boolword) + '  À toi %s' %self.current)

                elif self.test and msg not in self.letters and won(self.boolword):
                    self.message(target, 'Bingo il en manquait qu\'une %s! Tu gagnes %d points '\
                                 'et la partie est finie, thx bye !' %(self.current, 2 + n_occur))
                    self.message(target, 'Le mot était bien : %s' %self.mysteryword.upper())
                    self.players[self.current] += 2 + n_occur
                    
                else:
                    if msg not in self.letters: self.letters += msg
                    self.players[self.current], self.count = \
                                self.players[self.current] - 2, self.count - 1
                    self.message(target, 'Non dsl %s, tu perds 2 points '\
                                 'et il vous reste %d coups (%s)' %(umask, self.count, self.letters))
                    self.next_player()
                    self.message(target, printword(self.mysteryword, self.boolword) + '  À toi %s' %self.current)
        
        if msg.endswith('!') and self.start == 2 and str(umask) in self.players and len(mots) == 2:
            (test, n_occur, self.boolword) = checkin(self.mysteryword, mots[0], self.boolword)
            n_missed = nb_missed(self.boolword)
            if self.mysteryword in msg:
                nb_pts_won = 5 + 2*(len(self.mysteryword) - n_missed)
                self.message(target, 'Tranquille %s ! Tu gagnes %d points ! '\
                             'Le mot était bien %s. '
                             ' Thx bye !!' %(umask, nb_pts_won, self.mysteryword.upper()))
                self.players[str(umask)] += nb_pts_won
                self.reset()
            
            else:
                nb_pts_lost = 4 + 2*(len(self.mysteryword) - n_missed)
                self.count -= 1
                self.message(target, 'ET NON BIM %s ! Tu viens de perdre %d points, '\
                             'noraj buddy. Coups restants : %d' %(umask, nb_pts_lost, self.count))
                self.players[str(umask)] -= nb_pts_lost
                
                if self.current == str(umask) and str(umask) in self.players:
                    self.next_player()
                    self.message(target, 'À toi %s' %self.current)
                elif self.current != str(umask) and str(umask) in self.players:
                    self.message(target, 'À toi %s' %self.current)
        
        if mots[0] in bonjour and 'cobblestone' in msg:
            self.message(target, '%s, %s' %(mots[0], umask))
        if len(mots) >= 2 and mots[1] in bonjour and 'cobblestone' in msg:
            self.message(target, '%s %s' %(mots[1], umask))
        
        if self.count == 0 and self.start == 2:
            self.message(target, 'Non dsl %s et en plus la partie est foirée. '\
                         'Le mot était %s ! De plus, la partie est terminée. '\
                         'Thx bye !' %(umask, self.mysteryword.upper()))
            self.reset()
        
        if won(self.boolword) and self.start == 2:
            self.message(target, 'BIP BIP ! Partie terminée, thx bye !')
            self.reset()

if __name__ == '__main__':
    # Enable debug-level logging
    import logging
    logging.basicConfig(level=logging.DEBUG)
    
    # Instanciate our SimpleBot class and let it run
    bot = SimpleBot()
    bot.connect('irc.freenode.net', 6667)
    bot.ident('pendu')
    
    bot.run()
