# -*- python -*-
# -*- coding: utf-8 -*-
#
# Debian Member Portfolio Service views
#
# Copyright © 2015-2022 Jan Dittberner <jan@dittberner.info>
#
# This file is part of the Debian Member Portfolio Service.
#
# Debian Member Portfolio Service is free software: you can redistribute it
# and/or modify it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Debian Member Portfolio Service is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
from __future__ import unicode_literals

from flask_babel import gettext as _
from flask_wtf import FlaskForm
from wtforms import IntegerField, StringField, RadioField
from wtforms.validators import (
    AnyOf, DataRequired, Email, Length, Optional, Regexp
)
from string import hexdigits


class FingerPrint(Regexp):
    def __init__(self, **kwargs):
        super(FingerPrint, self).__init__(r'^[a-fA-F0-9]*$', **kwargs)


class PlainText(Regexp):
    def __init__(self):
        super(PlainText, self).__init__(r'^[a-zA-Z\-0-9]*$')


def gpg_fingerprint(data):
    if data is not None:
        return "".join([
            char for char in str(data) if char.lower() in hexdigits])
    return data


class DeveloperData(FlaskForm):
    email = StringField('email', validators=[DataRequired(), Email()])
    name = StringField('name', validators=[Optional(), DataRequired()])
    openpgpfp = StringField('openpgpfp', filters=[gpg_fingerprint], validators=[
        Optional(), FingerPrint(), Length(min=32, max=40)
    ])
    username = StringField('username', validators=[Optional(), PlainText()])
    nonddemail = StringField('nonddemail', validators=[Optional(), Email()])
    salsausername = StringField('salsausername', validators=[
        Optional(), PlainText()
    ])
    mode = RadioField(
        'mode', default='html', choices=[
            ('json', _('JSON')), ('html', _('HTML'))
        ], validators=[AnyOf(['json', 'html'])]
    )
    forumsid = IntegerField('forumsid', default=None, validators=[Optional()])
    wikihomepage = StringField('wikihomepage', default=None, validators=[
        Optional()])


class DeveloperDataRequest(FlaskForm):
    email = StringField('email', validators=[DataRequired(), Email()])