# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03-raw-methods.ipynb (unless otherwise specified).

__all__ = ['clean_path_name', 'dict_head', 'get_available_methods', 'extract_parameter_example', 'construct_parameters',
           'construct_path_functions', 'construct_all_functions', 'save_methods']

# Cell
import pandas as pd
import io
import yaml
import xmltodict
from jinja2 import Template

# Cell
dict_head = lambda dict_, n=5: dict(pd.Series(dict_).head(n))

def clean_path_name(
    path_name: str='/BMRS/B0610/v1',
    name_components_to_drop: list=['BMRS', 'v1', 'v2']
):
    for name_component_to_drop in name_components_to_drop:
        path_name = path_name.replace(name_component_to_drop, '')

    path_name = path_name.strip('/')

    return path_name

# Cell
def get_available_methods(
    API_yaml: dict,
    path: str,
    acceptable_methods: list=['get', 'post', 'put', 'head', 'delete', 'patch', 'options']
):
    path_keys = API_yaml['paths'][path].keys()
    available_methods = list(set(path_keys) - (set(path_keys) - set(acceptable_methods)))

    return available_methods

def extract_parameter_example(parameter):
    if 'examples' in parameter.keys():
        examples = [value['value'] for value in parameter['examples'].values()]
        example = examples[0]
    else:
        example = parameter['example']

    return example

def construct_parameters(method_details):
    parameters = list()

    for parameter in method_details['parameters']:
        parameter_info = dict()
        parameter_info['name'] = parameter['name']
        parameter_info['type'] = parameter['schema']['type']
        parameter_info['example'] = extract_parameter_example(parameter)

        parameters += [parameter_info]

    return parameters

def construct_path_functions(API_yaml, path):
    functions = list()
    root_url = API_yaml['servers'][0]['url']
    available_methods = get_available_methods(API_yaml, path)

    for method in available_methods:
        function = dict()
        method_details = API_yaml['paths'][path][method]

        function['name'] = f'{method}_{clean_path_name(path)}'
        function['endpoint'] = f'{root_url}{path}'
        function['description'] = method_details['description']
        function['parameters'] = construct_parameters(method_details)

        functions += [function]

    return functions

def construct_all_functions(API_yaml):
    functions = list()

    for path in API_yaml['paths']:
        functions += construct_path_functions(API_yaml, path)

    return functions

# Cell
def save_methods(
    functions: list,
    in_fp: str='../templates/raw_methods.py',
    out_fp: str='../ElexonDataPortal/dev/raw.py'
):
    rendered_schema = Template(open(in_fp).read()).render(functions=functions)

    with open(out_fp, 'w') as f:
        try:
            f.write(rendered_schema)
        except e as exc:
            raise exc