from PySide6.QtCore import QSizeF, QMarginsF
from PySide6.QtGui import QPageSize, QPageLayout
from PySide6.QtPrintSupport import QPrinter

from pypos.modules.printer.config.printer_config import (
    THERMAL_DPI,
    PREVIEW_HEIGHT_MM,
    ROLL_HEIGHT_MM,
    get_paper_width_mm,
    estimate_cols_by_mm,
)


class PrinterPaperService:
    def mm_to_points(self, mm: float) -> float:
        return float(mm) * 2.83465

    def get_paper_mm(self, paper_label: str) -> float:
        return get_paper_width_mm(paper_label)

    def apply_paper_size(self, printer: QPrinter, paper_label: str):
        width_mm = self.get_paper_mm(paper_label)
        printer.setPageSize(QPageSize(QSizeF(width_mm, ROLL_HEIGHT_MM), QPageSize.Millimeter))
        printer.setPageMargins(QMarginsF(0, 0, 0, 0), QPageLayout.Millimeter)

    def estimate_cols(self, paper_label: str) -> int:
        width_mm = self.get_paper_mm(paper_label)
        return estimate_cols_by_mm(width_mm)

    def make_preview_printer(self, width_mm: float) -> QPrinter:
        preview_printer = QPrinter(QPrinter.HighResolution)
        preview_printer.setResolution(THERMAL_DPI)
        try:
            preview_printer.setOutputFormat(QPrinter.NativeFormat)
        except (TypeError, ValueError, KeyError, AttributeError, RuntimeError, OSError, LookupError, ArithmeticError, ImportError):
            pass
        preview_printer.setPageSize(QPageSize(QSizeF(width_mm, PREVIEW_HEIGHT_MM), QPageSize.Millimeter))
        preview_printer.setPageMargins(QMarginsF(0, 0, 0, 0), QPageLayout.Millimeter)
        preview_printer.setFullPage(True)
        return preview_printer
