import requests


def get_job_id(
    domain,
    org_key,
    headers,
    hostname="*",
    process="*",
    window="10h",
    start="0",
    end="0",
):
    """
    Function takes in the domain, org_key, headers, hostname, and timeframe to generate
    the initial query an retrieve the job id of that query returns job_id
    """
    url = f"{domain}/api/investigate/v2/orgs/{org_key}/processes/search_jobs"
    if start != "0":
        time_range = {"end": end, "start": start}
    else:
        time_range = {"window": "-" + window}
    if hostname == "*":
        query_payload = {
            "query": "process_name:" + process,
            "fields": [
                "device_name",
                "process_start_time",
                "process_cmdline",
                "process_name",
                "process_pid",
                "parent_pid",
            ],
            "sort": [{"field": "device_timestamp", "order": "asc"}],
            "start": 0,
            "rows": 10000,
            "time_range": time_range,
        }
    else:
        query_payload = {
            "criteria": {"device_name": [hostname]},
            "query": "process_name:" + process,
            "fields": [
                "device_name",
                "process_start_time",
                "process_cmdline",
                "process_name",
                "process_pid",
                "parent_pid",
            ],
            "sort": [{"field": "device_timestamp", "order": "asc"}],
            "start": 0,
            "rows": 10000,
            "time_range": time_range,
        }
    print("")
    response = requests.post(url, headers=headers, json=query_payload).json()
    job_id = response.get("job_id")
    print("Query sent to Carbon Black Cloud")
    return job_id