import os, json
from minecraft_manager.models import Player
from django.conf import settings

stats_dir = os.path.join(settings.MINECRAFT_BASE_DIR, getattr(settings, "WORLD", "world"), "stats")

def get_score(data):
    return data['score']


def get_stats():
    stats = {}
    for filename in os.listdir(stats_dir):
        with open(stats_dir + "/" + filename) as json_file:
            j = json.load(json_file)['stats']
            uuid = filename.replace(".json", "")
            stats[uuid] = j
    return stats


def get_names(stats=None, sort=False):
    names = []
    if not stats:
        stats = get_stats()
    for uuid in stats:
        for base in stats[uuid]:
            for stat in stats[uuid][base]:
                name = "{}.{}".format(base, stat)
                if name not in names:
                    names.append(name)
    if sort:
        names = sorted(names)
    return names


def top_ten_stat(stat):
    stats = get_stats()
    top_ten = []
    parts = stat.split('.')
    for s in stats:
        if parts[0] in stats[s]:
            top_ten.append({'uuid': s, 'score': stats[s][parts[0]][parts[1]] if parts[1] in stats[s][parts[0]] else 0})
    top_ten = sorted(top_ten, key=get_score, reverse=True)[:10]
    for idx, tt in enumerate(top_ten):
        uuid = tt['uuid']
        try:
            top_ten[idx]['username'] = Player.objects.get(uuid=uuid).username
        except:
            top_ten[idx]['username'] = uuid
    return top_ten


def top_ten_player(uuid):
    stats = get_stats()
    names = get_names(stats)
    top_ten_list = {}
    for name in names:
        top_ten_list[name] = []
        parts = name.split('.')
        for stat in stats:
            bases = stats[stat]
            if parts[0] in bases:
                top_ten_list[name].append({'uuid': stat, 'score': bases[parts[0]][parts[1]] if parts[1] in bases[parts[0]] else 0})
        top_ten_list[name] = sorted(top_ten_list[name], key=get_score, reverse=True)
    top_ten = []
    for tt in top_ten_list:
        idx = 0
        for ttl in top_ten_list[tt]:
            if idx > 10:
                break
            if ttl['uuid'] == uuid:
                ttl['rank'] = idx+1
                ttl['stat'] = tt
                top_ten.append(ttl)
                break
            idx += 1
    return top_ten


def one_single(uuid, stat):
    stats = get_stats()
    if uuid in stats:
        return [{'uuid': uuid, 'stat': stat, 'score': stats[uuid][stat]}]
    return 0

