"""Extra functionality for [nbdev](https://nbdev.fast.ai/)"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/api/utilities/nbdev.ipynb.

# %% auto 0
__all__ = ['MarkdownTable', 'DictTbl', 'AttributeTbl']

# %% ../../nbs/api/utilities/nbdev.ipynb
import inspect
from fastcore.foundation import L

# %% ../../nbs/api/utilities/nbdev.ipynb
def _split_at(s:str, *args, strip=False):
    result = [s]
    for arg in args:
        strs = result.pop().split(arg)
        if len(strs) == 2: result += strs
        else: return None
    if strip: result = [s.strip(strip) for s in result]
    return result        

# %% ../../nbs/api/utilities/nbdev.ipynb
def _bold(s): return f'**{s}**' if s.strip() else s

# %% ../../nbs/api/utilities/nbdev.ipynb
def _list2row(l:list): return '| '+' | '.join(l) + ' |'

# %% ../../nbs/api/utilities/nbdev.ipynb
class MarkdownTable:
    
    def __init__(self, data, headers):
        self.data = data
        self.headers = headers
    
    @property
    def _columns(self):
        return self._map

    @property
    def _hdr_list(self): return [_bold(l) for l in self.headers]

    @property
    def hdr_str(self):
        "The markdown string for the header portion of the table"
        md = _list2row(self._hdr_list)
        return md + '\n' + _list2row(['-' * len(l) for l in self._hdr_list])

    @property
    def params_str(self):
        "The markdown string for the parameters portion of the table."
        return '\n'.join(L(self.data).map(_list2row))

    def _repr_markdown_(self):
        _tbl = [self.hdr_str, self.params_str]
        return '\n'.join(_tbl)

    def __eq__(self,other): return self.__str__() == str(other).strip()

    __str__ = _repr_markdown_

# %% ../../nbs/api/utilities/nbdev.ipynb
class DictTbl(MarkdownTable):
    def __init__(self, obj):
        rows = []
        for s in inspect.getsource(obj).split('\n'):
            line = L(_split_at(s, ":", "#", strip=' '))
            if len(line) == 3 and line[0][0] in "\'\"": rows.append(s.strip('\"\'') for s in line[[0, -1]])
        super().__init__(rows, [' ', 'Description'])

# %% ../../nbs/api/utilities/nbdev.ipynb
class AttributeTbl(MarkdownTable):
    def __init__(self, obj):
        rows = []
        for s in inspect.getsource(obj.__init__).split('\n'):
            line = L(_split_at(s, " = ", " # ", strip=' '))
            if len(line) == 3 and line[0].startswith('self.'): rows.append([line[0][5:], line[2]])
        super().__init__(rows, ['Attribute', 'Description'])
