from django.conf import settings
from django.core.mail import send_mail
from django.db import models
from django.utils.text import gettext_lazy as _

from report.tasks import send_report_task
from utils.models import ProjectBaseMixin


class ReportManager(models.Manager):
    """Manager for model Report."""

    def make(self, source: int, category, url: str, description: str):
        """Make object."""
        obj = self.create(
            source=source,
            category=category,
            url=url,
            description=description
        )
        if settings.USE_CELERY:
            send_report_task.delay(obj.id)
        else:
            send_report_task(obj.id)
        return obj


class ReportQuerySet(models.QuerySet):
    """QuerySet for model Report."""

    def by_source(self, source: int):
        """Return QuerySet filtered by a source."""
        return self.filter(source=source)


class Report(ProjectBaseMixin):
    """Report model."""

    BACK_OFFICE = 0
    WEB = 1
    MOBILE = 2

    SOURCE_CHOICES = (
        (BACK_OFFICE, _('Back office')),
        (WEB, _('Web')),
        (MOBILE, _('Mobile')),
    )

    BUG = 0
    SUGGESTION_IMPROVEMENT = 1

    CATEGORY_CHOICES = (
        (BUG, _('Bug')),
        (SUGGESTION_IMPROVEMENT, _('Suggestion/improvement')),
    )

    source = models.PositiveSmallIntegerField(choices=SOURCE_CHOICES,
                                              verbose_name=_('source'))
    category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES,
                                                verbose_name=_('category'))
    url = models.URLField(verbose_name=_('URL'))
    description = models.TextField(verbose_name=_('description'))

    objects = ReportManager.from_queryset(ReportQuerySet)()

    class Meta:
        """Meta class."""
        verbose_name = _('Report')
        verbose_name_plural = _('Reports')

    def get_body_email_message(self):
        """Prepare the body of the email message"""
        return {
            'subject': self.get_category_display(),
            'message': str(self.description),
            'html_message': self.description,
            'from_email': settings.EMAIL_HOST_USER,
            'recipient_list': [settings.EMAIL_TECHNICAL_SUPPORT, ],
        }

    def send_email(self):
        """Send an email reset user password"""
        send_mail(**self.get_body_email_message())

