# This file is part of Sigviewr.
# This project is licensed under the GNU GPL (version 3 or higher).
# Copyright 2014 by Clemens Brunner and Thomas Brunner.


from collections import OrderedDict
import time

from .streamreader import StreamReader

# begin HACK
try:
    import external.pylsl.pylsl as pylsl
except ImportError:
    pass
# end HACK


class LSLReader(StreamReader):
    def __init__(self):
        super(LSLReader, self).__init__()
        
    def open(self, streams):
        self.inlet = pylsl.stream_inlet(streams)
        self.metainfo.general["Type"] = "LSL"
        self.metainfo.general["Version"] = str(pylsl.protocol_version())
        self.metainfo.general["Recording time"] = time.asctime(time.gmtime())

        for stream in [streams]:
            stream_info = OrderedDict()
            stream_info["Type"] = stream.type()
            stream_info["Sampling rate"] = str(stream.nominal_srate())
            stream_info["Channels"] = str(stream.channel_count())
            self.metainfo.streams.append(stream_info)
    
    def close(self):
        pass
    
    def numStreams(self):
        return len(self.metainfo.streams)
    
    def sampleRate(self, stream):
        return float(self.metainfo.streams[stream]["Sampling rate"])
    
    def numChannels(self, stream):
        return int(self.metainfo.streams[stream]["Channels"])
    
    def channelLabel(self, stream, channel):
        return "Test"
    
    def resolve_streams(self):
        self.streams = pylsl.resolve_streams()
        return self.streams
    
    def get_data(self):
        sample = pylsl.vectorf()
        self.inlet.pull_sample(sample)
        return list(sample)