"""
Wrapper around version 2 of the Energy Aspects API

"""

import requests
import pandas as pd
import typing as t
from datetime import date
import os

base_url = "https://api.energyaspects.com/data/datasets/timeseries/"
timeseries_url = "https://api.energyaspects.com/data/timeseries/"

api_key = os.getenv('EA_API_KEY')

headers = {"Accept": "application/json"}


def get_timeseries_def():
    querystring = {
        "api_key": api_key,
    }
    response = requests.request("GET", base_url, headers=headers, params=querystring)

    alls = pd.read_json(response.text)
    alls = pd.merge(alls, alls['metadata'].apply(lambda x: pd.Series(x), 1), left_index=True, right_index=True)
    alls = alls.set_index('dataset_id')
    return alls


def extract_data(s, id_):
    r = pd.Series(s)
    r.index = pd.to_datetime(r.index)
    r.name = id_
    return r


def read_timeseries(ids_: t.Tuple[int], use_desc: bool = False, date_from:date = None) -> pd.DataFrame():
    querystring = {
        "api_key": api_key,
        "dataset_id": [str(x) for x in ids_]
    }

    if date_from:
        querystring["date_from"] = date_from.strftime("%Y-%m-%d")

    response = requests.request("GET", timeseries_url, headers=headers, params=querystring)
    if response.status_code == 200:
        df = pd.read_json(response.text)
        data = df.apply(lambda x: extract_data(x.data, x.dataset_id), 1)
        if use_desc:
            data.index = data.index.map(lambda x: df.loc[x].metadata['description'])
        else:
            data.index = data.index.map(lambda x: df.loc[x].dataset_id)
        data = data.T
        return data


def detailed_metadata(id_: int) -> pd.DataFrame:
    querystring = { "api_key": api_key, }

    response = requests.request("GET", '%s%s' % (base_url, id_), headers=headers, params=querystring)
    if response.status_code == 200:
        df = pd.read_json(response.text)
        df = df['metadata']
        df.name = id_
        data = pd.DataFrame(df)
        return data.T


