# Buggy code
def search():
    query = request.args.get("query", "")
    page = int(request.args.get("page", 1))
    format = request.args.get("format", "")
    scan_ids = request.args.get("includeScanIDs", "")
    includeHistory = request.args.get("includeHistory", False)

    results_per_page = current_user.results_per_page
    if includeHistory:
        searchIndex = "nmap_history"
    else:
        searchIndex = "nmap"

    searchOffset = results_per_page * (page - 1)
    count, context = current_app.elastic.search(
        query, results_per_page, searchOffset, searchIndex=searchIndex
    )
    totalHosts = current_app.elastic.totalHosts()

    if includeHistory:
        next_url = (
            url_for(
                "main.search", query=query, page=page + 1, includeHistory=includeHistory
            )
            if count > page * results_per_page
            else None
        )
        prev_url = (
            url_for(
                "main.search", query=query, page=page - 1, includeHistory=includeHistory
            )
            if page > 1
            else None
        )
    else:
        next_url = (
            url_for("main.search", query=query, page=page + 1)
            if count > page * results_per_page
            else None
        )
        prev_url = (
            url_for("main.search", query=query, page=page - 1) if page > 1 else None
        )

    # what kind of output are we looking for?
    if format == "hostlist":
        hostlist = []
        for host in context:
            if scan_ids:
                hostlist.append(str(host["ip"]) + "," + str(host["scan_id"]))
            else:
                hostlist.append(str(host["ip"]))
        return Response("\n".join(hostlist), mimetype="text/plain")
    else:
        return render_template(
            "search.html",
            query=query,
            numresults=count,
            totalHosts=totalHosts,
            page=page,
            hosts=context,
            next_url=next_url,
            prev_url=prev_url,
        )


# Traceback (TypeError)
Nov 05 17:22:50 natlas-server bash[10026]: [2019-11-05 17:22:50,681] ERROR in app: Exception on /api/getwork [GET]
Nov 05 17:22:50 natlas-server bash[10026]: Traceback (most recent call last):
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
Nov 05 17:22:50 natlas-server bash[10026]:     response = self.full_dispatch_request()
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
Nov 05 17:22:50 natlas-server bash[10026]:     rv = self.handle_user_exception(e)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
Nov 05 17:22:50 natlas-server bash[10026]:     reraise(exc_type, exc_value, tb)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
Nov 05 17:22:50 natlas-server bash[10026]:     raise value
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
Nov 05 17:22:50 natlas-server bash[10026]:     rv = self.dispatch_request()
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
Nov 05 17:22:50 natlas-server bash[10026]:     return self.view_functions[rule.endpoint](**req.view_args)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/auth/wrappers.py", line 41, in decorated_function
Nov 05 17:22:50 natlas-server bash[10026]:     return f(*args, **kwargs)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/api/routes.py", line 70, in getwork
Nov 05 17:22:50 natlas-server bash[10026]:     count, context = current_app.elastic.gethost_scan_id(rand)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/elastic.py", line 238, in gethost_scan_id
Nov 05 17:22:50 natlas-server bash[10026]:     if not self.checkStatus():
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/elastic.py", line 60, in checkStatus
Nov 05 17:22:50 natlas-server bash[10026]:     if not self.attemptReconnect():
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/elastic.py", line 43, in attemptReconnect
Nov 05 17:22:50 natlas-server bash[10026]:     delta = now - self.lastReconnectAttempt
Nov 05 17:22:50 natlas-server bash[10026]: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType

# Fixed code
def search():
    """Return search results for a given query"""
    query = request.args.get("query", "")
    page = int(request.args.get("page", 1))
    format = request.args.get("format", "")
    scan_ids = request.args.get("includeScanIDs", "")
    includeHistory = request.args.get("includeHistory", False)

    results_per_page, search_offset = results_offset(page)

    searchIndex = "nmap_history" if includeHistory else "nmap"

    count, context = current_app.elastic.search(
        results_per_page, search_offset, query=query, searchIndex=searchIndex
    )
    totalHosts = current_app.elastic.total_hosts()

    if includeHistory:
        next_url, prev_url = build_pagination_urls(
            "main.search", page, count, query=query, includeHistory=includeHistory
        )
    else:
        next_url, prev_url = build_pagination_urls(
            "main.search", page, count, query=query
        )

    # what kind of output are we looking for?
    if format == "hostlist":
        hostlist = []
        for host in context:
            if scan_ids:
                hostlist.append(str(host["ip"]) + "," + str(host["scan_id"]))
            else:
                hostlist.append(str(host["ip"]))
        return Response("\n".join(hostlist), mimetype="text/plain")
    else:
        return render_template(
            "main/search.html",
            query=query,
            numresults=count,
            totalHosts=totalHosts,
            page=page,
            hosts=context,
            next_url=next_url,
            prev_url=prev_url,
        )