import logging

from django.conf import settings

from intranet.femida.src.celery_app import app
from intranet.femida.src.staff.achievements import (
    AchievementsAPI,
    give_interview_counter_achievements,
    ApprovedReferenceAchievement,
    AcceptedOfferReferenceAchievement,
)
from intranet.femida.src.staff.sync import (
    DepartmentSynchronizer,
    DepartmentUserSyncronizer,
    ServiceSynchronizer,
    UserSyncronizer,
    OfficeSynchronizer,
    OrganizationSynchronizer,
    PositionSynchronizer,
    ProfessionSynchronizer,
    ValueStreamSynchronizer,
    GeographySynchronizer,
)
from intranet.femida.src.utils.lock import locked_task


logger = logging.getLogger(__name__)


@app.task
def sync_organizations():
    OrganizationSynchronizer().sync()


@app.task
def sync_offices():
    OfficeSynchronizer().sync()


@app.autoretry_task(max_retries=3)
@locked_task
def sync_staff():
    ServiceSynchronizer().sync()
    DepartmentSynchronizer().sync()
    UserSyncronizer().sync()
    DepartmentUserSyncronizer().sync()
    OrganizationSynchronizer().sync()
    OfficeSynchronizer().sync()
    PositionSynchronizer().sync()
    ProfessionSynchronizer().sync()
    GeographySynchronizer().sync()


@app.task
def sync_users():
    UserSyncronizer().sync()


@app.task
def sync_groups():
    ServiceSynchronizer().sync()
    DepartmentSynchronizer().sync()
    sync_department_users.delay()


@app.task
def sync_department_users():
    DepartmentUserSyncronizer().sync()


@app.task
def sync_services():
    ServiceSynchronizer().sync()


@app.task
def sync_departments():
    DepartmentSynchronizer().sync()


@app.autoretry_task(max_retries=3)
def give_aa_achievement(login, aa_type):
    if settings.AA_TYPE_TO_ACHIEVEMENT_ID.get(aa_type):
        AchievementsAPI().give(login, settings.AA_TYPE_TO_ACHIEVEMENT_ID[aa_type])


@app.autoretry_task(max_retries=3)
def take_away_aa_achievement(login, aa_type):
    if settings.AA_TYPE_TO_ACHIEVEMENT_ID.get(aa_type):
        AchievementsAPI().take_away(login, settings.AA_TYPE_TO_ACHIEVEMENT_ID[aa_type])


@app.autoretry_task(max_retries=3)
def give_interview_counter_achievement(login):
    give_interview_counter_achievements(logins=[login])


@app.autoretry_task(max_retries=3)
@locked_task
def sync_value_streams():
    ValueStreamSynchronizer().sync()


@app.autoretry_task(max_retries=3)
@locked_task
def sync_geographies():
    GeographySynchronizer().sync()


@app.autoretry_task(max_retries=3)
def give_approved_reference_counter_achievement(usernames):
    ApprovedReferenceAchievement(usernames=usernames).give_all()


@app.autoretry_task(max_retries=3)
def give_accepted_offer_reference_counter_achievement(offer_id):
    AcceptedOfferReferenceAchievement(offer_id=offer_id).give_all()
