import web
import re
from decorators import i18n
from model import User

def unique_username(i):
    query = web.ctx.orm.query(User).filter(User.name == i.username)
    return query.count() == 0

class CreateUserView:
    form = web.form.Form(
        web.form.Textbox('username', description=_('Username (3 to 60 alfanumeric chars)')),
        web.form.Password('password', description=_('Password (7 or more characters)')),
        web.form.Password('password2', description=_('Repeat Password')),
        web.form.Textbox('email', description=_('Email')),
        web.form.Button('submit', type='submit', value=_('Register')),
        validators = [
            web.form.Validator(_('Passwords did\'t match'),
                lambda i: i.password == i.password2),

            web.form.Validator(_('Password shorter than 7 characters'),
                lambda i: len(i.password) >= 7),

            web.form.Validator(_('Username length should be from 3 to 60 characters'),
                lambda i: len(i.username) >= 3 or len(i.username) <= 60),

            web.form.Validator(_('Invalid username'),
                lambda i: re.compile("^\w+$").match(i.username)),

            web.form.Validator(_('Email too long'),
                lambda i: len(i.email) <= 250),

            web.form.Validator(_('Invalid email'),
                lambda i: re.compile("^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$").match(i.email)),

            web.form.Validator(_('Username already exists'),
                unique_username)
            ])

    @i18n
    def GET(self):
        return web.ctx.render.user.create(self.form)

    def POST(self):
        if not self.form.validates():
            return web.ctx.render.user.create(self.form)

        # register the user
        new_user = User(
            name = web.input().username,
            password = web.input().password,
            email = web.input().email)
        web.ctx.orm.add(new_user)
        new_user.send_activation_mail()
        web.ctx.notify(_('User %s registered successfully, check your email to activate it') % web.input().username, 'notification')


        raise web.seeother('/')

