from queryservice_client.stream.peekable import Peekable
from queryservice_client.stream.stream import Stream

class DelimitedStream(Peekable):
    def __init__(self, stream: Stream, is_delimiter):
        self.stream = stream
        self.done = False
        self.is_delimiter = is_delimiter

    def has_next(self):
        if self.done:
            return False
        peek = self.stream.peek()
        if peek is None:
            self.done = True
            return False
        elif self.is_delimiter(peek):
            self.done = True
            next(self.stream)
            return False
        else:
            return True

    def __next__(self):
        if self.done:
            raise StopIteration()
        peek = self.stream.peek()
        if peek is None:
            self.done = True
            raise StopIteration()
        elif self.is_delimiter(peek):
            self.done = True
            next(self.stream)
            raise StopIteration()
        else:
            return next(self.stream)

    def peek(self):
        if self.done:
            return None
        peek = self.stream.peek()
        if peek is None:
            self.done = True
            return None
        elif self.is_delimiter(peek):
            self.done = True
            next(self.stream)
            return None
        else:
            return peek

    def __iter__(self):
        return self