from xml.etree import cElementTree as eTree

from dailygoals_services.model.repository import DailyGoalsRepository
from dailygoals_services.service import DailyGoalsService
from externals.util import LoggerUtil
from sysactions import get_model, get_posot

logger = LoggerUtil.get_logger_name(__name__)


class UpdateTotalSoldTableInteractor:
    def __init__(self, daily_goals_repository, daily_goals_service):
        # type: (DailyGoalsRepository, DailyGoalsService) -> None

        self.daily_goals_repository = daily_goals_repository
        self.daily_goals_service = daily_goals_service

    def update(self, data):
        # type: (str) -> None

        logger.info("[handle_event] TABLE_CLOSED event received")
        table_picture = eTree.XML(data)
        payment_order = table_picture.findall('.//PaymentOrder')[0]
        pos_id = table_picture.find("Table").get("currentPOSId", None)
        order_id = payment_order.get("orderId", None)

        order = self._get_order_picture(pos_id, order_id)
        number_of_seats = 0

        if not order or order.get("state") != "PAID":
            return

        if table_picture.find("Table").get("serviceSeats") is not None:
            number_of_seats = int(table_picture.find("Table").get("serviceSeats"))

        self.daily_goals_service.update_daily_sold(order, number_of_seats=number_of_seats)

    @staticmethod
    def _get_order_picture(pos_id, order_id):
        # type: (str, str) -> eTree.Element

        order = None
        if pos_id and order_id:
            model = get_model(pos_id)
            pos_ot = get_posot(model)
            orders = eTree.XML(pos_ot.orderPicture(pos_id, order_id))
            order = orders.findall('.//Order')[0]
        return order
