# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
# Copyright (C) 2018 RERO.
#
# Invenio-Circulation is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.

"""Circulation search API."""

from invenio_search.api import RecordsSearch

from ..proxies import current_circulation


class LoansSearch(RecordsSearch):
    """RecordsSearch for borrowed documents."""

    class Meta:
        """Search only on loans index."""

        index = "loans"
        doc_types = None


def search_by_pid(item_pid=None, document_pid=None, filter_states=None,
                  exclude_states=None):
    """Retrieve loans attached to the given item or document."""
    search = current_circulation.loan_search

    if document_pid:
        search = search.filter("term", document_pid=document_pid)
    elif item_pid:
        search = search.filter("term", item_pid=item_pid)
    else:
        raise ValueError("Must specify item_pid or document_pid param")

    if filter_states:
        search = search.filter("terms", state=filter_states)
    elif exclude_states:
        search = search.exclude("terms", state=exclude_states)

    return search


def search_by_patron_item(patron_pid, item_pid, filter_states=None):
    """Retrieve loans for patron given an item."""
    search = current_circulation.loan_search
    search = search \
        .filter("term", patron_pid=patron_pid) \
        .filter("term", item_pid=item_pid)

    if filter_states:
        search = search.filter("terms", state=filter_states)

    return search


def search_by_patron_pid(patron_pid):
    """Retrieve loans of a patron."""
    search = current_circulation.loan_search
    search = search.filter("term", patron_pid=patron_pid)
    return search

@@ -261,16 +261,68 @@
 PI.%22%22%22%0A%0A
+from elasticsearch_dsl import VERSION as ES_VERSION%0A
 from inv
@@ -595,16 +595,360 @@
 = None%0A%0A
+    def exclude(self, *args, **kwargs):%0A        %22%22%22Add method %60exclude%60 to old elastic search versions.%22%22%22%0A        if ES_VERSION%5B0%5D == 2:%0A            from elasticsearch_dsl.query import Bool, Q%0A            return self.query(Bool(filter=%5B~Q(*args, **kwargs)%5D))%0A        else:%0A            return super(LoansSearch, self).exclude(*args, **kwargs)%0A%0A
 %0Adef sea

add support search exclude to ES 2