from androidMemoryTool import AndroidMemoryTool
from time import sleep
from os import system

tool = AndroidMemoryTool(PKG="Tutorial-x86_64.exe")
profile_instance = tool.get_memory_profiler()

custom_log_file = "memory_dump.txt"


def custom_log_memory_data(data: list[dict]) -> None:
    with open(custom_log_file, 'w') as log_file:
        log_file.write(f"{'Time':<10}{'Process RSS (BYTES)':<40}{'Memory Leak':<15}{'Memory Churn':<15}\n")
        for entry in data:
            log_file.write(f"{entry['time']:<10}{entry['process_memory']:<40}{entry['leak']:<15}{entry['churn']:<15}\n")


def custom_print_function(data: list[dict]):
    if AndroidMemoryTool.get_platform() == 'Windows':
        system("CLS")
    else:
        system("clear")
    formatted_status_print_header = f"{'Time':<10}{'Process RSS (MB)':<30}{'Memory Leak':<15}{'Memory Churn':<15}\n"
    current_body = formatted_status_print_header
    for entry in data:
        current_body += f"{entry['time']:<10}{entry['process_memory'] / (1024 * 1024):<30}{entry['leak']:<15}" \
                        f"{entry['churn']:<15}\n"
    print(current_body)


def start_custom_profiler():
    threshold_in_mb: float = 20.0
    update_interval_delay: float = 1.0
    while True:
        try:
            # This function will store memory in public variables
            profile_instance.current_memory_data(threshold_in_mb=threshold_in_mb)
            profile_instance.create_data_from_files()  # Create the data and store in self._data which we can get latter
            data = profile_instance.get_current_data()  # return the data generated by profiler
            custom_log_memory_data(data=data)
            custom_print_function(data=data)
            """
            Data will get these values
            time, ram, cores, process_memory, leak, churn, pid
            """
            sleep(update_interval_delay)  # Delay for some time
        except KeyboardInterrupt:
            print('Closing Program please wait')
            break


start_custom_profiler()
