from django.utils.safestring import mark_safe
import django_tables2 as tables
from django_tables2.utils import A

from .models import Question, UserAnswer

from django.utils.html import format_html


class QuestionTable(tables.Table):
    # edit = tables.LinkColumn(
    #    "physics:physics_question_update", text="Edit", args=[A("pk")], orderable=False
    # )
    view = tables.LinkColumn(
        "physics:question_detail", text="View", args=[A("pk")], orderable=False
    )
    # delete = tables.LinkColumn(
    #    "physics:question_delete", text="Delete", args=[A("pk")], orderable=False
    # )
    exams = tables.ManyToManyColumn(verbose_name="Exams")

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

    stem = tables.Column()
    answers = tables.TemplateColumn(
        "<ol type='A'><li>{{ record.a|safe}} : {{ record.a_answer|safe}}</li><li>{{ record.b|safe}} : {{ record.b_answer|safe}}</li><li>{{ record.c|safe}} : {{ record.c_answer|safe}}</li><li>{{ record.d|safe}} : {{ record.d_answer|safe}}</li><li>{{ record.e|safe}} : {{ record.e_answer|safe}}</li></ol>"
    )
    feedback = tables.TemplateColumn(
        "<ol type='A'><li>{{ record.a_feedback|safe}}</li><li>{{ record.b_feedback|safe}}</li><li>{{ record.c_feedback|safe}}</li><li>{{ record.d_feedback|safe}}</li><li>{{ record.e_feedback|safe}}</li></ol>"
    )

    class Meta:
        model = Question
        template_name = "django_tables2/bootstrap4.html"
        fields = (
            # "stem",
            # "a_answer",
            # "b_answer",
            # "c_answer",
            # "d_answer",
            # "e_answer",
            # "best_answer",
            # "feedback",
            "created_date",
            "category",
            "author",
        )
        sequence = ("view", "stem", "answers", "exams")

    def __init__(self, data=None, *args, **kwargs):
        super().__init__(
            data.prefetch_related(
                "category", "author", "exams"
            ),
            *args,
            **kwargs,
        )

    def render_stem(self, value):
        return mark_safe(value)


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

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