import json
from http import HTTPStatus

from aws_lambda_powertools.event_handler import Response, content_types
from aws_lambda_powertools.event_handler.api_gateway import Router
from elasticsearch import Elasticsearch
from layercake.dynamodb import DynamoDBCollection, DynamoDBPersistenceLayer

import elastic
from boto3clients import dynamodb_client
from course import create_course
from middlewares import AuditLogMiddleware
from models import Course, Org
from settings import COURSE_TABLE, ELASTIC_CONN, USER_TABLE

router = Router()
elastic_client = Elasticsearch(**ELASTIC_CONN)
course_layer = DynamoDBPersistenceLayer(COURSE_TABLE, dynamodb_client)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
collect = DynamoDBCollection(user_layer)


@router.get(
    '/',
    compress=True,
    tags=['Course'],
    summary='Get courses',
)
def get_courses():
    event = router.current_event
    query = event.get_query_string_value('query', '{}')
    page_size = event.get_query_string_value('page_size', '25')

    return elastic.search(
        index=COURSE_TABLE,
        page_size=int(page_size),
        query=json.loads(query),
        elastic_client=elastic_client,
    )


@router.post(
    '/',
    compress=True,
    tags=['Course'],
    middlewares=[AuditLogMiddleware('COURSE_ADD', collect)],
)
def post_course(payload: Course):
    create_course(
        course=payload,
        org=Org(id='*', name='default'),
        persistence_layer=course_layer,
    )

    return Response(
        body={'id': str(payload.id), },
        content_type=content_types.APPLICATION_JSON,
        status_code=HTTPStatus.CREATED,
    )


@router.get('/<id>', compress=True, tags=['Course'])
def get_course(id: str):
    return {}
