import urllib.parse as parse
from os import rename

from aws_lambda_powertools.event_handler.api_gateway import Router
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    KeyPair,
    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 .download_issued_cert import router as issued_cert
from .enroll import router as enroll
from .slots import router as slots

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


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', 'created_at: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': 'org_id',
                'op': '=',
                # Post-migration (enrollemnt): rename `tenant` to `org`
                '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):
    record = enrollment_layer.collection.get_items(
        TransactKey(id)
        + SortKey('0')
        + SortKey('ORG', rename_key='org')
        # + SortKey('STARTED', rename_key='started_at', path_spec='started_at')
        # + SortKey('COMPLETED', rename_key='completed_at', path_spec='completed_at')
        # + SortKey('FAILED', rename_key='failed_at', path_spec='failed_at')
        + SortKey('CANCELED', rename_key='canceled')
        # + SortKey('ARCHIVED', rename_key='archived_at', path_spec='archived_at')
        + SortKey('CANCEL_POLICY', rename_key='cancel_policy')
        + SortKey('LOCK', rename_key='lock')
        + SortKey('parent_vacancy', path_spec='vacancy')
        + SortKey('author')
    )

    events = enrollment_layer.collection.query(KeyPair(id, 'SCHEDULE#'))
    record['events'] = events.get('items', [])

    return record
