# Path: project/user/handlers/user_handler.py
# class UserHandler:
# 
#     @classmethod
#     def login(cls, form):
#         """
#         Login user by giving "LoginForm" form and validate if username+password pair is valid
#         """
#         if not form.validate_on_submit():
#             flash.danger(u'Form is not valid.')
#             return False
# 
#         user = UserFinder.by_username(form.username.data)
#         if not user:
#             flash.danger(u'User {} does not exists.'.format(form.username.data))
#             return False
# 
#         if not check_password_hash(user.password, form.password.data):
#             flash.warning(u'Invalid Credentials. Please try again.')
#             return False
# 
#         LoginUserService(user).call()
#         return user
# 
#     @classmethod
#     def logout(cls):
#         """
#         Delete user session
#         """
#         return LogoutUserService().call()
# 
#     @classmethod
#     def register(cls, form):
#         """
#         Create new user by given "RegisterForm"
#         """
#         if not form.validate_on_submit():
#             flash.danger(u'Form is not valid.')
#             return False
# 
#         user = CreateUserService(form.username.data, form.password.data).call()
#         return LoginUserService(user).call()
# 
# Path: project/user/forms.py
# class LoginForm(FlaskForm):
#     username = StringField('Username', validators=[DataRequired()])
#     password = PasswordField('Password', validators=[DataRequired()])
# 
# class RegisterForm(FlaskForm):
#     username = StringField('Username', validators=[DataRequired()])
#     password = PasswordField('Password', validators=[DataRequired()])
#     confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# 
#     def validate_username(form, field):
#         username = field.data
# 
#         user = UserFinder.by_username(username)
#         if not user:
#             raise ValidationError("Username \"{}\" already exists. ".format(username))
#         return username
# 
# Path: project/utils/flash.py
# def flash(message, category='default'):
#     """
#     For the given message, if html is present, add bootstrap .alert-link class to all links
#     """
#     if message.startswith('<p>') and message.endswith('</p>'):
#         message = BeautifulSoup(message, "lxml")
#         for a in message.find_all("a"):
#             if not a.get('class'):
#                 a.attrs.update({'class': []})
#             a['class'].extend(ALERT_LINK_CLASS)
#         message = str(message)
# 
#     FLASH(message, category)


from flask import redirect, render_template, request, url_for, Blueprint
from flask_login import login_required, current_user
from project.user.handlers.user_handler import UserHandler
from project.user.forms import LoginForm, RegisterForm
from project.utils import flash

@user_blueprint.route('/sign-in/', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)

    if request.method == "POST":
        user = UserHandler.register(form)
        if user:
            flash.info('Welcome "{}".'.format(user.username))
            return redirect(request.args.get('next', url_for('app.home')))

    return render_template('user/register.html', form=form)


@user_blueprint.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)

    if request.method == "POST":
        user = UserHandler.login(form)
        if user:
            flash.info('Welcome "{}".'.format(user.username))
            return redirect(request.args.get('next', url_for('app.home')))

    return render_template('user/login.html', form=form)


@user_blueprint.route('/logout/')
@login_required
def logout():

# Path: project/user/handlers/user_handler.py
# class UserHandler:
# 
#     @classmethod
#     def login(cls, form):
#         """
#         Login user by giving "LoginForm" form and validate if username+password pair is valid
#         """
#         if not form.validate_on_submit():
#             flash.danger(u'Form is not valid.')
#             return False
# 
#         user = UserFinder.by_username(form.username.data)
#         if not user:
#             flash.danger(u'User {} does not exists.'.format(form.username.data))
#             return False
# 
#         if not check_password_hash(user.password, form.password.data):
#             flash.warning(u'Invalid Credentials. Please try again.')
#             return False
# 
#         LoginUserService(user).call()
#         return user
# 
#     @classmethod
#     def logout(cls):
#         """
#         Delete user session
#         """
#         return LogoutUserService().call()
# 
#     @classmethod
#     def register(cls, form):
#         """
#         Create new user by given "RegisterForm"
#         """
#         if not form.validate_on_submit():
#             flash.danger(u'Form is not valid.')
#             return False
# 
#         user = CreateUserService(form.username.data, form.password.data).call()
#         return LoginUserService(user).call()
# 
# Path: project/user/forms.py
# class LoginForm(FlaskForm):
#     username = StringField('Username', validators=[DataRequired()])
#     password = PasswordField('Password', validators=[DataRequired()])
# 
# class RegisterForm(FlaskForm):
#     username = StringField('Username', validators=[DataRequired()])
#     password = PasswordField('Password', validators=[DataRequired()])
#     confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# 
#     def validate_username(form, field):
#         username = field.data
# 
#         user = UserFinder.by_username(username)
#         if not user:
#             raise ValidationError("Username \"{}\" already exists. ".format(username))
#         return username
# 
# Path: project/utils/flash.py
# def flash(message, category='default'):
#     """
#     For the given message, if html is present, add bootstrap .alert-link class to all links
#     """
#     if message.startswith('<p>') and message.endswith('</p>'):
#         message = BeautifulSoup(message, "lxml")
#         for a in message.find_all("a"):
#             if not a.get('class'):
#                 a.attrs.update({'class': []})
#             a['class'].extend(ALERT_LINK_CLASS)
#         message = str(message)
# 
#     FLASH(message, category)


# Path: project/user/views.py
from flask import redirect, render_template, request, url_for, Blueprint
from flask_login import login_required, current_user
from project.user.handlers.user_handler import UserHandler
from project.user.forms import LoginForm, RegisterForm
from project.utils import flash


@user_blueprint.route('/sign-in/', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)

    if request.method == "POST":
        user = UserHandler.register(form)
        if user:
            flash.info('Welcome "{}".'.format(user.username))
            return redirect(request.args.get('next', url_for('app.home')))

    return render_template('user/register.html', form=form)


@user_blueprint.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)

    if request.method == "POST":
        user = UserHandler.login(form)
        if user:
            flash.info('Welcome "{}".'.format(user.username))
            return redirect(request.args.get('next', url_for('app.home')))

    return render_template('user/login.html', form=form)


@user_blueprint.route('/logout/')
@login_required
def logout():

    UserHandler.logout()