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

import	os

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

import	json

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

class Logger:
    
    def __init__(self, size, fn=None):
        self.size = size
        self.fn   = fn
        self.idx  = 0
        self.data = {}
        for idx in range(size):
            self.data[idx] = None
        
     
    # return stored logger data as string
    def __str__(self):
        return str(self.data)

       
    # add integer to data
    def append(self, value):
        self.data[self.idx] = value
        self.idx += 1
        
        
    # return len elements from start    
    def query(self, start=0, len=8):
        return [self.data[start+idx] for idx in range(len)]
        
    
    # save logger data into file
    def save(self):
        temp = {str(k):v for k, v in self.data.items()}
        if self.fn:
            with open(self.fn, 'w') as f:
                json.dump(temp, f)
        else: print('Error, logger not associated with a file')
        
        
    # load logger data from file
    def load(self):
        if self.fn:
            with open(self.fn, 'r') as f:
                temp = json.load(f)
            self.data = {int(k):v for k, v in temp.items()}
        else: print('Error, logger not associated with a file')
        
# ====================== test =======================

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

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


