import os
import json
from django.conf import settings
from minecraft_manager.models import Application, Player, Ticket, Warning, IP


def overview_data():
    data = {}

    # Setup
    with open(os.path.join(settings.MINECRAFT_BASE_DIR, 'banned-players.json'), encoding='utf-8') as f:
        bans = json.load(f)


    # Totals
    data['total'] = {
        'application': {
            'accepted': Application.objects.filter(accepted=True).count(),
            'denied': Application.objects.filter(accepted=False).count(),
            'all': Application.objects.count()
        },
        'player': {
            'banned': len(bans),
            'unbanned': Player.objects.count() - len(bans),
            'all': Player.objects.count()
        },
        'ticket': {
            'claimed': Ticket.objects.filter(staff__isnull=False).count(),
            'unclaimed': Ticket.objects.filter(staff__isnull=True).count(),
            'resolved': Ticket.objects.filter(resolved=True).count(),
            'unresolved': Ticket.objects.filter(resolved=False).count(),
            'all': Ticket.objects.count()
        },
        'warning': Warning.objects.count(),
        'ip': IP.objects.count()
    }

    # Averages
    data['average'] = {
        'age': sum([application.age for application in Application.objects.all()]) /
               data['total']['application']['all'] if data['total']['application']['all'] != 0 else 1
    }

    # Ratios
    data['ratio'] = {
        'accepted': data['total']['application']['accepted'] /
                    data['total']['application']['denied'] if data['total']['application']['denied'] != 0 else 1,
        'banned': data['total']['player']['banned'] /
                  data['total']['player']['unbanned'] if data['total']['player']['unbanned'] != 0 else 1
    }

    return data
