from hashlib import md5

from staff.celery_app import app
from staff.lib.tasks import LockedTask

from ..survey_email import send_mails
from ..notifications import send_welcome_mail
from ..password_reminder import password_reminder


@app.task(name='staff.person.tasks.email.SendSurveyMail')
class SendSurveyMail(LockedTask):
    def locked_run(self, *args, **kwargs):
        send_mails()


@app.task(name='staff.person.tasks.email.SendWelcomeMail')
class SendWelcomeMail(LockedTask):

    def get_lock_name(self, *args, **kwargs):
        person_ids = kwargs.get('person_ids', args and args[0])
        person_ids = ''.join((str(pk) for pk in sorted(person_ids)))
        hashed_ids = md5(person_ids.encode('utf-8')).hexdigest()
        return 'SendWelcomeMail_%s' % hashed_ids

    def locked_run(self, person_ids=None, *args, **kwargs):
        try:
            return send_welcome_mail(person_ids)
        except Exception as exc:
            self.retry(countdown=600, exc=exc)


@app.task(name='staff.person.tasks.email.PasswordReminderMail')
class PasswordReminderMail(LockedTask):
    def locked_run(self, person_logins=None):
        password_reminder(person_logins)
