from celery.task import periodic_task
from django.core.mail import send_mail
from ..models import Issue
from django.contrib.auth.models import User
from datetime import timedelta
from celery import task


@task
def issue_created(title):
    """
    Task to send an email notification after 12 mins when an issue is successfully created
    :param title:
    :return:
    """
    issue = Issue.objects.get(title=title)
    subject = 'Issue no. {}'.format(title)
    message = 'Dear {}. \n\n An Issue has been assigned to you.\n Issue: {}'.format(issue.assigned_to, issue.title)

    mail_sent = send_mail(subject, message, 'admin@sit.io', [User.email])
    return mail_sent


@periodic_task(run_every = timedelta(hours=24))
def issue_list_user():
    """
    Send a mail of all the list of issues assigned to a particular user every 24 hours.
    :return:
    """
    mail_to_send = []
    for i in User.first_name:
        issue_list = Issue.objects.get(created_by=i)
        subject = 'Current Number of issues assigned to you: {}'.format(len(issue_list))
        message = 'issue_list: {}'.format(issue_list)
        mail_to_send = send_mail(subject, message, 'admin.sit.io', [User.email])
    return mail_to_send
