from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser


class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ("username", "email", "grade")  # 필요에 따라 추가 필드 지정


class CustomUserChangeForm(UserChangeForm):
    password = forms.CharField(
        label="새 비밀번호",
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
    )
    password_confirm = forms.CharField(
        label="비밀번호 확인",
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
    )

    class Meta:
        model = CustomUser
        fields = [
            'email', 
            'nhnc_id', 
            'nhnc_api_tenant_id', 
            'url_gitea', 
            'url_harbor', 
            'url_argocd', 
            'url_web_ide', 
            'url_rancher', 
            'url_grafana', 
            'url_prometheus', 
            'url_opensearch', 
            'url_kiali',
            'url_nexus',
            'url_mattermost',
        ]

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        password_confirm = cleaned_data.get("password_confirm")

        if password and password != password_confirm:
            raise forms.ValidationError("비밀번호가 일치하지 않습니다.")
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data.get("password")
        if password:
            user.set_password(password)
        if commit:
            user.save()
        return user

class SSHKeyForm(forms.ModelForm):
    """SSH Private Key 관리 폼"""
    private_key = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 5,
            'placeholder': 'Enter your SSH Private Key',
        }),
        required=True,
        label="SSH Private Key"
    )

    class Meta:
        model = CustomUser
        fields = []  # 모델 필드는 직접 관리하므로 비움

    def save(self, commit=True):
        """SSH Private Key 암호화 후 저장"""
        user = self.instance
        private_key = self.cleaned_data['private_key']
        user.save_private_key(private_key)
        return user