import urllib.parse as parse

from aws_lambda_powertools.event_handler.api_gateway import Router
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    SortKey,
    TransactKey,
)
from meilisearch import Client as Meilisearch

import meili
from boto3clients import dynamodb_client
from config import ENROLLMENT_TABLE, MEILISEARCH_API_KEY, MEILISEARCH_HOST, USER_TABLE
from middlewares import Tenant, TenantMiddleware

from .cancel import router as cancel
from .deduplication_window import router as deduplication_window
from .enroll import router as enroll
from .slots import router as slots

__all__ = ['slots', 'cancel', 'enroll', 'deduplication_window']


router = Router()
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
meili_client = Meilisearch(MEILISEARCH_HOST, MEILISEARCH_API_KEY)


@router.get(
    '/',
    compress=True,
    tags=['Enrollment'],
    middlewares=[
        TenantMiddleware(user_layer.collection),
    ],
)
def get_enrollments():
    tenant: Tenant = router.context['tenant']
    event = router.current_event
    query = parse.unquote(event.get_query_string_value('q', ''))
    sort = event.get_query_string_value('sort', 'create_date:desc')
    page = int(event.get_query_string_value('page', '1'))
    hits_per_page = int(event.get_query_string_value('hitsPerPage', '25'))
    filter_ = meili.parse(event.get_query_string_value('filter', ''))

    if tenant.id != '*':
        filter_ = [
            {
                'attr': 'tenant_id',
                'op': '=',
                'value': tenant.id,
            },
        ] + filter_

    return meili_client.index(ENROLLMENT_TABLE).search(
        query,
        {
            'sort': [sort],
            'locales': ['pt'],
            'page': page,
            'hitsPerPage': hits_per_page,
            'filter': meili.encode(filter_),
        },
    )


@router.get('/<id>', compress=True, tags=['Enrollment'])
def get_enrollment(id: str):
    return enrollment_layer.collection.get_items(
        TransactKey(id)
        + SortKey('0')
        + SortKey('started_date')
        + SortKey('finished_date')
        + SortKey('failed_date')
        + SortKey('canceled_date')
        + SortKey('archived_date')
        + SortKey('cancel_policy')
        + SortKey('parent_vacancy', path_spec='vacancy')
        + SortKey('lock')
        + SortKey('author')
        + SortKey('tenant')
        + SortKey('cert')
    )
