# mPy: oscilloscope datalogger based on a btree database
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-06-11  initial release

from	file_utilities	import	fExists, fRemove

# Implemented:
# Logger(size, fn=None)
#    Logger.__str__
#    Logger.append(value)
#    Logger.query (start=0, len=8)
#    Logger.save ()
#    Logger.open  ()

import	btree

# ======================= Logger ========================

class Logger:
    
    def __init__(self, size, fn=None):
        self.size = size
        self.fn   = fn
        self.f    = None
        self.idx  = 0
        self.data = None
        try:
            self.f = open(self.fn, 'r+b')
            self.data = btree.open(self.f)
        except:
            self.f = open(self.fn, 'w+b')
            self.data = btree.open(self.f)
            for idx in range(self.size):
                i = idx.to_bytes(2, 'big')
                self.data[i] = b'\x00'
        
     
    # return stored logger data as string
    def __str__(self):
        res = ''
        for k, v in self.data.items():
            res += f'{k}  {v}\n'
        return res

       
    # add integer to data
    def append(self, value):
        idx   = self.idx.to_bytes(2, 'big')
        self.data[idx] = bytes([value])
        self.idx += 1
        
        
    # return len elements from start    
    def query(self, start=0, len=8):
        strt = start.to_bytes(2, 'big')
        end  = (start+len).to_bytes(2, 'big')
        return b''.join(self.data.values(strt, end))
        
    
    # save logger data into file
    def save(self):
        self.data.flush()
        self.f.close()
        
        
    # load logger data from file
    def load(self):
        pass							# done by __init__()
            
# ====================== test =======================

if __name__ == '__main__':

    fn = 'logger.data'
    if fExists(fn): fRemove(fn)

    db = Logger(100, 'logger.data')
    print(db)
    db.append(4)
    print(db.query(5))
    db.save()
    print()
    db1 = Logger(100, 'logger.data')
    db1.load()
    print(db1.query(0))

# ====================== end ========================
