from postgres import Postgres
from django.shortcuts import render, get_object_or_404
from .models import Networks, Channels, Users

def networks(request):
    networks = Networks.objects.all()
    channels = Channels.objects.all()
    users = Users.objects.all()
    db = Postgres("postgres://pyRot:4h8q(.@localhost/pyRot")
    messages = db.all("SELECT channel_network, messages, actions, notices FROM messages")
    
    #foo = db.all("SELECT * FROM messages WHERE channel_network='GamerGalaxy'")
    #print(foo)
    
    networklist = {}
    for network in networks:
        #print(db.all("SELECT messages, actions, notices FROM messages WHERE channel_network='" + str(network) + "'"))
        networklist[network.name] = {'channels': 0, 'users': 0, 'messages': 0}
    for user in users:
        networklist[user.network.name]['users'] += 1
    print(channels)
    for channel in channels:
        networklist[channel.network.name]['channels'] += 1
    totalmessages = 0
    print(messages)
    
    for idx, record in enumerate(messages):
        print(record)
        totalmessages += record[1] + record[2] + record[3]
        networklist[record[0]]['messages'] += record[1] + record[2] + record[3]
    
    context = {
        'networks': networks,
        'channels': channels,
        'users': users,
        'messages': messages,
        'totalmessages': totalmessages,
        'networklist': networklist,
    }
    return render(request, 'stats/networks.html', context)

def network(request, network_name):
    network = get_object_or_404(Networks, name=network_name)
    context = {'network': network}
    return render(request, 'stats/network.html', context)
