import hashlib
from flask import request
from flask_wtf import FlaskForm
from flask_login import current_user
from flask_pagedown.fields import PageDownField
from wtforms import StringField, PasswordField, SubmitField, IntegerField, \
                    BooleanField, ValidationError, TextAreaField, RadioField
from wtforms.validators import DataRequired, Email, Length, EqualTo, NumberRange
from .models import User, db
from .email import send_email


class RegisterForm(FlaskForm):
    name = StringField('名字', validators=[DataRequired(), Length(3, 22)])
    email = StringField('邮箱', validators=[DataRequired(), 
            Email('无效邮箱')])
    password = PasswordField('密码', validators=[DataRequired(), Length(3, 22)])
    repeat_password = PasswordField('重复密码', validators=[DataRequired(),
                      EqualTo('password', message='密码不一致')])
    submit = SubmitField('提交')

    def validate_name(self, field):
        if not 'edit' in request.url and \
            User.query.filter_by(name=field.data).first():
            raise ValidationError('用户名已经被注册')

    def validate_email(self, field):
        if not 'edit' in request.url and \
            User.query.filter_by(email=field.data).first():
            raise ValidationError('邮箱已经被注册')

    def create_user(self):
        user = User()
        self.populate_obj(user)
        user.avatar_hash = hashlib.md5(user.email.encode('utf-8')).hexdigest()
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirm_token()
        send_email(user, self.email.data, 'confirm', token)


class LoginForm(FlaskForm):
    name_or_email = StringField('名字或邮箱', 
                    validators=[DataRequired(), Length(2, 22)])
    password = PasswordField('密码', validators=[DataRequired(), Length(6, 22)])
    remember_me = BooleanField('记住我')
    submit = SubmitField('提交')

    def validate_name_or_email(self, field):
        if not User.query.filter_by(name=field.data).first() and \
            not User.query.filter_by(email=field.data).first():
            raise ValidationError('用户名或邮箱不存在')

    def validate_password(self, field):
        user = User.query.filter_by(name=self.name_or_email.data).first()
        if not user:
            user = User.query.filter_by(name=self.name_or_email.data).first()
        if user and not user.check_password(field.data):
            raise ValidationError('密码错误')


class EditUserForm(FlaskForm):
    name = StringField('名字', validators=[DataRequired(), Length(3, 22)])
    age = IntegerField('年龄', validators=[NumberRange(min=1, max=120)])
    gender = RadioField('性别',
             choices=[('MALE', '男'), ('FEMALE', '女')], 
             default='男')
    location = StringField('所在城市')
    call_num = StringField('电话', validators=[Length(8, 11)])
    about_me = TextAreaField('自我介绍')
    submit = SubmitField('提交')

    def __init__(self, user, *args, **kw):
        super().__init__(*args, **kw)
        self.user = user

    def validate_name(self, field):
        user = User.query.filter_by(name=field.data).first()
        if user and user != self.user:
            print('user failed')
            raise ValidationError('该用户名已经存在')


class AdminEditUserForm(EditUserForm):
    '''
    role_id = RadioField(u'角色',
              choices=[(1, '普通用户'), (2, '协管员'), (3, '管理员')],
              default='普通用户')
    '''
    password = PasswordField('密码', validators=[DataRequired(), Length(3, 22)])
    repeat_password = PasswordField('重复密码', validators=[DataRequired(),
                      EqualTo('password', message='密码不一致')])
    submit = SubmitField('提交')

class ChangeEmailForm(FlaskForm):
    email = StringField('New Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Update Email Address')

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('Email already registered')


class ChangePasswordForm(FlaskForm):
    old_password = PasswordField('输入原密码以确定你的身份',
                   validators=[DataRequired()])
    password = PasswordField('新密码', validators=[DataRequired(),
               Length(5, 22)])
    repeat_password = PasswordField('重复新密码', validators=[DataRequired(),
                      EqualTo('password', message='Passwords must match.')])
    submit = SubmitField('Submit')

    def validate_old_password(self, field):
        if not current_user.check_password(field.data):
            raise ValidationError('原密码不正确')


class ResetPasswordRequestForm(FlaskForm):
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    submit = SubmitField('提交')

    def validate_email(self, field):
        if not User.query.filter_by(email=field.data).first():
            raise ValidationError('该邮箱未注册')


class ResetPasswordForm(FlaskForm):
    password = PasswordField('新密码', validators=[DataRequired(),
               Length(5, 22)])
    repeat_password = PasswordField('重复新密码', validators=[DataRequired(),
                      EqualTo('password', message='Passwords must match.')])
    submit = SubmitField('Submit')


class PostForm(FlaskForm):
    body = PageDownField('What\'s on your mind?', validators=[DataRequired()])
    submit = SubmitField('提交')

class CommentForm(FlaskForm):
    body = StringField('', validators=[DataRequired(), Length(5, 999)])
    submit = SubmitField('提交')
