from django import forms
from .models import License
from django.db.models import Q
from django.contrib.auth.models import User
from health_view.models import Permission

class CreateLicenseForm(forms.ModelForm):
    class Meta:
        model = License
        fields = ('patient', 'justified', 'exp_date', 'folder_parts', 'permissions', 'signature',)

    def __init__(self, current_user, *args, **kwargs):
        super(CreateLicenseForm, self).__init__(*args, **kwargs)
        license = License.objects.filter(justified=current_user).order_by('patient')
        conditions = Q(id='0')
        for li in license:
            print(li.patient_id)
            conditions |= Q(id=li.patient_id)
        self.fields['permissions'] = forms.ModelMultipleChoiceField(queryset=Permission.objects.all())
        if License.objects.filter(justified=current_user).exists() and License.objects.filter(license_creator=current_user).exists():
            self.fields['patient'].queryset = User.objects.filter(conditions).distinct()
        elif License.objects.filter(justified=current_user).exists():
            conditions |= Q(username=current_user.username)
            self.fields['patient'].queryset = User.objects.filter(conditions).distinct()
        elif License.objects.filter(license_creator=current_user).exists():
            self.fields['patient'].queryset = User.objects.filter(username="-")
        else:
            self.fields['patient'].queryset = User.objects.filter(username=current_user.username)


class CreateLicenseForm_filled(forms.Form):
    patient = forms.CharField()
    justified = forms.CharField()
    license_creator = forms.CharField()
    exp_date = forms.CharField()
    folder_parts = forms.CharField()
    permissions = forms.CharField()
    signature = forms.CharField()
