from django import forms
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404

from intranet.search.core.models import Organization
from intranet.search.admin.template import render
from intranet.search.admin.admin.utils import paginate
from intranet.search.admin.utils import OrganizationField


class OrganizationSearchForm(forms.Form):
    organization = OrganizationField(required=False)


def organization_list(request):
    org_queryset = Organization.objects.prefetch_related('service_set').order_by('-id')

    form = OrganizationSearchForm(request.GET)
    if form.is_valid() and form.cleaned_data['organization']:
        url = reverse('isearch-organization-details', args=(form.cleaned_data['organization']['id'], ))
        return HttpResponseRedirect(url)

    organizations = paginate(org_queryset, request.GET.get('page'))
    return render(request, 'isearch/organization/organization-list.html',
                  {'organizations': organizations, 'form': form})


def organization_details(request, organization_id):
    organization = get_object_or_404(Organization.objects.select_related(), id=organization_id)
    context = {
        'organization': organization,
        'robot_user': organization.robot_user if hasattr(organization, 'robot_user') else None
    }
    return render(request, 'isearch/organization/organization.html', context)
