import os
import json
from datetime import datetime, timedelta
from django.conf import settings
from minecraft_manager.models import Application, Player, Ticket, Note, IP
from django.contrib.auth.models import User


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()
        },
        'note': Note.objects.count(),
        'ip': IP.objects.count()
    }

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

    # Percentage
    data['percentage'] = {
        'accepted': round((data['total']['application']['accepted'] /
                    data['total']['application']['all'] if data['total']['application']['all'] != 0 else 1) * 100, 2),
        'banned': round((data['total']['player']['banned'] /
                  data['total']['player']['all'] if data['total']['player']['all'] != 0 else 1) * 100, 2),
        'applied': round((data['total']['application']['all'] /
                   data['total']['player']['all'] if data['total']['player']['all'] != 0 else 1) * 100, 2)
    }

    # Unique logins
    now = datetime.now()
    day = now - timedelta(days=1)
    week = now - timedelta(weeks=1)
    month = now - timedelta(weeks=4)
    data['unique'] = {
        'day': Player.objects.filter(last_seen__range=[day, now]).count(),
        'week': Player.objects.filter(last_seen__range=[week, now]).count(),
        'month': Player.objects.filter(last_seen__range=[month, now]).count()
    }

    # Admin
    data['resolved'] = []
    for user in User.objects.all().order_by('username'):
        data['resolved'].append({
            'active': user.is_active,
            'username': user.username,
            'tickets': Ticket.objects.filter(staff=user).count()
        })

    return data
