from typing import Type, Iterable, Sized, Iterator, NewType
from google.protobuf.reflection import GeneratedProtocolMessageType
"""
The type which generated by 
google.protobuf.reflection.GeneratedProtocolMessageType
"""
GeneratedProtocolMessageType = "GeneratedProtocolMessageType"


class ProtoList(Sized, Iterable):

    def __init__(self, path, proto_class: Type[GeneratedProtocolMessageType]):
        self.path = path
        self.proto_class = proto_class

    def __enter__(self):        
        self.file = open(self.path, 'rb')
        self.length = []
        self.coordinate = [[list()]]
        while (N := self.file.read(8)) != b'':
            self.length.append(self.file.tell())
            N = int.from_bytes(N, byteorder='big')
            self.coordinate.append(N)
            self.file.seek(N, 1)
        return 

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.__exit__(exc_type, exc_val, exc_tb)

    def __len__(self):
        return self.lengths.__len__()

    def __getitem__(self, item):
        self.file.seek(self.coordinate[item])
        return self.proto_class().ParseFromString(self.file.read(self.length[item]))

    def __iter__(self) -> Iterator[GeneratedProtocolMessageType]:
        for n in range(self.__len__()):
            yield self[n]



