import base64
import logging

import unicodedata
from typing import (
    Dict,
    Optional,
)

from application.repository.api import APIRepository
from dto import EndOfSaleNotesRequest

logger = logging.getLogger(__name__)


class EndOfSaleNotesInteractor(object):

    def __init__(
        self,               # type: EndOfSaleNotesInteractor
        api_repository,     # type: APIRepository
    ):
        # type: (...) -> None

        self.api_repository = api_repository

    def execute(
        self,       # type: EndOfSaleNotesInteractor
        request,    # type: EndOfSaleNotesRequest
    ):
        # type: (...) -> Optional[Dict[str, str]]

        logger.info("Searching for end of sale notes. PosId/OrderId {}/{}".format(request.pos_id, request.order_id))
        response = self.api_repository.end_of_sale_notes(
            pos_id=request.pos_id,
            order_id=request.order_id,
        )

        logger.info("End of sale notes response: {}".format(response))
        if not response:
            return None

        center_command = b"\x1b" + b"\x61\x01"
        data = center_command
        for line in response:
            data += self._remove_accents(text=line.get("text")) + "\n"

        return {
            "data": base64.b64encode(data.encode("utf-8")),
        }

    @staticmethod
    def _remove_accents(
        text,   # type: str
    ):
        # type: (...) -> str

        if not text:
            return text

        try:
            text = unicode(text, "utf-8")
        except (TypeError, NameError):
            pass

        text = unicodedata.normalize("NFD", text)
        text = text.encode("ascii", "ignore")
        return text
