import os
import shutil
import sys
from random import randint
from datetime import datetime, timedelta
from .output_handler import HandleOutput


class HandleRotation:

    def __init__(self, configs):
        self.file_path = configs["file_locations"]["log_file_path"]
        self.log_rotation = configs["log_rotation_configs"]

    def check_rotation_condition(self, full_path, max_size, max_time):

        if os.path.getsize(full_path) >= max_size or datetime.now() - datetime.fromtimestamp(os.path.getctime(full_path)) >= timedelta(days=max_time):
            return True
        return False

    def rotate_log_path(self):

        HandleOutput.log_internal_message("Running rotation check")

        if self.check_rotation_condition(self.file_path,
                                         self.log_rotation["max_file_size"],
                                         self.log_rotation["max_file_age"]
                                         ):

            try:

                self.full_rotation()

            except (FileNotFoundError, PermissionError) as error:

                HandleOutput.log_internal_message(
                    "An error occured whilst attempting log rotation.", exception_traceback=error)

    def rename_rotating_log(self, log_file_path):
        archive_name = f"log_archive_{datetime.now().strftime('%d_%m_%y %H_%M_%S')}_{randint(1000, 99999)}.txt"
        archive_dir = os.path.dirname(log_file_path)
        archive_path = os.path.join(archive_dir, archive_name)

        os.makedirs(archive_dir, exist_ok=True)

        with open(log_file_path, 'r'):
            shutil.copy2(log_file_path, archive_path)

        
        HandleOutput.log_internal_message(
            f"Log file Archived as {archive_name}.\nArchived file size: {(os.path.getsize(archive_path) / 1024):.3f} KB\nArchived file age: {os.path.getmtime(archive_path)}.")

    def create_fresh_log(self, log_file_path):

        with open(log_file_path, 'w') as new_log_file:
            HandleOutput.log_internal_message(
                "Cleared log file")

    def full_rotation(self):

        self.rename_rotating_log(self.file_path)
        self.create_fresh_log(self.file_path)
