# SPDX-FileCopyrightText: 2017-present Tobias Kunze
# SPDX-License-Identifier: AGPL-3.0-only WITH LicenseRef-Pretalx-AGPL-3.0-Terms
#
# This file contains Apache-2.0 licensed contributions copyrighted by the following contributors:
# SPDX-FileContributor: Raphael Michel

from django import forms
from django.core.exceptions import ValidationError

from pretalx.common.forms.fields import NewPasswordConfirmationField, NewPasswordField
from pretalx.common.forms.renderers import InlineFormLabelRenderer, InlineFormRenderer
from pretalx.common.text.phrases import phrases
from pretalx.person.models import User


class ResetForm(forms.Form):
    default_renderer = InlineFormLabelRenderer

    login_email = forms.EmailField(
        max_length=60,
        label=phrases.base.enter_email,
        required=True,
    )

    def clean(self):
        data = super().clean()
        try:
            user = User.objects.get(email__iexact=data.get("login_email"))
        except User.DoesNotExist:
            user = None

        data["user"] = user
        return data


class RecoverForm(forms.Form):
    default_renderer = InlineFormRenderer

    password = NewPasswordField(label=phrases.base.new_password, required=False)
    password_repeat = NewPasswordConfirmationField(
        label=phrases.base.password_repeat,
        required=False,
        confirm_with="password",
    )

    def clean(self):
        data = super().clean()
        if data.get("password") != data.get("password_repeat"):
            self.add_error(
                "password_repeat", ValidationError(phrases.base.passwords_differ)
            )
        return data
