from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django_better_admin_arrayfield.models.fields import ArrayField


class RecurrentImport(models.Model):
    class Meta:
        verbose_name = _("Recurrent import")
        verbose_name_plural = _("Recurrent imports")
        permissions = [("run_recurrentimport", "Can run a recurrent import")]

    class PROCESSOR(models.TextChoices):
        ICAL = "ical", _("ical")
        ICALNOBUSY = "icalnobusy", _("ical no busy")
        ICALNOVC = "icalnovc", _("ical no VC")
        ICALNAIVETZ = "ical naive tz", _("ical naive timezone")
        LACOOPE = "lacoope", _("lacoope.org")
        LACOMEDIE = "lacomedie", _("la comédie")
        LEFOTOMAT = "lefotomat", _("le fotomat")
        LAPUCEALOREILLE = "lapucealoreille", _("la puce à l'oreille")
        MECWORDPRESS = "Plugin wordpress MEC", _("Plugin wordpress MEC")
        FBEVENTS = "Facebook events", _("Événements d'une page FB")
        BILLETTERIECF = "Billetterie CF", _("Billetterie Clermont-Ferrand")
        ARACHNEE = "arachnee", _("Arachnée concert")
        LERIO = "rio", _("Le Rio")
        LARAYMONDE = "raymonde", _("La Raymonde")
        APIDAE = "apidae", _("Agenda apidae tourisme")
        IGUANA = "iguana", _("Agenda iguana (médiathèques)")
        MILLEFORMES = "Mille formes", _("Mille formes")
        AMISCERISES = "Amis cerises", _("Les Amis du Temps des Cerises")
        MOBILIZON = "Mobilizon", _("Mobilizon")
        LECAMELEON = "Le Caméléon", _("Le caméléon")
        ECHOSCIENCES = "Echosciences", _("Echosciences")
        HELLOASSO = "HelloAsso", _("Hello Asso")

    class DOWNLOADER(models.TextChoices):
        SIMPLE = "simple", _("simple")
        CHROMIUMHEADLESS = "chromium headless", _("Headless Chromium")
        CHROMIUMHEADLESSPAUSE = (
            "chromium (pause)",
            _("Headless Chromium (pause)"),
        )

    class RECURRENCE(models.TextChoices):
        DAILY = (
            "daily",
            _("daily"),
        )
        WEEKLY = "weekly", _("weekly")
        NEVER = "never", _("never")

    name = models.CharField(
        verbose_name=_("Name"),
        help_text=_(
            "Recurrent import name. Be careful to choose a name that is easy to understand, as it will be public and displayed on the site"
            "s About page."
        ),
        max_length=512,
        default="",
    )
    processor = models.CharField(
        _("Processor"),
        max_length=20,
        choices=PROCESSOR.choices,
        default=PROCESSOR.ICAL,
    )
    downloader = models.CharField(
        _("Downloader"),
        max_length=20,
        choices=DOWNLOADER.choices,
        default=DOWNLOADER.SIMPLE,
    )

    recurrence = models.CharField(
        _("Import recurrence"),
        max_length=10,
        choices=RECURRENCE.choices,
        default=RECURRENCE.DAILY,
    )

    source = models.URLField(
        verbose_name=_("Source"),
        help_text=_("URL of the source document"),
        unique=True,
        max_length=1024,
    )
    browsable_url = models.URLField(
        verbose_name=_("Browsable url"),
        help_text=_(
            "URL of the corresponding document that will be shown to visitors."
        ),
        max_length=1024,
        blank=True,
        null=True,
    )

    defaultPublished = models.BooleanField(
        verbose_name=_("Published"),
        help_text=_("Status of each imported event (published or draft)"),
        default=True,
    )
    defaultLocation = models.CharField(
        verbose_name=_("Location"),
        help_text=_("Address for each imported event"),
        max_length=512,
        null=True,
        blank=True,
    )

    forceLocation = models.BooleanField(
        verbose_name=_("Force location"),
        help_text=_("force location even if another is detected."),
        default=False,
    )

    defaultOrganiser = models.ForeignKey(
        "Organisation",
        verbose_name=_("Organiser"),
        help_text=_("Organiser of each imported event"),
        default=None,
        null=True,
        blank=True,
        on_delete=models.SET_DEFAULT,
    )

    defaultCategory = models.ForeignKey(
        "Category",
        verbose_name=_("Category"),
        help_text=_("Category of each imported event"),
        default=None,
        null=True,
        blank=True,
        on_delete=models.SET_DEFAULT,
    )
    defaultTags = ArrayField(
        models.CharField(max_length=64),
        verbose_name=_("Tags for each imported event"),
        help_text=_("A list of tags that describe each imported event."),
        blank=True,
        null=True,
    )

    def __str__(self):
        return self.name

    def nb_imports(self):
        return BatchImportation.objects.filter(recurrentImport=self).count()

    def nb_events(self):
        from ..models.event import Event

        return Event.objects.filter(import_sources__contains=[self.source]).count()

    def get_absolute_url(self):
        return reverse("view_rimport", kwargs={"pk": self.pk})

    def last_import(self):
        events = BatchImportation.objects.filter(recurrentImport=self).order_by(
            "-created_date"
        )
        if events and len(events) > 0:
            return events[0]
        else:
            return None


class BatchImportation(models.Model):
    class STATUS(models.TextChoices):
        RUNNING = "running", _("Running")
        CANCELED = "canceled", _("Canceled")
        SUCCESS = "success", _("Success")
        FAILED = "failed", _("Failed")

    class Meta:
        verbose_name = _("Batch importation")
        verbose_name_plural = _("Batch importations")
        permissions = [("run_batchimportation", "Can run a batch importation")]
        indexes = [
            models.Index(fields=["created_date"]),
            models.Index(fields=["status"]),
            models.Index(fields=["created_date", "recurrentImport"]),
        ]

    created_date = models.DateTimeField(auto_now_add=True)

    recurrentImport = models.ForeignKey(
        RecurrentImport,
        verbose_name=_("Recurrent import"),
        help_text=_("Reference to the recurrent import processing"),
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        editable=False,
    )

    url_source = models.URLField(
        verbose_name=_("URL (if not recurrent import)"),
        help_text=_("Source URL if no RecurrentImport is associated."),
        max_length=1024,
        blank=True,
        null=True,
        editable=False,
    )

    status = models.CharField(
        _("Status"),
        max_length=20,
        choices=STATUS.choices,
        default=STATUS.RUNNING,
    )

    error_message = models.CharField(
        verbose_name=_("Error message"), max_length=512, blank=True, null=True
    )

    nb_initial = models.PositiveIntegerField(
        verbose_name=_("Number of collected events"), default=0
    )
    nb_imported = models.PositiveIntegerField(
        verbose_name=_("Number of imported events"), default=0
    )
    nb_updated = models.PositiveIntegerField(
        verbose_name=_("Number of updated events"), default=0
    )
    nb_removed = models.PositiveIntegerField(
        verbose_name=_("Number of removed events"), default=0
    )

    celery_id = models.CharField(max_length=128, default="")
