from logger_local.LoggerLocal import Logger
from python_sdk_local.http_response import handler_decorator
from python_sdk_local.utilities import DEFAULT_LANG_CODE_STR

from opensearch_local.our_opensearch import OurOpenSearch

from .constants_event_local import EVENTS_LOCAL_CODE_LOGGER_OBJECT
from .events_local import EventsLocal

logger = Logger.create_logger(object=EVENTS_LOCAL_CODE_LOGGER_OBJECT)


@handler_decorator(logger)
def createHandler(request_parameters: dict) -> dict:
    # In all serverless-com handlers' logger.start()- Add optional parameter
    # to logger.start() which called api_call, so logger.start will call
    # api_management to insert into api_call_table all fields including
    # session_id.
    """Read parameters from the payload and insert them"""
    print("in createHandler request_parameters", request_parameters)
    is_test_data = request_parameters.get("isTestData", False)
    event_id = EventsLocal(is_test_data=is_test_data).insert_event_data(
        request_parameters
    )
    message = {"message": "Event created successfully", "event_id": event_id}
    logger.info(
        object={
            "message": message,
            "request_parameters": request_parameters,
        }
    )
    return message


# TODO: except ValueError as exception, BAD_REQUEST / INTERNAL_SERVER_ERROR...


@handler_decorator(logger)
def deleteHandler(request_parameters: dict) -> dict:
    """url/5   (5 is the eventId)"""

    event_id = request_parameters.get("eventId")
    is_test_data = request_parameters.get("isTestData", False)
    EventsLocal(is_test_data=is_test_data).delete_by_event_id(event_id=event_id)
    message = {"message": "Event deleted successfully"}
    return message


# TODO This should be imported from entity-type-python-package (this file will be generated by Sql2Code)
@handler_decorator(logger)
def getAllHandler(request_parameters: dict) -> list:
    """url?langCode=en&limit=10"""

    lang_code_str = request_parameters.get("langCode") or DEFAULT_LANG_CODE_STR
    limit = request_parameters.get("limit")
    is_test_data = request_parameters.get("isTestData", False)
    events_list = EventsLocal(is_test_data=is_test_data).select_all_events(
        lang_code_str, limit=limit
    )
    return events_list


@handler_decorator(logger)
def getEventByProfileIdHandler(request_parameters: dict) -> list:
    """url/5?limit=10   (5 is the profileId)"""

    request_parameters = request_parameters
    profile_id = request_parameters.get("profileId")
    limit = request_parameters.get("limit")

    is_test_data = request_parameters.get("isTestData", False)
    events_list = EventsLocal(is_test_data=is_test_data).select_events_by_profile_id(
        profile_id, limit=limit
    )
    return events_list


@handler_decorator(logger)
def getEventByEventIdHandler(request_parameters: dict) -> dict:
    """url/5?isTestData=true   (eventId)"""

    event_id = request_parameters.get("eventId")

    is_test_data = request_parameters.get("isTestData", False)
    event = EventsLocal(is_test_data=is_test_data).select_by_event_id(event_id)
    if not event:
        raise Exception(f"Event not found with event_id: {event_id}")
    return event


@handler_decorator(logger)
def updateHandler(request_parameters: dict) -> dict:
    """url/5  (eventId)
    Read parameters from the payload and update them"""

    event_id = request_parameters.get("eventId")
    is_test_data = request_parameters.get("isTestData", False)
    if not event_id:
        raise Exception("event_id is required")

    EventsLocal(is_test_data=is_test_data).update_by_event_id(
        event_id, request_parameters
    )
    message = {"message": "Event updated successfully"}
    return message


@handler_decorator(logger)
def getEventByEventTitleHandler(request_parameters: dict) -> list:  # TODO: test
    """url/SomeTitle?limit=10"""

    title = request_parameters.get("title")

    limit = request_parameters.get("limit")
    is_test_data = request_parameters.get("isTestData", False)
    events_list = EventsLocal(is_test_data=is_test_data).select_events_by_title(
        title, limit=limit
    )
    return events_list


def getEventsFromOpensearch(request_parameters: dict, opensearch_query: dict) -> list:
    """url?langCode=en&limit=10"""
    our_opensearch = OurOpenSearch(buffer_size=5)
    lang_code_str = request_parameters.get("langCode") or DEFAULT_LANG_CODE_STR

    limit = request_parameters.get("limit")
    is_test_data = request_parameters.get("isTestData", False)

    bool_query = {
        "bool": {
            "must": [
                opensearch_query,  # Keep the existing query conditions
                {"match": {"lang_code": lang_code_str}},  # Add lang_code filter
                {"match": {"is_test_data": is_test_data}},  # Add is_test_data filter
            ]
        }
    }

    new_query = {
        "query": bool_query,
        "size": limit
    }

    events_list = our_opensearch.search(
        index="event",
        body=new_query
    )
    return events_list
