# Path: trtools/io/pytables.py
# def convert_frame(df):
#     """
#         Input: DataFrame
#         Output: pytable table description and pytable compatible recarray
#     """
#     sdict = OrderedDict()
#     atoms = OrderedDict()
#     types = OrderedDict()
# 
#     #index
#     index_name = df.index.name or 'pd_index'
#     converted, inferred_type, atom = _convert_obj(df.index)
#     atoms[index_name] = atom
#     sdict[index_name] = converted
#     types[index_name] = inferred_type
# 
# 
#     # columns
#     for col in df.columns:
#         converted, inferred_type, atom = _convert_obj(df[col])
#         atoms[col] = atom
#         sdict[col] = converted
#         types[col] = inferred_type
# 
#     # create table desc
#     desc = OrderedDict() 
#     for pos, data in enumerate(atoms.items()):
#         k, atom = data
#         col = tb.Col.from_atom(atom, pos=pos) 
#         desc[str(k)] = col
# 
#     # create recarray
#     dtypes = [(str(k), v.dtype) for k, v in list(sdict.items())]
#     recs = np.recarray(shape=len(df), dtype=dtypes)
#     for k, v in list(sdict.items()):
#         recs[str(k)] = v
#     return desc, recs, types
# 
# def _meta(obj, meta=None):
#     obj = _unwrap(obj)
# 
#     if isinstance(obj, tb.file.File):
#         obj = obj.root
#         return _meta_file(obj, meta)
# 
#     handle = _handle(obj)
#     type = handle.type
#     if type == 'directory':
#         return _meta_dir(obj, meta)
# 
#     return _meta_file(obj, meta)
# 
# def copy_table_def(group, name, orig):
#     table_meta = _meta(orig)
#     desc = orig.description
#     types = table_meta['value_types']
#     index_name = table_meta['index_name']
#     columns = table_meta['columns']
#     expectedrows = orig.nrows
#     table = group.create_table(name, desc, types, columns=columns, index_name=index_name, expectedrows=expectedrows)
#     return table
# 
# class SimpleIndexer(object):
#     def __init__(self, obj):
#         self.obj = obj
# 
#     def __getitem__(self, key):
#         # TODO, get fancier slicing later on
#         if isinstance(key, tuple):
#             return self._getitem_tuple(key)
#         if isinstance(key, IndexSlice):
#             key = slice(key.start, key.end, key.step)
#         return self.obj[key]
# 
#     def _getitem_tuple(self, key):
#         # TODO check if this is faster than just grabbing the whole
#         rows = key[0]
#         if isinstance(rows, IndexSlice):
#             rows = slice(rows.start, rows.end, rows.step)
# 
#         cols = key[1]
#         if isinstance(cols, str):
#             cols = [cols]
# 
#         # grabbing the straight data. obj is an HDF5Table. obj.obj is table.Table
#         if len(cols) > 1:
#             data = self.obj.obj[rows]
#         else:
#             # this doesn't seem to be all that much faster, keeping in anyways
#             data = {}
#             col = cols[0]
#             data[col] = self.obj.obj.col(col)
# 
#         return table_data_to_frame(data, self.obj, columns=cols)


import pandas as pd
import numpy as np
from trtools.io.pytables import convert_frame, _meta, copy_table_def, SimpleIndexer

    def __getattr__(self, key):
        if hasattr(self.table, key):
            return getattr(self.table, key)
        raise AttributeError()

    def __getitem__(self, key):
        if isinstance(key, str):
            return self._getitem_framekey(key)
        if isinstance(key, int):
            return self._getitem_framekey(key)
        df = self.table[key]
        df.set_index(self.frame_key, append=True, inplace=True)
        return df

    def _getitem_framekey(self, key):
        query = getattr(self.table.sql, self.frame_key) == key
        df = self.table[query]
        del df[self.frame_key]
        return df

    def index_default(self):
        table_meta = _meta(self.table)
        index_name = table_meta['index_name']
        self.table.add_index(index_name)
        self.table.add_index(self.frame_key)

    def sort_index(self):
        df = self.table[:] # getitem returns MultiIndex
        df = df.sort_index()

