import importlib

from django.contrib import admin
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from async_tasks.models import AsyncTask


def re_run(modeladmin, request, queryset):
    for task in queryset:
        task.status_text = _("Re-running")
        task.status = AsyncTask.STATUS_CREATED
        task.save()
        module_path, function_name = task.handler.rsplit('.', 1)
        module = importlib.import_module(module_path)
        handler = getattr(module, function_name)
        handler.delay(task.pk)


re_run.short_description = _("Re-run task")


@admin.register(AsyncTask)
class AsyncTaskAdmin(admin.ModelAdmin):

    list_per_page = 100
    list_display = [
        'created', 'id', 'name', 'percent', 'status_cell'
    ]
    actions = [re_run]
    list_filter = ["status"]
    search_fields = ["name"]

    def status_cell(self, obj):

        text_color, bg_color = self._get_status_color(obj.status)

        styles = """
            color: %s;
            background-color: %s;
            padding: 2px;
            text-align: center;
        """ % (text_color, bg_color)

        status_text = obj.get_status_display()

        if obj.status_text:
            status_text += ": " + obj.status_text

        return mark_safe(
            f"<div style='{styles}'>"
            f"    {status_text}"
            f"</div>"
        )

    status_cell.short_description = _("Status")

    def _get_status_color(self, status):

        if status == AsyncTask.STATUS_CREATED:
            return "#333", "#c4cb5f"

        if status == AsyncTask.STATUS_PROCESSING:
            return "#fff", "#5fa3cb"

        if status == AsyncTask.STATUS_INLINE:
            return "#fff", "#cbb45f"

        if status == AsyncTask.STATUS_ERROR:
            return "#fff", "#f44336"

        if status == AsyncTask.STATUS_COMPLETED:
            return "#fff", "#5cb85c"

        return "#333", "#fff"
