from django import forms
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from templated_email import send_templated_mail

from .models import Post, Comment

NOTIFICATION_EMAIL_TEMPLATE = 'notification.html'


class CommentCreateForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = (
            'content_type',
            'object_id',
            'content',
        )
        labels = {
            'content': ''
        }
        widgets = {
            'content_type': forms.HiddenInput(),
            'object_id': forms.HiddenInput(),
            'content': forms.Textarea(attrs={
                'placeholder': 'Add your comment here, supports markdown'
            })
        }

    def send_notification(self, request):
        author = self.instance.author
        message = self.cleaned_data.get('content')
        post = Post.objects.get(pk=self.cleaned_data['object_id'])
        url = get_current_site(request).domain + post.get_absolute_url()
        recipients = list(post.recipients.all().values_list('email', flat=True))
        if author.email in recipients:
            recipients.remove(author.email)

        context = {
            'subject': post.title,
            'author': author,
            'message': message,
            'url': url
        }

        send_templated_mail(
            template_name=NOTIFICATION_EMAIL_TEMPLATE,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=recipients,
            context=context
        )


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            'title',
            'content',
            'recipients'
        ]
        labels = {
            'content': ''
        }
        widgets = {
            'recipients': forms.CheckboxSelectMultiple()
        }


class PostCreateForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            'title',
            'content',
            'recipients'
        ]
        labels = {
            'content': ''
        }
        widgets = {
            'recipients': forms.CheckboxSelectMultiple()
        }

    def send_notification(self, request, post):
        recipients = list(post.recipients.values_list('email', flat=True))
        url = get_current_site(request).domain + post.get_absolute_url()
        if post.author.email in recipients:
            recipients.remove(post.author.email)

        context = {
            'subject': post.title,
            'author': post.author,
            'message': post.content,
            'url': url
        }

        send_templated_mail(
            template_name=NOTIFICATION_EMAIL_TEMPLATE,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=recipients,
            context=context
        )
