import json

from django import forms


class TaskNotesWidget(forms.Widget):
    template_name = "tasks/task_notes_widget.html"

    class Media:
        js = ("tasks/task_notes.js",)

    def value_from_datadict(self, data, files, name):
        timestamps = data.getlist(f"{name}_timestamps")
        contents = data.getlist(f"{name}_contents")
        return {
            "timestamps": timestamps,
            "contents": contents,
        }

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        notes = {}
        if value:
            if isinstance(value, str):
                try:
                    notes = json.loads(value)
                except (json.JSONDecodeError, TypeError):
                    notes = {}
            elif isinstance(value, dict):
                notes = value
        context["widget"]["notes"] = notes
        return context


class TaskNotesField(forms.Field):
    widget = TaskNotesWidget

    def clean(self, value):
        if not value:
            return {}
        result = {}
        timestamps = value.get("timestamps", [])
        contents = value.get("contents", [])
        for i, ts in enumerate(timestamps):
            if i < len(contents) and ts and contents[i].strip():
                result[ts] = contents[i].strip()
        return result if result else {}