# Path: trtools/io/pytables.py
# def convert_frame(df):
#     """
#         Input: DataFrame
#         Output: pytable table description and pytable compatible recarray
#     """
#     sdict = OrderedDict()
#     atoms = OrderedDict()
#     types = OrderedDict()
# 
#     #index
#     index_name = df.index.name or 'pd_index'
#     converted, inferred_type, atom = _convert_obj(df.index)
#     atoms[index_name] = atom
#     sdict[index_name] = converted
#     types[index_name] = inferred_type
# 
# 
#     # columns
#     for col in df.columns:
#         converted, inferred_type, atom = _convert_obj(df[col])
#         atoms[col] = atom
#         sdict[col] = converted
#         types[col] = inferred_type
# 
#     # create table desc
#     desc = OrderedDict() 
#     for pos, data in enumerate(atoms.items()):
#         k, atom = data
#         col = tb.Col.from_atom(atom, pos=pos) 
#         desc[str(k)] = col
# 
#     # create recarray
#     dtypes = [(str(k), v.dtype) for k, v in list(sdict.items())]
#     recs = np.recarray(shape=len(df), dtype=dtypes)
#     for k, v in list(sdict.items()):
#         recs[str(k)] = v
#     return desc, recs, types
# 
# def _meta(obj, meta=None):
#     obj = _unwrap(obj)
# 
#     if isinstance(obj, tb.file.File):
#         obj = obj.root
#         return _meta_file(obj, meta)
# 
#     handle = _handle(obj)
#     type = handle.type
#     if type == 'directory':
#         return _meta_dir(obj, meta)
# 
#     return _meta_file(obj, meta)
# 
# def copy_table_def(group, name, orig):
#     table_meta = _meta(orig)
#     desc = orig.description
#     types = table_meta['value_types']
#     index_name = table_meta['index_name']
#     columns = table_meta['columns']
#     expectedrows = orig.nrows
#     table = group.create_table(name, desc, types, columns=columns, index_name=index_name, expectedrows=expectedrows)
#     return table
# 
# class SimpleIndexer(object):
#     def __init__(self, obj):
#         self.obj = obj
# 
#     def __getitem__(self, key):
#         # TODO, get fancier slicing later on
#         if isinstance(key, tuple):
#             return self._getitem_tuple(key)
#         if isinstance(key, IndexSlice):
#             key = slice(key.start, key.end, key.step)
#         return self.obj[key]
# 
#     def _getitem_tuple(self, key):
#         # TODO check if this is faster than just grabbing the whole
#         rows = key[0]
#         if isinstance(rows, IndexSlice):
#             rows = slice(rows.start, rows.end, rows.step)
# 
#         cols = key[1]
#         if isinstance(cols, str):
#             cols = [cols]
# 
#         # grabbing the straight data. obj is an HDF5Table. obj.obj is table.Table
#         if len(cols) > 1:
#             data = self.obj.obj[rows]
#         else:
#             # this doesn't seem to be all that much faster, keeping in anyways
#             data = {}
#             col = cols[0]
#             data[col] = self.obj.obj.col(col)
# 
#         return table_data_to_frame(data, self.obj, columns=cols)


# Path: trtools/io/panda_hdf.py
import pandas as pd
import numpy as np
from trtools.io.pytables import convert_frame, _meta, copy_table_def, SimpleIndexer


    def __getattr__(self, key):
        if hasattr(self.table, key):
            return getattr(self.table, key)
        raise AttributeError()

    def __getitem__(self, key):
        if isinstance(key, str):
            return self._getitem_framekey(key)
        if isinstance(key, int):
            return self._getitem_framekey(key)
        df = self.table[key]
        df.set_index(self.frame_key, append=True, inplace=True)
        return df

    def _getitem_framekey(self, key):
        query = getattr(self.table.sql, self.frame_key) == key
        df = self.table[query]
        del df[self.frame_key]
        return df

    def index_default(self):
        table_meta = _meta(self.table)
        index_name = table_meta['index_name']
        self.table.add_index(index_name)
        self.table.add_index(self.frame_key)

    def sort_index(self):
        df = self.table[:] # getitem returns MultiIndex
        df = df.sort_index()

        table = copy_table_def(self.group, 'indexed_table', self.table)