from django import forms
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

import pytz

from newsreader.news.collection.choices import RuleTypeChoices
from newsreader.news.collection.forms.base import CollectionRuleForm
from newsreader.news.collection.models import CollectionRule
from newsreader.news.collection.reddit import REDDIT_API_URL


def get_reddit_help_text():
    return mark_safe(
        "Only subreddits are supported"
        " see the 'listings' section in <a className='link' target='_blank' rel='noopener noreferrer'"
        " href='https://www.reddit.com/dev/api#section_listings'>the reddit API docs</a>."
        " For example: <a className='link' target='_blank' rel='noopener noreferrer'"
        " href='https://oauth.reddit.com/r/aww'>https://oauth.reddit.com/r/aww</a>"
    )


class SubRedditForm(CollectionRuleForm):
    url = forms.URLField(max_length=1024, help_text=get_reddit_help_text)

    def clean_url(self):
        url = self.cleaned_data["url"]

        if not url.startswith(REDDIT_API_URL):
            raise ValidationError(_("This does not look like an Reddit API URL"))

        return url

    def save(self, commit=True):
        instance = super().save(commit=False)

        instance.type = RuleTypeChoices.subreddit
        instance.timezone = str(pytz.utc)

        if commit:
            instance.save()
            self.save_m2m()

        return instance

    class Meta:
        model = CollectionRule
        fields = (
            "name",
            "url",
            "favicon",
            "category",
            "reddit_allow_nfsw",
            "reddit_allow_spoiler",
            "reddit_allow_viewed",
            "reddit_upvotes_min",
            "reddit_downvotes_max",
            "reddit_comments_min",
        )
