# -*- coding: utf-8 -*-
from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, BooleanField, FileField,SelectField,\
    SubmitField
from wtforms.validators import Required, Length, Email, Regexp
from wtforms import ValidationError
from ..models import Role, User


class NameForm(Form):
    name = StringField(u'What is your name?', validators=[Required()])
    submit = SubmitField(u'提交')


class SearchForm(Form):
    keyword = StringField(u'搜索', validators=[Required()])


class EditProfileForm(Form):
    name = StringField(u'真实姓名', validators=[Length(0, 64)])
    location = StringField(u'地址', validators=[Length(0, 64)])
    about_me = TextAreaField(u'个性签名')
    submit = SubmitField(u'提交')


class EditProfileAdminForm(Form):
    email = StringField(u'Email', validators=[Required(), Length(1, 64),
                                             Email()])
    username = StringField(u'用户名', validators=[
        Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0,
                                          u'只支持字母数字符号')])
    confirmed = BooleanField(u'已验证')
    role = SelectField(u'角色', coerce=int)
    name = StringField(u'真实姓名', validators=[Length(0, 64)])
    location = StringField(u'地址', validators=[Length(0, 64)])
    about_me = TextAreaField(u'个性签名')
    submit = SubmitField(u'提交')

    def __init__(self, user, *args, **kwargs):
        super(EditProfileAdminForm, self).__init__(*args, **kwargs)
        self.role.choices = [(role.id, role.name)
                             for role in Role.query.order_by(Role.name).all()]
        self.user = user

    def validate_email(self, field):
        if field.data != self.user.email and \
                User.query.filter_by(email=field.data).first():
            raise ValidationError(u'邮箱已注册')

    def validate_username(self, field):
        if field.data != self.user.username and \
                User.query.filter_by(username=field.data).first():
            raise ValidationError(u'用户名已存在')


class QuestionForm(Form):
    body = StringField(u'问题标题（50字以内）', validators=[Required(u'请输入标题'), Length(0, 50, u'标题在20字范围内')])
    content = TextAreaField(u'问题描述', validators=[Required(u'具体描述')])
    submit = SubmitField(u'提问')


class ReplyForm(Form):
    body = TextAreaField(u'', validators=[Required()])
    submit = SubmitField(u'回答')


class CommentForm(Form):
    body = TextAreaField(u'', validators=[Required()])
    submit = SubmitField(u'评论')