from unicodedata import normalize

from report import Formatter
from helper import (
    remove_accents,
    custom_encode_cp860,
)
from typing import Optional

from _CommandFactory import CommandFactory
from report import Report

ESC = b'\x1b'


class EscPosFormatter(Formatter):
    def __init__(self, encoding="cp860", command_factory=None):
        # type: (str, CommandFactory) -> None
        self.encoding = encoding
        self.command_factory = command_factory

    def format(
        self,
        report,                 # type: Report
        allow_accents=False,    # type: Optional[bool]
        is_mobile=False,        # type: Optional[bool]
    ):
        # type: (...) -> str

        body = self.create_report_body(report.get_parts())
        if body == "":
            return body

        content = self._get_page_command() + body
        if is_mobile:
            return content.encode('utf-8')
        if not allow_accents:
            return remove_accents(text=content).encode(self.encoding)
        return custom_encode_cp860(text=content)

    def create_report_body(self, parts):
        body = ""
        for part in parts:
            if part.commands is not None:
                for command in part.commands:
                    body += self.command_factory.get_processor(command).get_bytes(command)
            if part.text is not None:
                body += part.text
        return body

    def _get_page_command(self):
        if self.encoding == "cp850":
            return ESC + 't' + '\x02'
        else:
            return ESC + 't' + '\x03'
