import sys
import re
from collections import defaultdict
import os
import glob

def find_last_log(tsdir):
    files = glob.glob(os.path.join(tsdir, 'logs/*_1.log'))
    return max(files, key=os.path.getmtime)

def get_online_users(fname="", tsdir=""):
    if tsdir and not fname:
        fname = find_last_log(tsdir)
    with open(fname) as log:
        users = set()

        NAME_RE = r" '(.+?)'\(id:(\d+)\)"

        id_name_mapping = defaultdict(list)

        for line in log:
            if 'disconnected' in line:
                match = re.search("disconnected" + NAME_RE, line)
                id = match.groups()[1]

                if id in id_name_mapping:
                    for name in id_name_mapping[id]:
                        users -= {name}
            elif 'connected' in line:
                match = re.search("connected" + NAME_RE, line)
                name, id = match.groups()
                users |= {name}
                id_name_mapping[id].append(name)

        return sorted(list(users))
