from .logger import DolostLogger
from .docker_manager import DockerManager
import json
from datetime import datetime

logger = DolostLogger.get_instance()
docker_manager = DockerManager.get_instance()


class ActivityViewer:
    @staticmethod
    def review_logs():
        """
        Review logs from the activity viewer.

        This method retrieves the latest log entries from the activity viewer, specifically focusing on the logs generated by the decoys. It connects to the DolosT-Collector container, which serves as the centralized log collector for all decoys. It then tail the last 50 lines of each log file within the '/var/log/decoys/' folder, continuously monitoring for new log entries.

        Returns:
            list: A list containing the latest log entries from the activity viewer.
        """
        container_id = "DolosT-Collector"
        folder_path = "/var/log/decoys/"

        new_logs = []
        # Create a command to monitor each file within the folder continuously
        command = f"sh -c 'tail -n 50 {folder_path}*'"

        filters = {'name': [container_id]}
        CollectorExist = docker_manager.client.api.containers(filters=filters)

        # If collector doesnt exist, show a message
        if (CollectorExist):
            # Create the exec instance in the container
            exec_id = docker_manager.client.api.exec_create(container_id, command, tty=True)

            # Start streaming the output of the command
            for line in docker_manager.client.api.exec_start(exec_id['Id'], stream=True):
                log_line = line.decode().strip()  # Remove leading/trailing whitespace
                new_logs.append(log_line)

            # If no logs received, show a message
            if "tail: can't open '/var/log/decoys/*': No such file or directory\r\ntail: no files" in new_logs:
                new_logs = ["No decoy logs received in the environment yet"]
        else:
            new_logs = ["No collector deployed in the environment yet"]

        return new_logs
    
    def review_observable_ips():
        """
        Review logs from the activity viewer.

        This method retrieves the latest log entries from the activity viewer, specifically focusing on the logs generated by the decoys. It connects to the DolosT-Collector container, which serves as the centralized log collector for all decoys. It then tail the last 50 lines of each log file within the '/var/log/decoys/' folder, continuously monitoring for new log entries.

        Returns:
            list: A list containing the latest log entries from the activity viewer.
        """
        container_id = "DolosT-Collector"
        file_path = "/var/log/observables/observable_ips.log"
        observable_ips = []
        new_ips = []

        # Create a command to check for ips on each file
        command = f"sh -c 'tail -n 5000 {file_path}*'"
        filters = {'name': [container_id]}
        CollectorExist = docker_manager.client.api.containers(filters=filters)

        # If collector doesnt exist, show a message
        if (CollectorExist):
            # Create the exec instance in the container
            exec_id = docker_manager.client.api.exec_create(container_id, command, tty=True)

            # Start streaming the output of the command
            for line in docker_manager.client.api.exec_start(exec_id['Id'], stream=True):
                decoded_line = line.decode('utf-8')
                if decoded_line == ("tail: can't open '/var/log/observables/observable_ips.log*': No such file or directory\r\ntail: no files\r\n") :
                    new_ip = '{"id": 1, "ip": "-- No Observable IP --","timestamp": "----" }'
                    observable_ips.append(new_ip)
                else:    
                    records = decoded_line.strip().split('\r\n')
                    # Process each record
                    i = 1
                    for record in records:
                        # Split each record by space to separate the timestamp and the IP address
                        timestamp, ip_address = record.rsplit(' ', 1)
                        observable_ips.append('{"id": '+ str(i) +', "ip": "'+ ip_address +'", "timestamp": "' + timestamp + '"}')
                        if i >= 3:
                            break

                        i = i + 1
        else:
            new_ip = '{"id": 1, "ip": "-- No Collector available --","timestamp": "----" }'
            observable_ips.append(new_ip)

        return observable_ips

    def turn_on_crond():
        """
        This is an auxiliary task to run crond in the collector

        Returns:
            none
        """
        container_id = "DolosT-Collector"

        # Create a command to run crond
        command = "sh -c 'crond'"
        filters = {'name': [container_id]}
        CollectorExist = docker_manager.client.api.containers(filters=filters)

        # If collector doesnt exist, show a message
        if (CollectorExist):
            # Create the exec instance in the container
            exec_id = docker_manager.client.api.exec_create(container_id, command, tty=True)
            docker_manager.client.api.exec_start(exec_id['Id'], stream=True)
