from flask_babel import gettext
from wtforms import Form, StringField, PasswordField, validators, SelectField

from pritunl_dedicated.models.pritunl_dedicated import User


class LoginForm(Form):
    username = StringField(None, [validators.Length(min=3, max=35)])
    password = PasswordField(None, [validators.Length(min=3, max=35)])

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)
        self.user = None

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        user = User.query.filter_by(username=self.username.data)
        # email and password found and match
        if user is None:
            self.username.errors.append(gettext('Username was not found.'))
            return False

        message, state = user.check_password(self.password.data)
        if state is False:
            self.password.errors.append(message)
            return False

        self.user = user
        return True


class NewForm(Form):
    username = StringField(None, [validators.Length(min=3, max=35)])
    password = PasswordField(None, [validators.Length(min=3, max=35)])
    password_again = PasswordField(None, [validators.Length(min=3, max=35)])

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        username_exists = UserRepository.find_by_name(self.username.data)
        if username_exists:
            self.username.errors.append(gettext('Username %(username)s already exists.', username=self.username.data))
            return False

        if self.password.data != self.password_again.data:
            self.password_again.errors.append(gettext('Passwords do not match.'))
            return False

        return True


class EditForm(Form):
    password = PasswordField(None, [validators.Length(min=3, max=35), validators.Optional()])
    password_again = PasswordField(None, [validators.Length(min=3, max=35), validators.Optional()])
    layout_id = SelectField(None, [validators.DataRequired()], choices=[], coerce=int)

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        if self.password.data or self.password_again.data:
            if self.password.data != self.password_again.data:
                self.password_again.errors.append(gettext('Passwords do not match.'))
                return False

        return True