from datetime import date
import logging

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist

from staff.preprofile.models import Preprofile
from staff.person.models.person import Staff

from staff.achievery.models import GivenAchievement, Achievement
from staff.achievery.utils import find_available_slot

logger = logging.getLogger(__name__)


def give_internship_achievement(preprofile: Preprofile):
    person = Staff.objects.get(login=preprofile.login)
    internship_achievement = (
        GivenAchievement.objects
        .filter(
            person=person,
            achievement_id=settings.ACHIEVEMENT_INTERN_ID,
            is_active=True,
        )
        .first()
    )
    comment = f'{preprofile.office.city.name}, {date.today().year}'
    comment_html = f'<p>{comment}</p>'
    if internship_achievement is None:
        try:
            achievement = Achievement.objects.get(id=settings.ACHIEVEMENT_INTERN_ID)
        except ObjectDoesNotExist:
            logger.error('Not found intern achievement by ID = %s', settings.ACHIEVEMENT_INTERN_ID)
            return

        slot = find_available_slot(person)
        GivenAchievement.objects.create(
            person=person,
            achievement=achievement,
            level=1,
            comment=comment,
            comment_html=comment_html,
            slot=slot,
        )
    else:
        internship_achievement.level += 1
        internship_achievement.comment += f'\n{comment}'
        internship_achievement.comment_html += f'{comment_html}'
        internship_achievement.save()
