from django import forms
from django.contrib.auth.forms import AuthenticationForm,UserCreationForm
from django.contrib.auth.models import User
from .models import Branch,Profile,Category,Product

class StyledAuthenticationForm(AuthenticationForm):
    username=forms.CharField(label='نام کاربری',widget=forms.TextInput(attrs={'autofocus':True,'placeholder':'نام کاربری'}))
    password=forms.CharField(label='رمز عبور',widget=forms.PasswordInput(attrs={'placeholder':'رمز عبور'}))

class UserCreateForm(UserCreationForm):
    first_name=forms.CharField(label='نام نمایشی',max_length=70,required=False)
    role=forms.ChoiceField(label='نقش',choices=Profile.ROLES)
    branch=forms.ModelChoiceField(label='شعبه',queryset=Branch.objects.filter(active=True),required=False)
    class Meta:
        model=User
        fields=('username','first_name','password1','password2')
    def clean(self):
        data=super().clean()
        if data.get('role')=='branch' and not data.get('branch'):
            self.add_error('branch','برای مدیر شعبه، شعبه را انتخاب کنید.')
        if data.get('role')=='branch' and data.get('branch') and data['branch'].is_workshop:
            self.add_error('branch','برای مدیر شعبه، شعبه فروش را انتخاب کنید.')
        return data
    def save(self,commit=True):
        user=super().save(commit=False)
        user.first_name=self.cleaned_data.get('first_name','')
        if commit:
            user.save()
            Profile.objects.update_or_create(user=user,defaults={'role':self.cleaned_data['role'],'branch':self.cleaned_data.get('branch')})
        return user

class BranchForm(forms.ModelForm):
    class Meta:
        model=Branch
        fields=('name','is_workshop','active')

class CategoryForm(forms.ModelForm):
    class Meta:
        model=Category
        fields=('name','slug','parent','supplier','order_note','position','active')
    def clean_parent(self):
        parent=self.cleaned_data.get('parent')
        if self.instance.pk and parent and (parent.pk==self.instance.pk or parent.parent_id==self.instance.pk):
            raise forms.ValidationError('دسته را نمی‌توان زیرمجموعه خودش قرار داد.')
        return parent

class ProductForm(forms.ModelForm):
    class Meta:
        model=Product
        fields=('category','name','unit','minimum','estimated_price','note','active')

class UserEditForm(forms.Form):
    first_name=forms.CharField(label='نام نمایشی',max_length=70,required=False)
    role=forms.ChoiceField(label='نقش',choices=Profile.ROLES)
    branch=forms.ModelChoiceField(label='شعبه',queryset=Branch.objects.filter(active=True),required=False)
    is_active=forms.BooleanField(label='حساب فعال باشد',required=False)
    new_password=forms.CharField(label='رمز جدید (اختیاری)',required=False,widget=forms.PasswordInput(render_value=False),help_text='اگر نمی‌خواهید رمز عوض شود خالی بگذارید. حداقل ۱۰ کاراکتر.')
    def __init__(self,*args,user_obj=None,**kwargs):
        self.user_obj=user_obj
        if user_obj and 'initial' not in kwargs:
            try:profile=user_obj.samshaf_profile
            except Profile.DoesNotExist:profile=None
            kwargs['initial']={'first_name':user_obj.first_name,'role':profile.role if profile else ('admin' if user_obj.is_superuser else 'branch'),'branch':profile.branch if profile else None,'is_active':user_obj.is_active}
        super().__init__(*args,**kwargs)
    def clean(self):
        data=super().clean()
        if data.get('role')=='branch' and not data.get('branch'):self.add_error('branch','برای مدیر شعبه، شعبه الزامی است.')
        if data.get('role')=='branch' and data.get('branch') and data['branch'].is_workshop:self.add_error('branch','شعبه فروش را انتخاب کنید.')
        if self.user_obj and self.user_obj.is_superuser and data.get('role')!='admin':self.add_error('role','نقش سوپریوزر را از این فرم تغییر ندهید.')
        if data.get('new_password'):
            from django.contrib.auth.password_validation import validate_password
            validate_password(data['new_password'],user=self.user_obj)
        return data
    def save(self):
        user=self.user_obj
        user.first_name=self.cleaned_data['first_name']
        user.is_active=self.cleaned_data['is_active']
        if self.cleaned_data.get('new_password'):user.set_password(self.cleaned_data['new_password'])
        user.save()
        if not user.is_superuser:
            Profile.objects.update_or_create(user=user,defaults={'role':self.cleaned_data['role'],'branch':self.cleaned_data.get('branch')})
        return user
