import os
import tempfile

from shared.forms import JekyllImportForm as SharedJekyllImportForm
from shared.forms import ArticlesPageForm as SharedArticlesPageForm

from .tasks import import_jekyll_articles


class JekyllImportForm(SharedJekyllImportForm):
    def handle_import(self):
        lock_file_name = os.path.join(
            tempfile.gettempdir(), f".{self.instance.id}.articles-import-lock"
        )

        if os.path.isfile(lock_file_name):
            return

        open(lock_file_name, "w").close()

        import_jekyll_articles.delay(
            article_parent_page_id=self.instance.id,
            collection_id=self.cleaned_data["collection"].id,
            url=self.cleaned_data["jekyll_repo_url"],
            dry_run=self.cleaned_data["dry_run"],
            use_git=True,
        )


class ElectionsArticlesPageForm(SharedArticlesPageForm, JekyllImportForm):
    def __init__(self, *args, **kwargs):
        from .models import ElectionsArticleTag
        from shared.models import SharedTag

        super().__init__(*args, **kwargs)

        self.fields["shared_tags"].queryset = SharedTag.objects.order_by("name")

        if self.instance.pk:
            valid_tag_ids = ElectionsArticleTag.objects.filter(
                content_object__in=self.instance.get_children().specific()
            ).values_list('tag_id', flat=True).distinct()
            
            self.fields['displayed_tags'].queryset = ElectionsArticleTag.objects.filter(id__in=valid_tag_ids).order_by("tag__name")