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


logger = LoggerUtil.get_logger_name(__name__)


class UpdateTotalSoldOrderInteractor:
    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, event_type):
        # type: (str, str) -> None

        if event_type == "PAID":
            logger.info("[handle_event] ORDER_MODIFIED event received")
            order_picture = eTree.XML(data)

            if order_picture.find(".//CustomOrderProperties/OrderProperty[@key='TABLE_ID']") is not None:
                return

            order = order_picture.find('.//Order')
            self.daily_goals_service.update_daily_sold(order)
