import logging

from django.conf import settings

import yenv

from staff.lib.models.departments_chain import DepartmentsChain

from staff.departments.notifications import (
    DepartmentChiefUpdateNotification,
    NEW_DepartmentDeputiesUpdateNotification,
    DepartmentCreated,
    DepartmentDeleted,
)

logger = logging.getLogger(__name__)


def send_chief_updated(department, old_chief, new_chief):
    if old_chief == new_chief:
        return

    departments_chain = (
        DepartmentsChain().get_chain_as_list(department=department)
    )

    context = {
        'department': department,
        'old_chief': old_chief,
        'new_chief': new_chief,
        'settings': settings,
        'departments_chain': departments_chain,
    }

    try:
        DepartmentChiefUpdateNotification(
            context=context,
            target='SUPERIORS_HR',
            department=department,
            office=None,
            staff=None,
        ).send()

    except Exception:
        logger.exception("Can't send DepartmentChiefUpdateNotification")
        if yenv.type == 'production':
            raise


def send_deputies_updated(department, old_deputies, new_deputies):
    departments_chain = (
        DepartmentsChain().get_chain_as_list(department=department)
    )

    context = {
        'department': department,
        'old_deputies_list': old_deputies,
        'new_deputies_list': new_deputies,
        'settings': settings,
        'departments_chain': departments_chain,
    }

    try:
        NEW_DepartmentDeputiesUpdateNotification(
            context=context,
            target='SUPERIORS_HR',
            department=department,
            office=None,
            staff=None,
        ).send()

    except Exception:
        logger.exception("Can't send DepartmentDeputiesUpdateNotification")
        if yenv.type == 'production':
            raise


def send_department_created(department):
    departments_chain = (
        DepartmentsChain().get_chain_as_list(department=department)
    )
    context = {
        'department': department,
        'departments_chain': departments_chain
    }

    try:
        DepartmentCreated(
            context=context,
            target='DEPARTMENT_CREATED',
        ).send()
    except Exception:
        logger.exception("Can't send DepartmentCreated notification")
        if yenv.type == 'production':
            raise


def send_department_deleted(department, old_url):

    departments_chain = (
        DepartmentsChain().get_chain_as_list(department=department)
    )
    context = {
        'department': department,
        'old_url': old_url,
        'departments_chain': departments_chain
    }

    try:
        DepartmentDeleted(
            context=context,
            target='DEPARTMENT_DELETED',
        ).send()
    except Exception:
        logger.exception("Can't send DepartmentDeleted notification")
        if yenv.type == 'production':
            raise
