from mbcontextmessagehandler import MbContextMessageBus
from mwhelper import BaseRepository

from persistence import (
    Connection,
    Cursor,
)

from model.services import NavigationServiceModel


class NavigationService(NavigationServiceModel, BaseRepository):

    def __init__(
        self,
        message_bus     # type: MbContextMessageBus
    ):
        # type: (...) -> None

        super(NavigationService, self).__init__(message_bus.mbcontext)
        self.message_bus = message_bus

    def get_navigation_descriptions(
        self,
    ):
        # type: (...) -> str

        def inner_func(
            conn    # type: Connection
        ):
            # type: (...) -> dict

            query = """
                SELECT DescrId,
                    NavId,
                    NavigationDescription
                FROM NavigationDescriptions
            """
            cursor = conn.select(sql=query)
            navigations = self._parse_navigation_descriptions_data(cursor=cursor)

            return navigations

        descriptions_json = self.execute_with_connection(
            method=inner_func,
            service_name="Persistence",
        )

        return descriptions_json

    @staticmethod
    def _parse_navigation_descriptions_data(
        cursor,  # type: Cursor
    ):
        # type: (...) -> dict

        navigations = {}
        for row in cursor:
            descr_id = row.get_entry(0)
            nav_id = row.get_entry(1)
            description = row.get_entry(2)

            if nav_id not in navigations:
                navigations[nav_id] = {
                    "pt-br": "",
                    "en-us": "",
                    "es-es": "",
                }
            nav_descriptions = navigations.get(nav_id)

            language = None
            if descr_id == "4":
                language = "pt-br"
            elif descr_id == "14":
                language = "en-us"
            elif descr_id == "24":
                language = "es-es"

            if language:
                nav_descriptions[language] = description

        return navigations
