import logging

from app import notification_queue
from workers.worker import Worker

from endpoints.notificationmethod import NotificationMethod, InvalidNotificationMethodException
from endpoints.notificationevent import NotificationEvent, InvalidNotificationEventException
from workers.worker import JobException

from data import model


logger = logging.getLogger(__name__)


class NotificationWorker(Worker):
  def process_queue_item(self, job_details):
    notification_uuid = job_details['notification_uuid'];

    notification = model.get_repo_notification(notification_uuid)
    if not notification:
      # Probably deleted.
      return

    event_name = notification.event.name
    method_name = notification.method.name

    try:
      event_handler = NotificationEvent.get_event(event_name)
      method_handler = NotificationMethod.get_method(method_name)
    except InvalidNotificationMethodException as ex:
      logger.exception('Cannot find notification method: %s' % ex.message)
      raise JobException('Cannot find notification method: %s' % ex.message)
    except InvalidNotificationEventException as ex:
      logger.exception('Cannot find notification event: %s' % ex.message)
      raise JobException('Cannot find notification event: %s' % ex.message)

    method_handler.perform(notification, event_handler, job_details)


if __name__ == "__main__":
  logging.config.fileConfig('conf/logging.conf', disable_existing_loggers=False)

  worker = NotificationWorker(notification_queue, poll_period_seconds=10, reservation_seconds=30,
                              retry_after_seconds=30)
  worker.start()
