from django import forms
from iconolab.models import Bookmark, BookmarkCategory
import json, logging

logger = logging.getLogger(__name__)

class BookmarkForm(forms.ModelForm):

    bookmark_category = forms.ChoiceField(required=False)
    bookmark_category_new = forms.CharField(required=False)

    class Meta:
        model = Bookmark
        fields = ('bookmark_category', 'bookmark_category_new')

    def __init__(self, *args, **kwargs):

        user = kwargs.pop('user', None)
        super(BookmarkForm, self).__init__(*args, **kwargs)

        if user.is_authenticated():

            self.user = user

            # Create the default category if not exists
            try:
                default_category = BookmarkCategory.objects.get(user=user, name='Favoris')
            except BookmarkCategory.DoesNotExist:
                default_category = BookmarkCategory(
                    user=user,
                    name='Favoris'
                )
                default_category.save()

            bookmark_categories = BookmarkCategory.objects.filter(user=user).all()
            choices = [(bookmark_category.id, bookmark_category.name) for bookmark_category in bookmark_categories]
            for choice in choices:
                self.fields['bookmark_category'].choices.append(choice)

    def clean(self, *args, **kwargs):
        cleaned_data = super(BookmarkForm, self).clean(*args, **kwargs)

        if cleaned_data['bookmark_category_new']:
            bookmark_category = BookmarkCategory(
                user=self.user,
                name=cleaned_data['bookmark_category_new']
            )
            bookmark_category.save()
        else:
            bookmark_category = BookmarkCategory.objects.get(id=cleaned_data['bookmark_category'])

        cleaned_data['category'] = bookmark_category
