from __future__ import unicode_literals
# -*- coding: utf-8 -*-
import os, sys, time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ecran_connexion import Ui_ecranConnexion
from ecran_chat import Ui_chat
from serveur import Serveur, ServeurVoc
#from clientvoc import ClientVoc
from client import Client
from lancer import jet
import threading

class EcranConnexion(QGroupBox):
    def __init__(self, parent=None):
        super (EcranConnexion, self).__init__(parent)
        self.createWidgets()
        self.client_connecte = False
        self.serveur_connecte = False

    def msg(self, txt):
        self.ui.txt_msg.setText(QString.fromUtf8(txt))

    def creerServeur(self):
        self.pseudo = self.ui.in_pseudo.text()
        self.port = self.ui.in_port.text()        
        if len(self.pseudo) == 0 or len(self.port) == 0:
            self.msg("Parametres incorrects")
        else:    
            self.ui.in_ip.setText(QString.fromUtf8("localhost"))
            self.s = Serveur(int(self.ui.in_port.text()))
            self.serveur_connecte, txt = self.s.creer()
            self.msg(txt)
            if self.serveur_connecte:
               self.seConnecter()

    def seConnecter(self):
        self.pseudo = self.ui.in_pseudo.text()
        self.port = self.ui.in_port.text()
        self.ip = self.ui.in_ip.text()
        if len(self.pseudo) == 0 or len(self.ip) == 0 or len(self.port) == 0:
            self.msg("Parametres incorrects")
        else:    
            self.msg("En attente du serveur...")    
            self.client_connecte = True
            self.c = Client()
            txt = self.c.creer(self.pseudo, self.ip)
            self.msg(txt)
            time.sleep(0.2)
            self.close()
                    
    def fermer(self):
        print("fermerture")
        if self.serveur_connecte:
           self.s.stop()
           self.serveur_connecte = False
        if self.client_connecte:
           self.c.stop()
           self.client_connecte = False
        self.close()
        
    
    def createWidgets(self):
        self.ui = Ui_ecranConnexion()
        self.ui.setupUi(self)
        self.connect(self.ui.fermer, SIGNAL("clicked()"), self.fermer)
        self.connect(self.ui.creerServeur, SIGNAL("clicked()"), self.creerServeur)
        self.connect(self.ui.seConnecter, SIGNAL("clicked()"), self.seConnecter)

