import os

from django.db import models
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _


class AsyncTask(models.Model):

    STATUS_CREATED = 'created'
    STATUS_PROCESSING = 'processing'
    STATUS_INLINE = 'inline'
    STATUS_ERROR = 'error'
    STATUS_COMPLETED = 'completed'

    STATUS_CHOICES = (
        (STATUS_CREATED, _('Created')),
        (STATUS_PROCESSING, _('Processing')),
        (STATUS_INLINE, _('Waiting in line')),
        (STATUS_ERROR, _('Error')),
        (STATUS_COMPLETED, _('Completed')),
    )

    name = models.CharField(_("Task name"), max_length=255)

    handler = models.CharField(_("Task handler"), max_length=255)

    file = models.FileField(
        _('File'),
        upload_to='async_tasks',
        blank=True,
        null=True
    )

    created = models.DateTimeField(
        _('Creation date'),
        auto_now_add=True)

    status = models.CharField(
        _('Status'),
        max_length=255,
        choices=STATUS_CHOICES,
        default=STATUS_CREATED)

    status_text = models.CharField(
        _('Status'),
        max_length=255,
        blank=True)

    percent = models.CharField(_('Percent'), max_length=10, blank=True)

    params = models.JSONField(_("Params"), blank=True, null=True)

    def __str__(self):
        return str(self.created)

    @property
    def filename(self):
        return os.path.basename(self.file.name)

    @property
    def status_url(self):
        return reverse_lazy('async-tasks:status', args=[self.pk])

    def update(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

        self.save(update_fields=kwargs.keys())

    class Meta:
        ordering = ['-created']
        verbose_name = _('Async task')
        verbose_name_plural = _('Async tasks')
