# AUTOGENERATED! DO NOT EDIT! File to edit: 02_data_cloud.ipynb (unless otherwise specified).

__all__ = ['get_data_cloud', 'get_charts_cloud']

# Cell
# export
import os
import requests
import json
import pandas as pd

# Cell


def get_data_cloud(space_id, room_id, context, after=-60, before=0, points=None, api_token=None,
                   base_url='https://app.netdata.cloud', time_as_index=True, time_unit='ms',
                   group='average', aggregations=[{'method': 'sum', 'groupBy': ['dimension']}],
                   agent_options=['absolute', 'jsonwrap', 'nonzero', 'flip', 'ms'], gtime=0, with_metadata=True,
                   format='array', node_ids=[], dimensions=[], freq=None
                   ):
    """Get data from netdata cloud api.

    ##### Parameters:
    - **space_id** `str` The space_id you would like to pull data from.
    - **room_id** `str` The room_id you would like to pull data from.
    - **context** `str` The context you would like to pull data from.
    - **after** `int` The timestamp or relative integer from which to pull data after.
    - **before** `int` The timestamp or relative integer from which to pull data before.
    - **points** `int` The `points` parameter to pass to the api call if need to aggregate data in some way.
    - **api_token** `str` The api token to use for the api call.
    - **base_url** `str` The base url to use for the api call.
    - **time_as_index** `bool` Whether to set the time column as the index of the dataframe.
    - **time_unit** `str` The unit of time to use for the time column.
    - **group** `str` The `group` parameter to pass to the api call.
    - **aggregations** `list` The `aggregations` parameter to pass to the api call.
    - **agent_options** `list` The `agent_options` parameter to pass to the api call.
    - **gtime** `int` The `gtime` parameter to pass to the api call.
    - **with_metadata** `bool` The `with_metadata` parameter to pass to the api call.
    - **format** `str` The `format` parameter to pass to the api call.
    - **node_ids** `list` The `node_ids` parameter to pass to the api call.
    - **dimensions** `list` The `dimensions` parameter to pass to the api call.
    - **freq** `str` The frequency to use for the dataframe index.

    ##### Returns:
    - **df** `pd.DataFrame` A pandas dataframe.

    """

    if api_token is None:
        api_token = os.getenv('NETDATA_API_TOKEN')

    window_length = before - after
    if freq:
        if freq.endswith('s'):
            points = int(window_length / int(freq.replace('s','')))
        elif freq.endswith('m'):
            points = int(window_length / (int(freq.replace('m','')) * 60))
        elif freq.endswith('h'):
            points = int(window_length / (int(freq.replace('h','')) * 60 * 60))

    base_url = 'https://app.netdata.cloud'
    url = f'{base_url}/api/v2/spaces/{space_id}/rooms/{room_id}/data'
    headers = {'Accept': '*/*', 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_token}'}
    data = {
        'filter': {
            'nodeIDs': node_ids,
            'context': context,
            'dimensions': dimensions,
        },
        'after': int(after),
        'before': int(before),
        'format': format,
        'group': group,
        'aggregations': aggregations,
        'agent_options': agent_options,
        'gtime': gtime,
        'with_metadata': with_metadata
    }
    if points:
        data['points'] = points
    r = requests.post(url, headers=headers, data=json.dumps(data))

    if r.status_code != 200:

        print(f'Error: {r.status_code, r.text}')
        return pd.DataFrame()

    else:

        df = pd.DataFrame(data=r.json()['result']['data'], columns=r.json()['result']['labels'])

        if time_unit:
            df['time'] = pd.to_datetime(df['time'], unit='ms')
        if time_as_index:
            df = df.set_index('time')

        return df



# Cell


def get_charts_cloud(space_id, room_id, api_token=None, base_url='https://app.netdata.cloud', node_ids=[]):
    """Get charts from netdata cloud api.
    """

    if api_token is None:
        api_token = os.getenv('NETDATA_API_TOKEN')

    base_url = 'https://app.netdata.cloud'
    url = f'{base_url}/api/v2/spaces/{space_id}/rooms/{room_id}/charts'
    headers = {'Accept': '*/*', 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_token}'}
    data = {
        'filter': {
            'nodeIDs': node_ids,
        }
    }
    r = requests.post(url, headers=headers, data=json.dumps(data))

    if r.status_code != 200:

        print(f'Error: {r.status_code, r.text}')
        return None

    else:

        return r.json()['results']

