@admin_bp.route('/manage-user', methods=['GET', 'POST'])
@login_required
@operator_role_required
def manage_user():
    if (request.method == 'GET'):
        roles = Role.query.all()
        users = User.query.order_by(User.username).all()
        return render_template('admin_manage_user.html', users=users, roles=roles)
    if (request.method == 'POST'):
        try:
            jdata = request.json
            data = jdata['data']
            if (jdata['action'] == 'user_otp_disable'):
                user = User(username=data)
                result = user.update_profile(enable_otp=False)
                if result:
                    history = History(msg='Two factor authentication disabled for user {0}'.format(data), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'Two factor authentication has been disabled for user.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot disable two factor authentication for user.'}), 500)
            elif (jdata['action'] == 'delete_user'):
                user = User(username=data)
                if (user.username == current_user.username):
                    return make_response(jsonify({'status': 'error', 'msg': 'You cannot delete yourself.'}), 400)
                user_accounts = Account.query.join(AccountUser).join(User).filter((AccountUser.user_id == user.id), (AccountUser.account_id == Account.id)).all()
                for uc in user_accounts:
                    uc.revoke_privileges_by_id(user.id)
                result = user.delete()
                if result:
                    history = History(msg='Delete user {0}'.format(data), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'User has been removed.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot remove user.'}), 500)
            elif (jdata['action'] == 'revoke_user_privileges'):
                user = User(username=data)
                result = user.revoke_privilege()
                if result:
                    history = History(msg='Revoke {0} user privileges'.format(data), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'Revoked user privileges.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot revoke user privilege.'}), 500)
            elif (jdata['action'] == 'update_user_role'):
                username = data['username']
                role_name = data['role_name']
                if (username == current_user.username):
                    return make_response(jsonify({'status': 'error', 'msg': 'You cannot change you own roles.'}), 400)
                user = User.query.filter((User.username == username)).first()
                if (not user):
                    return make_response(jsonify({'status': 'error', 'msg': 'User does not exist.'}), 404)
                if ((user.role.name == 'Administrator') and (current_user.role.name != 'Administrator')):
                    return make_response(jsonify({'status': 'error', 'msg': 'You do not have permission to change Administrator users role.'}), 400)
                if ((role_name == 'Administrator') and (current_user.role.name != 'Administrator')):
                    return make_response(jsonify({'status': 'error', 'msg': 'You do not have permission to promote a user to Administrator role.'}), 400)
                user = User(username=username)
                result = user.set_role(role_name)
                if result['status']:
                    history = History(msg='Change user role of {0} to {1}'.format(username, role_name), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'Changed user role successfully.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot change user role. {0}'.format(result['msg'])}), 500)
            else:
                return make_response(jsonify({'status': 'error', 'msg': 'Action not supported.'}), 400)
        except Exception as e:
            current_app.logger.error('Cannot update user. Error: {0}'.format(e))
            current_app.logger.debug(traceback.format_exc())
            return make_response(jsonify({'status': 'error', 'msg': 'There is something wrong, please contact Administrator.'}), 400)
@admin_bp.route('/manage-user', methods=['GET', 'POST'])
@login_required
@operator_role_required
def manage_user():
    if (request.method == 'GET'):
        roles = Role.query.all()
        users = User.query.order_by(User.username).all()
        return render_template('admin_manage_user.html', users=users, roles=roles)
    if (request.method == 'POST'):
        try:
            jdata = request.json
            data = jdata['data']
            if (jdata['action'] == 'user_otp_disable'):
                user = User(username=data)
                result = user.update_profile(enable_otp=False)
                if result:
                    history = History(msg='Two factor authentication disabled for user {0}'.format(data), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'Two factor authentication has been disabled for user.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot disable two factor authentication for user.'}), 500)
            elif (jdata['action'] == 'delete_user'):
                user = User(username=data)
                if (user.username == current_user.username):
                    return make_response(jsonify({'status': 'error', 'msg': 'You cannot delete yourself.'}), 400)
                user_accounts = Account.query.join(AccountUser).join(User).filter((AccountUser.user_id == user.id), (AccountUser.account_id == Account.id)).all()
                for uc in user_accounts:
                    uc.revoke_privileges_by_id(user.id)
                result = user.delete()
                if result:
                    history = History(msg='Delete user {0}'.format(data), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'User has been removed.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot remove user.'}), 500)
            elif (jdata['action'] == 'revoke_user_privileges'):
                user = User(username=data)
                result = user.revoke_privilege()
                if result:
                    history = History(msg='Revoke {0} user privileges'.format(data), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'Revoked user privileges.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot revoke user privilege.'}), 500)
            elif (jdata['action'] == 'update_user_role'):
                username = data['username']
                role_name = data['role_name']
                if (username == current_user.username):
                    return make_response(jsonify({'status': 'error', 'msg': 'You cannot change you own roles.'}), 400)
                user = User.query.filter((User.username == username)).first()
                if (not user):
                    return make_response(jsonify({'status': 'error', 'msg': 'User does not exist.'}), 404)
                if ((user.role.name == 'Administrator') and (current_user.role.name != 'Administrator')):
                    return make_response(jsonify({'status': 'error', 'msg': 'You do not have permission to change Administrator users role.'}), 400)
                if ((role_name == 'Administrator') and (current_user.role.name != 'Administrator')):
                    return make_response(jsonify({'status': 'error', 'msg': 'You do not have permission to promote a user to Administrator role.'}), 400)
                user = User(username=username)
                result = user.set_role(role_name)
                if result['status']:
                    history = History(msg='Change user role of {0} to {1}'.format(username, role_name), created_by=current_user.username)
                    history.add()
                    return make_response(jsonify({'status': 'ok', 'msg': 'Changed user role successfully.'}), 200)
                else:
                    return make_response(jsonify({'status': 'error', 'msg': 'Cannot change user role. {0}'.format(result['msg'])}), 500)
            else:
                return make_response(jsonify({'status': 'error', 'msg': 'Action not supported.'}), 400)
        except Exception as e:
            current_app.logger.error('Cannot update user. Error: {0}'.format(e))
            current_app.logger.debug(traceback.format_exc())
            return make_response(jsonify({'status': 'error', 'msg': 'There is something wrong, please contact Administrator.'}), 400)