from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.forms import inlineformset_factory
from django.contrib.auth.decorators import login_required, permission_required
from website.settings import APPLICATION_NAME
from rotbot.models import Network, Host, Channel, User, Message, Action, Notice, Join, Kick, Owner
from rotbot.forms import NetworkForm, HostForm, OwnerForm
from .common import default_keywords, shorten_number, total_messages

def networks(request):
    networks = Network.objects.all()
    hosts = Host.objects.all()
    channels = Channel.objects.all()
    users = User.objects.all()
    messages = Message.objects.all()
    actions = Action.objects.all()
    notices = Notice.objects.all()
    joins = Join.objects.all()
    kicks = Kick.objects.all()

    context = {
        'title': 'RotBot',
        'icon': 'robot',
        'description': 'Index of RotBot, the IRC robot.',
        'keywords': default_keywords('index'),
        'networks': networks,
        'total_networks': shorten_number(networks.count()),
        'total_hosts': shorten_number(hosts.count()),
        'total_chanels': shorten_number(channels.count()),
        'total_users': shorten_number(users.count()),
        'total_messages': shorten_number(total_messages(messages)),
        'total_actions': shorten_number(total_messages(actions)),
        'total_notices': shorten_number(total_messages(notices)),
        'total_joins': shorten_number(joins.count()),
        'total_kicks': shorten_number(kicks.count()),
    }
    return render(request, 'rotbot/networks.html', context)


def network(request, network_slug):
    network = get_object_or_404(Network, slug=network_slug)
    hosts = Host.objects.filter(network=network)
    channels = Channel.objects.filter(network=network)
    users = User.objects.filter(network=network)
    messages = Message.objects.filter(network=network)
    actions = Action.objects.filter(network=network)
    notices = Notice.objects.filter(network=network)
    joins = Join.objects.all()
    kicks = Kick.objects.all()

    for host in hosts:
        host.connection_fails = host.connection_attempts - host.connection_succeeds

    context = {
        'parent_title': 'Networks',
        'parent_url': reverse('rotbot:networks'),
        'parent_icon': 'robot',
        'title': network.name,
        'icon': 'sitemap',
        'description': 'Details of ' + network.name,
        'keywords': default_keywords() + 'network.name, display, details',
        'network': network,
        'hosts': hosts,
        'channels': channels,
        'total_hosts': shorten_number(hosts.count()),
        'total_chanels': shorten_number(channels.count()),
        'total_users': shorten_number(users.count()),
        'total_messages': shorten_number(total_messages(messages)),
        'total_actions': shorten_number(total_messages(actions)),
        'total_notices': shorten_number(total_messages(notices)),
        'total_joins': shorten_number(joins.count()),
        'total_kicks': shorten_number(kicks.count()),
    }
    return render(request, 'rotbot/network.html', context)


@login_required
@permission_required('rotbot.change_network', raise_exception=True)
def edit_network(request, network_slug):
    network = get_object_or_404(Network, slug=network_slug)
    title = network.name
    HostFormSet = inlineformset_factory(Network, Host, form=HostForm)
    OwnerFormSet = inlineformset_factory(Network, Owner, form=OwnerForm)
    if request.method == 'POST':
        form = NetworkForm(request.POST, instance=network)
        hostformset = HostFormSet(request.POST, instance=network)
        ownerformset = HostFormSet(request.POST, instance=network)
        if form.is_valid() and hostformset.is_valid() and ownerformset.is_valid():
            form.save()
            hostformset.save()
            ownerformset.save()
            return HttpResponseRedirect(reverse('rotbot:network', args=(network.slug,)))
    else:
        form = NetworkForm(instance=network)
        hostformset = HostFormSet(instance=network)
        ownerformset = OwnerFormSet(instance=network)
    context = {
        'parent_title': 'Networks',
        'parent_url': reverse('rotbot:networks'),
        'parent_icon': 'robot',
        'title': title,
        'icon': 'sitemap',
        'description': 'Edit ' + title,
        'keywords': default_keywords((title, 'edit')),
        'network_slug': network_slug,
        'form': form,
        'hostformset': hostformset,
        'ownerformset': ownerformset,
    }
    return render(request, 'rotbot/edit_network.html', context)

@login_required
@permission_required('rotbot.add_network', raise_exception=True)
def add_network(request):
    HostFormSet = inlineformset_factory(Network, Host, form=HostForm)
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            network = form.save()
            formset = HostFormSet(request.POST, instance=network)
            if formset.is_valid():
                formset.save()
                return HttpResponseRedirect(reverse('rotbot:network', args=(form.cleaned_data['slug'],)))
        else:
            formset = HostFormSet(queryset=Host.objects.none())
    else:   # Not a POST request.
        form = NetworkForm()
        formset = HostFormSet(queryset=Host.objects.none())
    context = {
        'parent_title': 'Networks',
        'parent_url': reverse('rotbot:networks'),
        'parent_icon': 'robot',
        'title': 'Add network',
        'icon': 'sitemap',
        'description': 'Add new irc network to ' + APPLICATION_NAME,
        'keywords': default_keywords() + 'add, add network',
        'form': form,
        'hostformset': formset,
    }
    return render(request, 'rotbot/add_network.html', context)


@login_required
@permission_required('rotbot.change_network', raise_exception=True)
def delete_network(request, network_slug):
    network = get_object_or_404(Network, slug=network_slug)
    network.delete()
    return HttpResponseRedirect(reverse('rotbot:networks'))
