from django import forms
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.twitter import TWITTER_API_URL


class TwitterTimelineForm(CollectionRuleForm):
    screen_name = forms.CharField(
        max_length=255,
        label=_("Twitter profile name"),
        help_text=_("Profile name without hashtags"),
        required=True,
    )

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

        instance.type = RuleTypeChoices.twitter_timeline
        instance.timezone = str(pytz.utc)
        instance.url = f"{TWITTER_API_URL}/statuses/user_timeline.json?screen_name={instance.screen_name}&tweet_mode=extended"

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

        return instance

    class Meta:
        model = CollectionRule
        fields = ("name", "screen_name", "favicon", "category")