class EcranChat(QGroupBox):
    def __init__(self, connexion, parent=None):
        super (EcranChat, self).__init__(parent)
        self.co = connexion
        self.c = connexion.c
        self.connecte = True
        self.estServeurVoc = False
        self.estClientVoc = False
        self.doc = QTextDocument() 
        self.createWidgets()
        
    def msg(self, txt):
        self.ui.txt_msg.setText(QString.fromUtf8(txt))
        
    def afficheReception(self):
        """thread d'affichage du chat et des infos"""
        while self.connecte:
            emetteur = nature = msg = ""
            if self.c.R.recuChat != ():
                emetteur, msg = self.c.R.recuChat
                if emetteur == self.c.R.idClient:
                    txt = "<b>{} </b>: {}".format(self.co.pseudo, msg)
                else:
                    txt = "{} : {}".format(self.c.R.autresCo[emetteur], msg)
                txt2 = QString.fromUtf8(txt)
                self.ui.listAffichage.addItem(QString.fromUtf8(txt2))
                self.c.R.recuChat = ()
            if self.c.R.recuInfo != ():
                nature, msg = self.c.R.recuInfo
                self.ui.listEvenement.addItem("{} - {}".format(nature, msg))
                self.c.R.recuInfo = ()
                if nature == "vf":
                    #fermeture du chat vocal
                    self.quitterChatVoc()
            time.sleep(0.001)    
               
    def closeEvent(self, event):
        self.co.client_connecte = False
        self.c.stop()
        if self.co.serveur_connecte:
            self.co.s.stop()
            self.co.serveur_connecte = False
        if self.estClientVoc:
            self.cVoc.stop()
        if self.estServeurVoc:
            self.sVoc.stop()
        self.close()
        
    def envoiMsg(self):
        msg = self.ui.inChat.text()
        self.c.envoi("m ", "tc", msg)
        self.ui.inChat.clear()

    def lancerD(self, expr):
        res, detail = jet(expr)
        if res > 0:
            txt = "{}: {}   ({})  [{}]".format(self.co.pseudo, res, detail, expr)
            self.c.envoi("id", "tc", txt)
        else:
            self.c.R.info("id","mmmhh, pas bon le jet")
        return res
             
    def d20(self):
        self.lancerD("1d20")
        
    def d100(self):
        self.lancerD("1d100")

    def autreJet(self):
        expr = str(self.ui.inJetDes.text())
        retour = self.lancerD(expr)
        self.ui.inJetDes.clear()

    def envoyerfichier(self):
        fichier = QFileDialog.getOpenFileName(
                       self, 
                       "Selectionnez un fichier a envoyer", 
                       "c:\\", 
                       "")
        self.c.envoiFichier(str(fichier))

    def repReception(self):
        dossier = QFileDialog.getExistingDirectory(self)
        self.c.R.repReceptionFichiers = dossier
        self.majStatut()
        
    def majStatut(self):
        if self.co.serveur_connecte:
            txt = "Serveur : Oui"
        else:
            txt = "Serveur : Non"
        txt += " \ Votre IP : {}".format(self.c.ipClient)
        txt += " \ Pseudo : {}".format(self.co.pseudo)
        if self.estServeurVoc:
            txt += " \ Serveur vocal"
            
        if self.estClientVoc:
            txt += " \ connecte au chat vocal"
            
        self.msg(txt)
        self.ui.txt_repReception.setText(QString.fromUtf8("Fichiers recus : '{}'".format(self.c.R.repReceptionFichiers)))
    
    def createWidgets(self):
        self.ui = Ui_chat()
        self.ui.setupUi(self)
        self.connect(self.ui.inChat, SIGNAL("returnPressed()"), self.envoiMsg)
        threading.Thread(None, self.afficheReception, None, (), {}).start()
        self.connect(self.ui.d20, SIGNAL("clicked()"), self.d20)
        self.connect(self.ui.d100, SIGNAL("clicked()"), self.d100)
        self.connect(self.ui.inJetDes, SIGNAL("returnPressed()"), self.autreJet)
        self.connect(self.ui.envoiFichier, SIGNAL("clicked()"), self.envoyerfichier) 
        self.connect(self.ui.repReceptionFichiers, SIGNAL("clicked()"), self.repReception)
        #self.connect(self.ui.chatVoc, SIGNAL("clicked()"), self.chatVoc)
        #self.connect(self.ui.creerServeurVoc, SIGNAL("clicked()"), self.creerServeurVoc)
        self.majStatut()
        
    def creerServeurVoc(self):
        if not self.estServeurVoc:
            self.sVoc = ServeurVoc(6660, 1024)
            txt = self.sVoc.creer()
            self.c.R.info("vs", txt)
            if self.sVoc.serveur_lance:
                self.c.envoi("vs","ac","{}".format(self.c.ipClient))
                self.estServeurVoc = True
                self.majStatut()
        else:
            self.fermerServeurVoc()
            

    def fermerServeurVoc(self):
        txt = self.sVoc.stop()
        self.c.R.info("vs", txt)
        if not self.sVoc.serveur_lance:
            self.c.envoi("vf","ac","")
            self.estServeurVoc = False
            self.majStatut()
        
    def chatVoc(self):
        if not self.estClientVoc:
             self.cVoc = ClientVoc()
             txt = self.cVoc.creer(self.co.pseudo, self.c.R.ipServeurVoc)
             if self.cVoc.connecte:
                 self.c.R.info("vi", txt)
                 self.c.envoi("vi","ac","")
                 self.estClientVoc = True
                 self.majStatut()
        else:
            self.quitterChatVoc()

    def quitterChatVoc(self):
        if self.estClientVoc:
            txt = self.cVoc.stop()
            self.c.R.info("vq", txt)
            self.c.envoi("vq","ac","")
            self.estClientVoc = False
            self.majStatut()            
             
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    connexion = EcranConnexion()
    connexion.show()
    r = app.exec_()
    if r == 0 and connexion.client_connecte:
        ecranChat = EcranChat(connexion)
        ecranChat.show()
        r = app.exec_()
        #connexion.s.stop()
        sys.exit(r)
        

    


    
    
    
