# -*- coding: utf-8 -*-

from elasticsearch import NotFoundError as ElasticsearchNotFoundError
from werkzeug.exceptions import NotFound

from distribution import app
from . import BaseManager


class ApiAuthBaseManager(BaseManager):
    def get(self, key):
        try:
            data = self.backend.client.get(self.index, key, self.doc_type)
            return self.cast_to_model(data)
        except ElasticsearchNotFoundError as e:
            raise NotFound(e)


class RoleManager(ApiAuthBaseManager):
    index = app.config.get('ELASTICSEARCH_AUTH_INDEX_NAME', 'distribution_auth')

    def get_role_permissions(self, roles, is_active=True, use_valid_until=True):
        if len(roles) == 0:
            return None

        query = {
            'post_filter': {
                'bool': {
                    'must': [
                        {
                            'terms': {
                                'name': roles,
                            }
                        }
                    ]
                }
            }
        }

        if is_active:
            query['post_filter']['bool']['must'].append({
                'term': {
                    'is_active': True
                }
            })

        if use_valid_until:
            query['post_filter']['bool']['must'].append({
                "bool": {
                    "should": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        'exists': {
                                            'field': 'valid_until'
                                        }
                                    },
                                    {
                                        'range': {
                                            'valid_until': {
                                                'gte': 'now'
                                            }
                                        }
                                    },
                                ]
                            }
                        },
                        {
                            "bool": {
                                "must_not": {
                                    'exists': {
                                        'field': 'valid_until'
                                    }
                                }
                            }
                        },
                    ]
                }
            })

        result = self.backend.client.search(self.index, self.doc_type, query)
        app.logger.debug('get_role_permissions: Found {} roles for query: {}'.format(
            len(result['hits']['hits']), query))
        if result['hits']['total'] == 0:
            return None

        return result['hits']['hits'][0]['_source']['permissions']


class APIUserManager(ApiAuthBaseManager):
    index = app.config.get('ELASTICSEARCH_AUTH_INDEX_NAME', 'distribution_auth')

    def build_search_query(self, *args, **kwargs):
        arguments = kwargs.get('arguments', {})

        if not arguments:
            return None

        query = {
            'post_filter': {
                'bool': {
                    'must': []
                }
            }
        }

        for arg in arguments:
            query['post_filter']['bool']['must'].append({'term': {arg: arguments[arg]}})

        return query
