from django import template

from atlas.helpers import get_cases_available_to_user

register = template.Library()


@register.inclusion_tag('atlas/partials/case_search_widget.html', takes_context=True)
def case_search_widget(
  context,
  collection=None,
  cases=None,
  recent_cases=None,
  input_id='case-search-input',
  target_id='case-search-results',
  selection_mode='single',
  action_url=None,
  show_select_button=False,
):
  """Render a reusable case search widget.

  Parameters:
    - collection: optional Collection object to scope searches
    - cases: optional initial queryset/list of cases to render
    - recent_cases: optional recent_cases list; if omitted, populate with user's recent cases
    - input_id: DOM id to use for the search input
    - target_id: DOM id to use for results container
  """
  request = context.get('request')
  user = getattr(request, 'user', None)

  # If recent_cases not provided, default to user's recent cases
  if recent_cases is None and user is not None and user.is_authenticated:
    try:
      recent_cases = get_cases_available_to_user(user, collection=collection).filter(author=user).order_by('-created_date')[:5]
    except Exception:
      recent_cases = []

  return {
    'request': request,
    'collection': collection,
    'cases': cases,
    'recent_cases': recent_cases,
    'input_id': input_id,
    'target_id': target_id,
    'selection_mode': selection_mode,
    'action_url': action_url,
    'show_select_button': show_select_button,
  }


@register.inclusion_tag('atlas/partials/finding_search_widget.html', takes_context=True)
def finding_search_widget(context, case=None, findings=None, input_id='finding-search-input', target_id='finding-search-results'):
  """Render a reusable finding search widget, optionally scoped to a `case`.

  Parameters:
    - case: optional Case instance to scope findings to
    - findings: optional initial queryset/list of findings to render
  """
  request = context.get('request')
  user = getattr(request, 'user', None)
  return {
    'request': request,
    'case': case,
    'findings': findings,
    'input_id': input_id,
    'target_id': target_id,
  }


@register.inclusion_tag('atlas/partials/displayset_search_widget.html', takes_context=True)
def displayset_search_widget(context, case=None, displaysets=None, input_id='displayset-search-input', target_id='displayset-search-results'):
  """Render a reusable displayset search widget scoped to a `case` by default."""
  request = context.get('request')
  return {
    'request': request,
    'case': case,
    'displaysets': displaysets,
    'input_id': input_id,
    'target_id': target_id,
  }
