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

__all__ = ['connect', 'tables', 'get_id', 'query']

# Internal Cell
import pydomo
from pydomo.datasets import Sorting
from jedi_toolz import config
import io
import csv

__tables__ = None

def connect() -> pydomo.Domo:
    """Returns a connection object to a DOMO instance."""
    client_id = config.select("domo", "client_id")
    secret = config.select("domo", "secret")
    return pydomo.Domo(client_id, secret)

def tables():
    """Returns a dataframe of all datasets for which the
    user has share permissions or is marked as the owner.
    """
    global __tables__
    if __tables__ is not None: return __tables__

    domo = connect()
    datasets = domo.datasets.list(sort=Sorting.NAME)
    result = []
    for table in datasets:
        table["owner_id"] = table["owner"]["id"]
        table["owner"] = table["owner"]["name"]
        result.append(table)
    __tables__ = result
    return __tables__

def get_id(table_name) -> str:
    """Returns the 'id' for a given table_name."""
    for table in tables():
        if table["name"] == table_name:
            return table["id"]

def query(table_name):
    """Takes a 'table_name' and returns a pandas.DataFrame
    object containing the rows and columns of a domo
    dataset.
    """
    id = get_id(table_name)
    domo = connect()
    include_csv_headers = True
    result = domo.datasets.data_export(
        id, include_csv_headers)
    file = io.StringIO(result)
    rows = csv.DictReader(file)
    return [row for row in rows]