import json

from aws_lambda_powertools.event_handler.api_gateway import Router
from elasticsearch import Elasticsearch
from layercake.dynamodb import (
    DynamoDBCollection,
    DynamoDBPersistenceLayer,
    SortKey,
    TransactKey,
)

import elastic
from boto3clients import dynamodb_client
from config import ELASTIC_CONN, ENROLLMENT_TABLE, USER_TABLE

from .cancel import router as cancel
from .enroll import router as enroll
from .vacancies import router as vacancies

__all__ = ['vacancies', 'cancel', 'enroll']


router = Router()
elastic_client = Elasticsearch(**ELASTIC_CONN)
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
enrollment_collect = DynamoDBCollection(enrollment_layer)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
user_collect = DynamoDBCollection(user_layer)


@router.get('/', compress=True, tags=['Enrollment'])
def get_enrollments():
    event = router.current_event
    query = event.get_query_string_value('query', '{}')
    page_size = event.get_query_string_value('page_size', '25')

    return elastic.search(  # type: ignore
        index=ENROLLMENT_TABLE,
        page_size=int(page_size),
        query=json.loads(query),
        elastic_client=elastic_client,
    )


@router.get('/<id>', compress=True, tags=['Enrollment'])
def get_enrollment(id: str):
    return enrollment_collect.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', path_spec='hash')
        + SortKey('author')
        + SortKey('tenant')
        + SortKey('cert')
    )
