import django_tables2 as tables
from django_tables2.utils import A

from generic.tables import BlockImageColumn, SeriesImageColumn

from .models import Long, LongSeries, UserAnswer

from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.db.models import Prefetch

from easy_thumbnails.files import get_thumbnailer

from easy_thumbnails.exceptions import InvalidImageFormatError


class LongTable(tables.Table):
    edit = tables.LinkColumn(
        "longs:long_update", text="Edit", args=[A("pk")], orderable=False
    )
    view = tables.LinkColumn(
        "longs:question_detail", text="View", args=[A("pk")], orderable=False
    )
    clone = tables.LinkColumn(
        "longs:long_clone", text="Clone", args=[A("pk")], orderable=False
    )
    delete = tables.LinkColumn(
        "longs:long_delete", text="Delete", args=[A("pk")], orderable=False
    )
    series = BlockImageColumn("Images", orderable=False)

    # series = tables.ManyToManyColumn(verbose_name="Exams")
    exams = tables.ManyToManyColumn(verbose_name="Exams")

    selection = tables.CheckBoxColumn(accessor="pk", orderable=False)

    class Meta:
        model = Long
        template_name = "django_tables2/bootstrap4.html"
        fields = ("description", "history", "created_date", "author")
        sequence = ("view", "series", "exams")

    def __init__(self, data=None, *args, **kwargs):
        super().__init__(
            data.prefetch_related(
                "series",
                "author",
                "exams",
                "series__images",
                "series__examination",
                "series__plane",
                "series__contrast",
            ),
            *args,
            **kwargs,
        )


class PopupLinkColumn(tables.Column):
    def render(self, value):
        return format_html("<span>test: {}<span>", value)
        obj = value.first()

        if obj is None:
            return mark_safe("<span>No image</span>")

        return obj.get_thumbnail()[0]


class LongSeriesTable(tables.Table):
    edit = tables.LinkColumn(
        "longs:long_series_update", text="Edit", args=[A("pk")], orderable=False
    )
    view = tables.LinkColumn(
        "longs:series_detail", text="View", args=[A("pk")], orderable=False
    )
    popup = tables.Column(empty_values=(), orderable=False)

    images = SeriesImageColumn("Images", orderable=False)

    delete = tables.LinkColumn(
        "longs:long_series_delete", text="Delete", args=[A("pk")], orderable=False
    )
    selection = tables.CheckBoxColumn(accessor="pk", orderable=False)

    long = tables.ManyToManyColumn(verbose_name="Question")

    class Meta:
        model = LongSeries
        template_name = "django_tables2/bootstrap4.html"
        fields = ("modality", "examination", "description", "author")
        sequence = ("view", "popup", "images", "long")

    def __init__(self, data=None, *args, **kwargs):
        super().__init__(
            data.prefetch_related(
                "long",
                "long__series",
                "images",
                "author",
                "examination",
                "plane",
                "contrast",
                "modality",
            ),
            *args,
            **kwargs,
        )

    def render_popup(self, value, record):
        print(self)
        return format_html(
            """<a href="#" onclick="return window.create_popup_window('/longs/series/{}', 'Series')" >Popup</a>""",
            record.pk,
        )


class UserAnswerTable(tables.Table):
    select = tables.CheckBoxColumn(accessor=("pk"))
    delete = tables.LinkColumn(
        "longs:user_answer_delete", text="Delete", args=[A("pk")], orderable=False
    )
    view = tables.LinkColumn(
        "longs:user_answer_view", text="View", args=[A("pk")], orderable=False
    )

    class Meta:
        model = UserAnswer
        template_name = "django_tables2/bootstrap4.html"
        fields = (
            "cid",
            "question",
            "score",
            # "normal",
            # "answer",
            # "answer_compare",
            "exam",
            "created",
            "updated",
        )

    def __init__(self, data=None, *args, **kwargs):
        super().__init__(
            data.prefetch_related(
                Prefetch(
                    "question",  # "question__exams"#, "author", "exams", "series__images", "series__examination", "series__plane", "series__contrast"
                    #queryset=Long.objects.select_related().prefetch_related(
                    #    Prefetch("exams")
                    #),
                )
            ),
            *args,
            **kwargs,
        )
