# 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 .source import Source


class BufferedSource(Source):
    def __init__(self, label, sampleRate, unit=None, minVal=-1, maxVal=1):
        super(BufferedSource, self).__init__(label, unit, minVal, maxVal)
        self._sampleRate = sampleRate
        self._samplesAvailable = 0
        self._buffer = []

    def sampleRate(self):
        return self._sampleRate
       
    def addSamples(self, newSamples):
        if not isinstance(newSamples, list):  # Only a single sample
            newSamples = [newSamples]

        self._buffer.extend(newSamples)
        self._samplesAvailable += len(newSamples)
    
    def lastAvailableTime(self):
        return (self._samplesAvailable - 1) / float(self._sampleRate)
            
    def getData(self, startTime, endTime):
        startSample = max(0, round(startTime * self._sampleRate - 0.5))
        endSample = min(self._samplesAvailable - 1, round(endTime * self._sampleRate))
        
        times = []
        values = []
        for sampleNr in range(startSample, endSample + 1):
            times.append(sampleNr / float(self._sampleRate))
            values.append(self._buffer[sampleNr])

        return times, values
