import logging
from collections import deque

from django.http import Http404
from django.shortcuts import render

from core.models import CustomFlatPage
from .models import Member, JobMember, JobGroup

logger = logging.getLogger(__name__)


def __remove_if_zero_active_mem(job_group):
    for elem in list(job_group):
        job_members = JobMember.active_member.get_all_by_slug(slug=elem.slug)
        if not job_members:
            job_group.remove(elem)

    return job_group


def __get_job_groups():
    pinned_job_groups = deque(JobGroup.all_jobgroups.get_pinned_jobgroups())
    unpinned_job_groups = deque(JobGroup.all_jobgroups.get_unpinned_jobgroups())

    # remove job group if there is no longer an active member
    pinned_job_groups = __remove_if_zero_active_mem(pinned_job_groups)
    unpinned_job_groups = __remove_if_zero_active_mem(unpinned_job_groups)

    # show max 5 pinned jobgroups
    if len(pinned_job_groups) > 5:
        for idx, val in enumerate(pinned_job_groups[5:]):
            unpinned_job_groups.append(val)

        pinned_job_groups = pinned_job_groups[:5]

    return pinned_job_groups, unpinned_job_groups


def index(request):
    pinned_job_groups, unpinned_job_groups = __get_job_groups()
    members = deque(Member.all_members.all())

    fs_info = CustomFlatPage.objects.filter(title__iexact="fachschaft").first()

    context = {
        "pinned_job_groups": pinned_job_groups,
        "unpinned_job_groups": unpinned_job_groups,
        "members": members,
        "fs_info": fs_info,
    }

    return render(request, "members/index.html", context)


def jobs_view(request, slug=None):
    pinned_job_groups, unpinned_job_groups = __get_job_groups()

    try:
        description = (
            JobGroup.all_jobgroups.filter(slug=slug).values().first()["description"]
        )
    except Exception:
        logger.info("Wrong job '{}'".format(slug))
        raise Http404("wrong job")

    job_members = JobMember.active_member.get_all_by_slug(slug=slug)

    context = {
        "pinned_job_groups": pinned_job_groups,
        "unpinned_job_groups": unpinned_job_groups,
        "description": description,
        "job_members": job_members,
    }

    return render(request, "members/index.html", context)


def members_view(request, filter=None):
    pinned_job_groups, unpinned_job_groups = __get_job_groups()

    for elem in Member.MemberRole:
        if filter == elem.label.lower():
            members = deque(Member.all_members.filter(role=elem.value))
            break
    else:
        logger.info("Wrong member role '{}'".format(filter))
        raise Http404("no member role")

    fs_info = CustomFlatPage.objects.filter(title__iexact="fachschaft").first()

    context = {
        "pinned_job_groups": pinned_job_groups,
        "unpinned_job_groups": unpinned_job_groups,
        "members": members,
        "fs_info": fs_info,
    }

    return render(request, "members/index.html", context)


def profile_view(request, member_id=None):
    pinned_job_groups, unpinned_job_groups = __get_job_groups()

    member = Member.all_members.filter(id=member_id).first()
    if not member:
        logger.info("Wrong member id '{}'".format(member_id))
        raise Http404("no member")

    jobs = deque(JobMember.members.filter(member__id=member_id))

    context = {
        "pinned_job_groups": pinned_job_groups,
        "unpinned_job_groups": unpinned_job_groups,
        "member": member,
        "jobs": jobs,
    }

    return render(request, "members/member.html", context)
