import json
from logging import Logger
from threading import Lock

from mbcontextmessagehandler import MbContextMessageBus
from messagebus import Event
from msgbus import MBEasyContext

from externals.repository import AlertsRepository
from externals.repository.api import AlertsAPIRepository
from services.util import get_store_id


updating_configured_alerts = Lock()


class UpdateService(object):

    def __init__(
        self,
        message_bus,            # type: MbContextMessageBus
        mb_context,             # type: MBEasyContext
        alerts_repository,      # type: AlertsRepository
        alerts_api_repository,  # type: AlertsAPIRepository
        logger,                 # type: Logger
    ):
        # type: (...) -> None

        self.message_bus = message_bus
        self.mb_context = mb_context
        self.alerts_repository = alerts_repository
        self.alerts_api_repository = alerts_api_repository
        self.logger = logger

    def update_configured_alerts(
        self,
    ):
        # type: (...) -> None

        global updating_configured_alerts

        with updating_configured_alerts:
            configured_alerts = self.alerts_api_repository.retrieve_configured_alerts()
            configured_alerts = json.loads(configured_alerts)
            self.alerts_repository.update_configured_alerts(configured_alerts)

    def update_configured_alerts_ack(
        self,
    ):
        # type: (...) -> None

        global updating_configured_alerts

        with updating_configured_alerts:
            subject = "BohChangeNotificationAck"
            store_id = get_store_id()
            self.logger.info(
                "Sending event %r from store %r",
                subject,
                store_id,
            )
            event = Event(
                subject=subject,
                event_type="",
                data=json.dumps({
                    "store_code": store_id
                })
            )
            self.message_bus.publish_event(event=event)
