@admin_bp.route('/history_table', methods=['GET', 'POST'])
@login_required
@history_access_required
def history_table():
    if (request.method == 'POST'):
        if (current_user.role.name != 'Administrator'):
            return make_response(jsonify({'status': 'error', 'msg': 'You do not have permission to remove history.'}), 401)
        h = History()
        result = h.remove_all()
        if result:
            history = History(msg='Remove all histories', 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': 'Can not remove histories.'}), 500)
    detailedHistories = []
    lim = int(Setting().get('max_history_records'))
    if (request.method == 'GET'):
        if (current_user.role.name in ['Administrator', 'Operator']):
            base_query = History.query
        else:
            base_query = db.session.query(History).join(Domain, (History.domain_id == Domain.id)).outerjoin(DomainUser, (Domain.id == DomainUser.domain_id)).outerjoin(Account, (Domain.account_id == Account.id)).outerjoin(AccountUser, (Account.id == AccountUser.account_id)).filter(db.or_((DomainUser.user_id == current_user.id), (AccountUser.user_id == current_user.id)))
        domain_name = (request.args.get('domain_name_filter') if ((request.args.get('domain_name_filter') != None) and (len(request.args.get('domain_name_filter')) != 0)) else None)
        account_name = (request.args.get('account_name_filter') if ((request.args.get('account_name_filter') != None) and (len(request.args.get('account_name_filter')) != 0)) else None)
        user_name = (request.args.get('auth_name_filter') if ((request.args.get('auth_name_filter') != None) and (len(request.args.get('auth_name_filter')) != 0)) else None)
        min_date = (request.args.get('min') if ((request.args.get('min') != None) and (len(request.args.get('min')) != 0)) else None)
        if (min_date != None):
            min_date = str((datetime.datetime.strptime(min_date, '%Y-%m-%d') - datetime.timedelta(days=1)))
        max_date = (request.args.get('max') if ((request.args.get('max') != None) and (len(request.args.get('max')) != 0)) else None)
        if (max_date != None):
            max_date = str((datetime.datetime.strptime(max_date, '%Y-%m-%d') + datetime.timedelta(days=1)))
        tzoffset = (request.args.get('tzoffset') if ((request.args.get('tzoffset') != None) and (len(request.args.get('tzoffset')) != 0)) else None)
        changed_by = (request.args.get('user_name_filter') if ((request.args.get('user_name_filter') != None) and (len(request.args.get('user_name_filter')) != 0)) else None)
        '\n\t\t\tAuth methods: LOCAL, Github OAuth, Azure OAuth, SAML, OIDC OAuth, Google OAuth\n\t\t'
        auth_methods = []
        if ((request.args.get('auth_local_only_checkbox') is None) and (request.args.get('auth_oauth_only_checkbox') is None) and (request.args.get('auth_saml_only_checkbox') is None) and (request.args.get('auth_all_checkbox') is None)):
            auth_methods = []
        if (request.args.get('auth_all_checkbox') == 'on'):
            auth_methods.append('')
        if (request.args.get('auth_local_only_checkbox') == 'on'):
            auth_methods.append('LOCAL')
        if (request.args.get('auth_oauth_only_checkbox') == 'on'):
            auth_methods.append('OAuth')
        if (request.args.get('auth_saml_only_checkbox') == 'on'):
            auth_methods.append('SAML')
        if (request.args.get('domain_changelog_only_checkbox') != None):
            changelog_only = (True if (request.args.get('domain_changelog_only_checkbox') == 'on') else False)
        else:
            changelog_only = False
        if ((user_name != None) and (current_user.role.name not in ['Administrator', 'Operator'])):
            histories = []
        elif (domain_name != None):
            if (not changelog_only):
                histories = base_query.filter(db.and_(db.or_((History.msg.like(('%domain ' + domain_name)) if (domain_name != '*') else History.msg.like('%domain%')), (History.msg.like((('%domain ' + domain_name) + ' access control')) if (domain_name != '*') else History.msg.like('%domain%access control'))), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
            else:
                histories = base_query.filter(db.and_((History.msg.like(('Apply record changes to domain ' + domain_name)) if (domain_name != '*') else History.msg.like('Apply record changes to domain%')), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif (account_name != None):
            if (current_user.role.name in ['Administrator', 'Operator']):
                histories = base_query.join(Domain, (History.domain_id == Domain.id)).outerjoin(Account, (Domain.account_id == Account.id)).filter(db.and_((Account.id == Domain.account_id), ((account_name == Account.name) if (account_name != '*') else True), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
            else:
                histories = base_query.filter(db.and_((Account.id == Domain.account_id), ((account_name == Account.name) if (account_name != '*') else True), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif ((user_name != None) and (current_user.role.name in ['Administrator', 'Operator'])):
            histories = History.query.filter(db.and_(db.or_((History.msg.like((('User ' + user_name) + ' authentication%')) if ((user_name != '*') and (user_name != None)) else History.msg.like('%authentication%')), (History.msg.like((('User ' + user_name) + ' was not authorized%')) if ((user_name != '*') and (user_name != None)) else History.msg.like('User%was not authorized%'))), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
            temp = []
            for h in histories:
                for method in auth_methods:
                    if (method in h.detail):
                        temp.append(h)
                        break
            histories = temp
        elif (((changed_by != None) or (max_date != None)) and (current_user.role.name in ['Administrator', 'Operator'])):
            histories = History.query.filter(db.and_(((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif ((changed_by != None) or (max_date != None)):
            histories = base_query.filter(db.and_(((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif (max_date != None):
            histories = base_query.filter(db.and_(((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif (current_user.role.name in ['Administrator', 'Operator']):
            histories = History.query.order_by(History.created_on.desc()).limit(lim).all()
        else:
            histories = db.session.query(History).join(Domain, (History.domain_id == Domain.id)).outerjoin(DomainUser, (Domain.id == DomainUser.domain_id)).outerjoin(Account, (Domain.account_id == Account.id)).outerjoin(AccountUser, (Account.id == AccountUser.account_id)).order_by(History.created_on.desc()).filter(db.or_((DomainUser.user_id == current_user.id), (AccountUser.user_id == current_user.id))).limit(lim).all()
        detailedHistories = convert_histories(histories)
        if (tzoffset != None):
            if (min_date != None):
                min_date_split = min_date.split()[0]
            if (max_date != None):
                max_date_split = max_date.split()[0]
            for (i, history_rec) in enumerate(detailedHistories):
                local_date = str(from_utc_to_local(int(tzoffset), history_rec.history.created_on).date())
                if (((min_date != None) and (local_date == min_date_split)) or ((max_date != None) and (local_date == max_date_split))):
                    detailedHistories[i] = None
        detailedHistories = [h for h in detailedHistories if (h is not None)]
        return render_template('admin_history_table.html', histories=detailedHistories, len_histories=len(detailedHistories), lim=lim)
@admin_bp.route('/history_table', methods=['GET', 'POST'])
@login_required
@history_access_required
def history_table():
    if (request.method == 'POST'):
        if (current_user.role.name != 'Administrator'):
            return make_response(jsonify({'status': 'error', 'msg': 'You do not have permission to remove history.'}), 401)
        h = History()
        result = h.remove_all()
        if result:
            history = History(msg='Remove all histories', 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': 'Can not remove histories.'}), 500)
    detailedHistories = []
    lim = int(Setting().get('max_history_records'))
    if (request.method == 'GET'):
        if (current_user.role.name in ['Administrator', 'Operator']):
            base_query = History.query
        else:
            base_query = db.session.query(History).join(Domain, (History.domain_id == Domain.id)).outerjoin(DomainUser, (Domain.id == DomainUser.domain_id)).outerjoin(Account, (Domain.account_id == Account.id)).outerjoin(AccountUser, (Account.id == AccountUser.account_id)).filter(db.or_((DomainUser.user_id == current_user.id), (AccountUser.user_id == current_user.id)))
        domain_name = (request.args.get('domain_name_filter') if ((request.args.get('domain_name_filter') != None) and (len(request.args.get('domain_name_filter')) != 0)) else None)
        account_name = (request.args.get('account_name_filter') if ((request.args.get('account_name_filter') != None) and (len(request.args.get('account_name_filter')) != 0)) else None)
        user_name = (request.args.get('auth_name_filter') if ((request.args.get('auth_name_filter') != None) and (len(request.args.get('auth_name_filter')) != 0)) else None)
        min_date = (request.args.get('min') if ((request.args.get('min') != None) and (len(request.args.get('min')) != 0)) else None)
        if (min_date != None):
            min_date = str((datetime.datetime.strptime(min_date, '%Y-%m-%d') - datetime.timedelta(days=1)))
        max_date = (request.args.get('max') if ((request.args.get('max') != None) and (len(request.args.get('max')) != 0)) else None)
        if (max_date != None):
            max_date = str((datetime.datetime.strptime(max_date, '%Y-%m-%d') + datetime.timedelta(days=1)))
        tzoffset = (request.args.get('tzoffset') if ((request.args.get('tzoffset') != None) and (len(request.args.get('tzoffset')) != 0)) else None)
        changed_by = (request.args.get('user_name_filter') if ((request.args.get('user_name_filter') != None) and (len(request.args.get('user_name_filter')) != 0)) else None)
        '\n\t\t\tAuth methods: LOCAL, Github OAuth, Azure OAuth, SAML, OIDC OAuth, Google OAuth\n\t\t'
        auth_methods = []
        if ((request.args.get('auth_local_only_checkbox') is None) and (request.args.get('auth_oauth_only_checkbox') is None) and (request.args.get('auth_saml_only_checkbox') is None) and (request.args.get('auth_all_checkbox') is None)):
            auth_methods = []
        if (request.args.get('auth_all_checkbox') == 'on'):
            auth_methods.append()
        if (request.args.get('auth_local_only_checkbox') == 'on'):
            auth_methods.append('LOCAL')
        if (request.args.get('auth_oauth_only_checkbox') == 'on'):
            auth_methods.append('OAuth')
        if (request.args.get('auth_saml_only_checkbox') == 'on'):
            auth_methods.append('SAML')
        if (request.args.get('domain_changelog_only_checkbox') != None):
            changelog_only = (True if (request.args.get('domain_changelog_only_checkbox') == 'on') else False)
        else:
            changelog_only = False
        if ((user_name != None) and (current_user.role.name not in ['Administrator', 'Operator'])):
            histories = []
        elif (domain_name != None):
            if (not changelog_only):
                histories = base_query.filter(db.and_(db.or_((History.msg.like(('%domain ' + domain_name)) if (domain_name != '*') else History.msg.like('%domain%')), (History.msg.like((('%domain ' + domain_name) + ' access control')) if (domain_name != '*') else History.msg.like('%domain%access control'))), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
            else:
                histories = base_query.filter(db.and_((History.msg.like(('Apply record changes to domain ' + domain_name)) if (domain_name != '*') else History.msg.like('Apply record changes to domain%')), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif (account_name != None):
            if (current_user.role.name in ['Administrator', 'Operator']):
                histories = base_query.join(Domain, (History.domain_id == Domain.id)).outerjoin(Account, (Domain.account_id == Account.id)).filter(db.and_((Account.id == Domain.account_id), ((account_name == Account.name) if (account_name != '*') else True), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
            else:
                histories = base_query.filter(db.and_((Account.id == Domain.account_id), ((account_name == Account.name) if (account_name != '*') else True), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif ((user_name != None) and (current_user.role.name in ['Administrator', 'Operator'])):
            histories = History.query.filter(db.and_(db.or_((History.msg.like((('User ' + user_name) + ' authentication%')) if ((user_name != '*') and (user_name != None)) else History.msg.like('%authentication%')), (History.msg.like((('User ' + user_name) + ' was not authorized%')) if ((user_name != '*') and (user_name != None)) else History.msg.like('User%was not authorized%'))), ((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
            temp = []
            for h in histories:
                for method in auth_methods:
                    if (method in h.detail):
                        temp.append(h)
                        break
            histories = temp
        elif (((changed_by != None) or (max_date != None)) and (current_user.role.name in ['Administrator', 'Operator'])):
            histories = History.query.filter(db.and_(((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif ((changed_by != None) or (max_date != None)):
            histories = base_query.filter(db.and_(((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True), ((History.created_by == changed_by) if (changed_by != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif (max_date != None):
            histories = base_query.filter(db.and_(((History.created_on <= max_date) if (max_date != None) else True), ((History.created_on >= min_date) if (min_date != None) else True))).order_by(History.created_on.desc()).limit(lim).all()
        elif (current_user.role.name in ['Administrator', 'Operator']):
            histories = History.query.order_by(History.created_on.desc()).limit(lim).all()
        else:
            histories = db.session.query(History).join(Domain, (History.domain_id == Domain.id)).outerjoin(DomainUser, (Domain.id == DomainUser.domain_id)).outerjoin(Account, (Domain.account_id == Account.id)).outerjoin(AccountUser, (Account.id == AccountUser.account_id)).order_by(History.created_on.desc()).filter(db.or_((DomainUser.user_id == current_user.id), (AccountUser.user_id == current_user.id))).limit(lim).all()
        detailedHistories = convert_histories(histories)
        if (tzoffset != None):
            if (min_date != None):
                min_date_split = min_date.split()[0]
            if (max_date != None):
                max_date_split = max_date.split()[0]
            for (i, history_rec) in enumerate(detailedHistories):
                local_date = str(from_utc_to_local(int(tzoffset), history_rec.history.created_on).date())
                if (((min_date != None) and (local_date == min_date_split)) or ((max_date != None) and (local_date == max_date_split))):
                    detailedHistories[i] = None
        detailedHistories = [h for h in detailedHistories if (h is not None)]
        return render_template('admin_history_table.html', histories=detailedHistories, len_histories=len(detailedHistories), lim=lim)