class Server:

    def __init__(self, ipAddr, port):
        app = QtGui.QApplication(sys.argv)
        self.ipAddr = ipAddr
        self.port = port
        self.serverGUI = None
        self.serverUI = None
        self.connectionList = []
        self.threadingList = []
        self.createServerGUI()
        self.start()
        sys.exit(app.exec_())

    def createServerGUI(self):
        self.serverGUI = ServerGUI()
        self.serverGUI.show()
        self.serverUI = self.serverGUI.getUI()

    def start(self):
        print("START")
        self.s = socket.socket()
        self.s.bind((self.ipAddr,self.port))
        print("BINDED")
        self.s.listen(5)
        print("server started...")
        conHandler = self.acceptConneectionHandler(self.s)
        conHandler.start()
        self.serverUI.connect(self.acceptConneectionHandler,QtCore.SIGNAL("newConnection(QString)"),self.updateIncomingUser)
        self.threadingList.append(conHandler)


    def acceptConnection(self):
        while True:
            conn, addr = self.s.accept()
            print("CONNECTED WITH " + str(addr))
            self.username = conn.recv(1024)
            self.username = self.username.decode("utf-8")
            print("Username "  + self.username)
            self.updateIncomingUser()
            self.connectionList.append((conn,addr,self.username))
            print("Client connected ip : " + str(addr))
            c = ClientHandler(conn, addr,self.serverUI)

            self.threadingList.append(c)

    def updateIncomingUser(self,username, tauple):
        print(self.serverUI)
        print("user info  : " + str(tauple))
        self.connectionList.append(tauple)
        self.serverUI.OnlineList.addItem( QListWidgetItem(username) )
        self.serverGUI.getTabWidget().addTab(TabChat(username),username)

    class acceptConneectionHandler(QtCore.QThread):
        def __init__(self,socket,parent = None):
            super(Server.acceptConneectionHandler,self).__init__(parent)
            self.s = socket


        def run(self):
            while True:
                conn,addr = self.s.accept()

                print("CONNECTED WITH " + str(addr))
                username = conn.recv(1024)
                username = username.decode("utf-8")
                print("USERNAME : "******"newConnection(QString)"), username, (conn,addr,username))

                print("CONNECT IP : " + str(addr))
def main():
    
    myGUI = ServerGUI()
    myGUI.run()
 def createServerGUI(self):
     self.serverGUI = ServerGUI()
     self.serverGUI.show()
     self.serverUI = self.serverGUI.getUI()