from boadata.core import DataNode, DataTree
import h5py
import logging
import os
import pydons


class _MatlabNode(DataNode):
    def __init__(self, parent, name, fb_node):
        super(_MatlabNode, self).__init__(parent)
        self.name = name
        self.fb_node = fb_node

    @property
    def title(self):
        return self.name

    def load_children(self):
        for name, value in self.fb_node.items():
            if isinstance(value, pydons.MatStruct):
                child = Matlab73Struct(self, name, value)
            elif isinstance(value, pydons.LazyDataset):
                child = Matlab73Dataset(self, name, value)
            else:
                pass
                # print ("Unknown: {0}".format(type(value)))
            self.add_child(child)


class Matlab73Dataset(_MatlabNode):
    def load_children(self):
        return None


class Matlab73Struct(_MatlabNode):
    pass


@DataTree.register_tree
class Matlab73Tree(_MatlabNode, DataTree):
    def __init__(self, path, parent=None):
        self.path = path
        fb_node = pydons.FileBrowser(self.path, any_keys=True)
        super(Matlab73Tree, self).__init__(parent, self.path, fb_node)

    @classmethod
    def accepts_uri(cls, uri):
        return uri and os.path.isfile(uri) and (uri.endswith(".fig") or uri.endswith(".mat"))

    @property
    def title(self):
        return os.path.basename(self.path)


class OldMatlabNode(DataNode):
    def __init__(self, parent, key):
        super(OldMatlabNode, self).__init__(parent=parent, uri=parent.uri + "::" + key)
        self.data = self.parent.inner_dict[key]
        self.key = key

    @property
    def data_object(self):
        from boadata.data.matlab_types import OldMatlabData
        return OldMatlabData(inner_data=self.data, uri=self.uri)

    @property
    def title(self):
        return self.key


@DataTree.register_tree
class OldMatlabTree(DataTree):
    @classmethod
    def accepts_uri(cls, uri):
        return uri and os.path.isfile(uri) and (uri.endswith(".mat"))

    def __init__(self, path, parent=None):
        from scipy.io import loadmat
        super(OldMatlabTree, self).__init__(parent=parent, uri=path)
        self.inner_dict = loadmat(path)

    def load_children(self):
        for key in self.inner_dict.keys():
            self.add_child(OldMatlabNode(self, key))


@@ -2341,12 +2341,302 @@
 elf, key))%0A%0A
+# TODO: Consider this which I found in one kaggle notebook%0A# def mat_to_pandas(path):%0A#    mat = loadmat(path)%0A#    names = mat%5B'dataStruct'%5D.dtype.names%0A#    ndata = %7Bn: mat%5B'dataStruct'%5D%5Bn%5D%5B0, 0%5D for n in names%7D%0A#    return pd.DataFrame(ndata%5B'data'%5D, columns=ndata%5B'channelIndices'%5D%5B0%5D)%0A

Update matlab.py