from io_module import IO_Module
from io_module import reg_table
from colorama import Fore
from random import randint
from time import sleep
import colorama
import struct

ARCHIVE_ENTRY = 0x06
LOG_ENTRY = 0x07


class LogReader(IO_Module):
    def __init__(self, tty: str, brate: int, address: int):
        super().__init__(tty, brate, address)
        colorama.init(autoreset=True)
        self.log_capacity = 0
        self.log_entries_number = 0
        self.archive_capacity = 0
        self.archive_entries_number = 0    

    def get_archive(self):
        print("LogReader")

    def get_log_info(self):
        data = self.read_holding_registers(reg_table['log_info'], 4)
        self.log_capacity = data[0]
        self.log_entries_number = data[1]
        self.archive_capacity = data[2]
        self.archive_entries_number = data[3]
        print('Log capacity           :', Fore.CYAN + str(self.log_capacity))
        print('Log entries number     :', Fore.CYAN + str(self.log_entries_number))
        print('Archive capacity       :', Fore.CYAN + str(self.archive_capacity))
        print('Archive entries number :', Fore.CYAN + str(self.archive_entries_number))


class DigitalLogReader(LogReader):
    def __init__(self, tty: str, brate: int, address: int):
        super().__init__(tty, brate, address)

    def get_archive(self):
        print("DigitalLogReader")

    def get_random_archive_entry(self):
        data = self.read_file_record(ARCHIVE_ENTRY, randint(1, self.archive_entries_number), 1)
        entry = struct.unpack('<QBB', data[5:15])
        print(entry)


class AnalogInputLogReader(LogReader):
    def __init__(self):
        super().__init__()

    def get_archive(self):
        print("AnalogInputLogReader")



def main():

    module = DigitalLogReader('COM24', 115200, 15)

    module.get_log_info()
    module.get_archive()

    for i in range(500):
        module.get_random_archive_entry()
        sleep(0.1)



if __name__ == '__main__':
    main()

