import json
from typing import Optional

from report import Generator
from reportsdata.justificationreport.dto import (
    JustificationGeneratorDto,
    JustificationHeaderDto,
    JustificationBodyDto,
)

from utils.report_formatters import remove_accents


class JustificationReportGenerator(Generator):

    def __init__(
        self,
        pos_id,     # type: str
        data,       # type: str
    ):
        # type: (...) -> None

        self.pos_id = pos_id
        self.data = json.loads(
            s=data,
        )

    def generate_data(
        self
    ):
        # type: (...) -> JustificationGeneratorDto

        return JustificationGeneratorDto(
            header=self._get_header(),
            body=self._get_body(),
        )

    def _get_header(
        self
    ):
        # type: (...) -> JustificationHeaderDto

        justification_type = self._get_data(
            key="justificationType",
        )

        title = '$JUSTIFICATION_DISCOUNT_TITLE'
        subtitle = ""
        if justification_type != 'APPLY_DISCOUNT':
            title = '$JUSTIFICATION_CANCELLATION_TITLE'
            subtitle = '$JUSTIFICATION_TITLE_ORDER'
            if str(justification_type) == "VOID_LINE":
                subtitle = '$JUSTIFICATION_TITLE_ITEM'

        return JustificationHeaderDto(
            title=title,
            subtitle=subtitle,
        )

    def _get_body(
        self
    ):
        # type: (...) -> JustificationBodyDto

        order_id = self._get_data(
            key="orderId",
        )

        operator = self._get_data(
            key="operator",
        )

        authorized_by = self._get_data(
            key="AuthorizedBy",
        )

        discount_description = remove_accents(
            text=self._get_data(
                key="discountUserDescription",
            )
        )

        justification = remove_accents(
            text=self._get_data(
                key="justification",
            )
        )

        return JustificationBodyDto(
            order_id=order_id,
            operator=operator,
            authorized_by=authorized_by,
            discount_description=discount_description,
            justification=justification,
        )

    def _get_data(
        self,
        key,                # type: str
        default="",         # type: Optional[str]
    ):
        # type: (...) -> str

        return self.data.get(
            key,
            default,
        )
