import json


def get_form_data(chart_id, dashboard=None):
    """
    Build `form_data` for chart GET request from dashboard's `default_filters`.

    When a dashboard has `default_filters` they need to be added  as extra
    filters in the GET request for charts.

    """
    form_data = {"slice_id": chart_id}

    if dashboard is None or not dashboard.json_metadata:
        return form_data

    json_metadata = json.loads(dashboard.json_metadata)

    # do not apply filters if chart is immune to them
    if chart_id in json_metadata.get("filter_immune_slices", []):
        return form_data

    default_filters = json.loads(json_metadata.get("default_filters", "null"))
    if not default_filters:
        return form_data

    # are some of the fields in the chart immune to filters?
    filter_immune_slice_fields = json_metadata.get("filter_immune_slice_fields", {})
    immune_fields = filter_immune_slice_fields.get(str(chart_id), [])

    extra_filters = []
    for filters in default_filters.values():
        for col, val in filters.items():
            if col not in immune_fields:
                extra_filters.append({"col": col, "op": "in", "val": val})
    if extra_filters:
        form_data["extra_filters"] = extra_filters

    return form_data