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):
    description = forms.CharField(required=False)
    fragment = forms.CharField(required=False)
    tags = forms.CharField(widget=forms.Textarea, required=False)
    comment = forms.CharField(widget=forms.Textarea, required=False)

    class Meta:
        model = AnnotationRevision
        fields = ('title', 'description', 'fragment')
        widgets = {
            'fragment': forms.Textarea(),
            'tags': forms.Textarea()
        }

    def __init__(self, *args, **kwargs):
        super(AnnotationRevisionForm, self).__init__(*args, **kwargs)

    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 '[]'
