class KnownUsers:
    """
    This deals with both the dedicated server log AND the xml "user" file, as related to the known users.

    TODO: refactor this to have a distinct class for the dedicatedLog and the users.xml
    """

    def __init__(self, existing_users_filename):
        """Setup init variables parsing the existing user xml."""

        import xml.etree.ElementTree as ET

        try:
            known_users = ET.parse(existing_users_filename)
            self.knownUsersRoot = known_users.getroot()
            self.existingUsers = self.knownUsersRoot.findall("./user")
        except IOError:
            print('warning: no known users file: %s' % existing_users_filename)
            return

    def getTodayLogins(self, serverLogLines):

        import re

        userLogins = {}
        user = {}
        # run through the server log lines, find this guy based on his displayname
        for line in serverLogLines:
            # 2015-11-10 19:51:36.696 - Thread:   8 ->  OnConnectedClient mccorkle attempt
            if ('OnConnectedClient' in line):  # should catch only the FIRST login
                matchObject = re.match(r'(\d+-\d+-\d+)\s(\d+:\d+:\d+\.\d+).*OnConnectedClient\s(.*?)\sattempt', line)
                if (matchObject):
                    user['loginTime'] = matchObject.group(1) + " " + matchObject.group(2)
                    user['loginName'] = matchObject.group(3)
                    # print ("LOGIN: %s %s" % (user['loginName'], user['loginTime']))
            if ('User left' in line and user['loginName'] in line):  # and will overwrite until the last logout time
                matchObject = re.match(r'(\d+-\d+-\d+)\s(\d+:\d+:\d+\.\d+)\s', line)
                user['logoutTime'] = matchObject.group(1) + " " + matchObject.group(2)

        # if user['logoutTime']:
        #     print ("LOGOUT: %s %s" % (user['loginName'], user['logoutTime']))

        userLogins[user['loginName']] = user
        del user

        return userLogins

    def getExistingUsers(self):
        return self.existingUsers
        # return self.knownUsersRoot.findall("./user")

    def getNewUsers(self, playersDict):
        newUsers = {}
        for player in playersDict:
            # print ("checking player %s to see if he is in users" % player)
            foundKnownUser = 0
            for knownUser in self.knownUsersRoot.findall("./user"):
                if knownUser.get('inGameID') == playersDict[player]["inGameID"]:
                    foundKnownUser = 1
                    # childBranch = knownUser

            if foundKnownUser == 0:
                # print ("** NEW USER")
                newUsers[playersDict[player]["inGameID"]] = playersDict[player]

        return newUsers

    def updateUsersFile(self, playersDict, existingUsersFilename):

        import xml.etree.ElementTree as ET

        for player in playersDict:
            # print ("checking player %s to see if he is in users" % player)
            foundKnownUser = 0
            for knownUser in self.knownUsersRoot.findall("./user"):
                if knownUser.get('inGameID') == playersDict[player]["inGameID"]:
                    foundKnownUser = 1
            if foundKnownUser == 0:

                # print ("** NEW USER")

                # add all the new users to the knownUsers file, so next time we read, they aren't new
                child = ET.SubElement(self.knownUsersRoot, "user")
                child.set("username", playersDict[player]["username"])
                child.set("inGameID", playersDict[player]["inGameID"])
                child.set("steamID", playersDict[player]["steamID"])
                child.set("playerToolbarSlotCount", playersDict[player]["playerToolbarSlotCount"])
                # firstSeen is a combination of loginTime || users.xml where we stored the first time we saw this user
                # we don't have those inside of parsing users, so need to parse and class log file first
                # child.set("firstSeen", today)
                # child.set("loginTime", loginTime)
                # child.set("logoutTime", logoutTime)

        testOut = ET.ElementTree(self.knownUsersRoot)
        testOut.write(existingUsersFilename, encoding='utf-8', xml_declaration=True)
