from django import forms
from django.shortcuts import redirect
from django.conf import settings
from django.http import HttpResponseBadRequest

from intranet.search.core.utils import get_ids_repository

from intranet.search.core.models import Feature
from intranet.search.admin.template import render


dep_repo = get_ids_repository('staff', 'group')


def get_group_id(group_name):
    group = dep_repo.get_one(lookup={'url': group_name})
    return group['id']


def get_group_name(group_id):
    group = dep_repo.get_one(lookup={'id': group_id})
    return group['url']


def get_group_name_bulk(groups):
    if not groups:
        return []
    groups = dep_repo.get(lookup={'id': ','.join(map(str, groups))})
    return [group['url'] for group in groups]


def features_user(request, user):
    user_features = Feature.objects.filter(user=user).values('name', 'value', 'id')
    return features(request, user_features, user, '', '')


def features_group(request, group_name):
    group_id = get_group_id(group_name)
    group_features = Feature.objects.filter(group_id=group_id).values('name', 'value', 'id')
    return features(request, group_features, '', group_id, group_name)


def features(request, features, user, group_id, group_name):
    active_features = [f['name'] for f in features]
    not_active = []
    for feature in set(settings.ISEARCH['features']) - set(active_features):
        not_active.append({'name': feature, 'id': None, 'value': ''})

    active_users = Feature.objects.filter(group_id=None).distinct().values_list('user', flat=True)
    active_groups = Feature.objects.filter(user=None).distinct().values_list('group_id', flat=True)
    active_groups_names = get_group_name_bulk(active_groups)

    return render(request, 'isearch/features.html',
                  {'features': features,
                   'not_active': not_active,
                   'active_users': active_users,
                   'active_groups': active_groups_names,
                   'active_user': user,
                   'active_group_id': group_id,
                   'active_group_name': group_name},
                  content_type='text/html')


def redirect_decider(user, group_id):
    if user:
        return redirect(features_user, user)
    else:
        group_name = get_group_name(group_id)
        return redirect(features_group, group_name)


class AddFeatureForm(forms.Form):
    name = forms.SlugField()
    value = forms.CharField(required=False)
    user = forms.CharField(required=False)
    group_id = forms.CharField(required=False)


def add_feature(request):
    f = AddFeatureForm(request.POST)

    if f.is_valid():
        user = f.cleaned_data['user'] or None
        group_id = f.cleaned_data['group_id'] or None
        obj, created = Feature.objects.get_or_create(user=user, group_id=group_id,
                                                     name=f.cleaned_data['name'])
        obj.value = f.cleaned_data['value']
        obj.save()
        return redirect_decider(user, group_id)
    else:
        return HttpResponseBadRequest(f.errors, content_type='text/html')


class DeleteFeatureForm(forms.Form):
    id = forms.IntegerField()
    user = forms.CharField(required=False)
    group_id = forms.IntegerField(required=False)


def del_feature(request):
    f = DeleteFeatureForm(request.POST)
    if f.is_valid():
        Feature.objects.get(id=f.cleaned_data['id']).delete()
        return redirect_decider(f.cleaned_data['user'], f.cleaned_data['group_id'])
    else:
        return HttpResponseBadRequest(f.errors, content_type='text/html')
