import logging

import requests

from src.ezgg_lan_manager.services.SeatingService import SeatingService
from src.ezgg_lan_manager.types.CateringOrder import CateringOrder
from src.ezgg_lan_manager.types.ConfigurationTypes import ReceiptPrintingConfiguration
from src.ezgg_lan_manager.types.User import User

logger = logging.getLogger(__name__.split(".")[-1])
logging.getLogger("urllib3").setLevel(logging.FATAL)  # Disable logging for urllib3

class ReceiptPrintingService:
    def __init__(self, seating_service: SeatingService, config: ReceiptPrintingConfiguration, dev_mode_enabled: bool) -> None:
        self._seating_service = seating_service
        self._config = config
        self._dev_mode_enabled = dev_mode_enabled
        self._url = f"http://{self._config.host}:{self._config.port}/{self._config.order_print_endpoint}"

    async def print_order(self, user: User, order: CateringOrder) -> None:
        seat = await self._seating_service.get_user_seat(user.user_id)
        if seat is None:
            seat_id = " - "
        else:
            seat_id = str(seat.seat_id)


        menu_items_payload = []
        for item, amount in order.items.items():
            menu_items_payload.append({
                "menu_item_name": item.name,
                "amount": amount
            })

        payload = {
            "order_id": str(order.order_id),
            "order_date": order.order_date.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
            "customer_name": user.user_name,
            "seat_id": seat_id,
            "items": menu_items_payload
        }

        logger.info(f"Sending print order to {self._url}: {payload}")
        try:
            response = requests.post(
                self._url,
                json=payload,
                headers={"x-password": self._config.password},
                timeout=2.0
            )
            if response.status_code != 200:
                logger.error(f"Received an error with code {response.status_code}: {response.text}")
        except Exception as e:
            if self._dev_mode_enabled:
                logger.info("An error occurred trying to print a receipt: %s", e)
                return
            logger.error("An error occurred trying to print a receipt: %s", e)
