from django import forms
from iconolab.models import AnnotationRevision
import json, logging

logger = logging.getLogger(__name__)

class MultipleTagsField(forms.TypedMultipleChoiceField):
    pass

class AnnotationRevisionForm(forms.ModelForm):
    tags = forms.CharField()
    comment = forms.CharField(widget=forms.Textarea)
    
    class Meta:
        model = AnnotationRevision
        fields = ('title', 'description', 'fragment')
        widgets = {
            'fragment': forms.HiddenInput(),
            'tags': forms.HiddenInput()
        }
        
    def __init__(self, *args, **kwargs):
        super(AnnotationRevisionForm, self).__init__(*args, **kwargs)
        for key in self.fields:
            if key != "comment":
                self.fields[key].required = False
        
    def clean(self, *args, **kwargs):
        cleaned_data = super(AnnotationRevisionForm, self).clean(*args, **kwargs)
        if not (cleaned_data.get("title", "") or cleaned_data.get("description", "") or json.loads(cleaned_data.get("tags", "[]"))):
            raise forms.ValidationError("Au moins un de ces champs doit être renseigné: description, titre ou mot-clé", code="missing_fields")
    
    def tags_json(self):
        if self.instance:
            tags_list = []
            for tag_info in self.instance.tagginginfo_set.all():
                tags_list.append({
                    'tag_input': tag_info.tag.link,
                    'relevancy': tag_info.relevancy,
                    'accuracy': tag_info.accuracy
                })
            return json.dumps(tags_list)
        else:
            return '[]' 