from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.forms.widgets import HiddenInput, MultipleHiddenInput

User = get_user_model()

class LazyMultipleChoiceField(forms.MultipleChoiceField):
    
    def validate(self, value):
        pass    

class ShareForm(forms.ModelForm):
    read_list = LazyMultipleChoiceField(required=False, widget=MultipleHiddenInput())
    write_list = LazyMultipleChoiceField(required=False, widget=MultipleHiddenInput()) 
    share = forms.BooleanField(required=False, initial=False, widget=HiddenInput())

    def clean(self):
        super(ShareForm, self).clean()
        
        try: 
            read_list = self.data.getlist("read_list")
            write_list = self.data.getlist("write_list")
        except AttributeError:
            # This will be raised for content creation. As data is preprocessed, self.data
            # is a dict and not a querydict, so getlist won't work
            read_list = self.data.get('read_list', [])
            write_list = self.data.get('write_list', [])
        
        elems = read_list + write_list
        users = [e.split('-')[0] for e in elems if e.split('-')[1] == 'user' ]
        groups = [e.split('-')[0] for e in elems if e.split('-')[1] == 'group' ]
        
        users = User.objects.filter(id__in=users)
        groups = Group.objects.filter(id__in=groups)
        
        def create_real_lists(r_list, users, groups):
            new_list = []
            for e in r_list:
                obj_id, cls_name = e.split('-')
                if cls_name == 'user':
                    new_list.append(users.get(id=obj_id))
                elif cls_name == 'group':
                    new_list.append(groups.get(id=obj_id))
            return new_list
        
        new_read_list = create_real_lists(read_list, users, groups)        
        new_write_list = create_real_lists(write_list, users, groups)

        self.cleaned_data["read_list"] = new_read_list
        self.cleaned_data["write_list"] = new_write_list
        
        if self.data.get("share", False) == "True":
            self.cleaned_data["share"] = True
        else:
            self.cleaned_data["share"] = False
        return self.cleaned_data