import time
import threading
import json

class DisplayManager:
    def __init__(self, power_manager, config_path='power_saving_config.json'):
        self.power_manager = power_manager
        self.config_path = config_path
        self.load_config()
        self.dimmed = False
        self.last_activity = time.time()
        self.timer = None
        self.lock = threading.Lock()

    def load_config(self):
        try:
            with open(self.config_path, 'r') as f:
                config = json.load(f)
                self.dim_timeout = config.get('dim_timeout', 60)  # Default to 60 seconds
                self.dim_brightness = config.get('dim_brightness', 0.2)  # Default to 20%
                self.normal_brightness = config.get('normal_brightness', 1.0)
        except FileNotFoundError:
            print(f"Config file not found: {self.config_path}. Using default values.")
            self.dim_timeout = 60
            self.dim_brightness = 0.2
            self.normal_brightness = 1.0
        except json.JSONDecodeError:
            print(f"Error decoding JSON in {self.config_path}. Using default values.")
            self.dim_timeout = 60
            self.dim_brightness = 0.2
            self.normal_brightness = 1.0

    def record_activity(self):
        with self.lock:
            self.last_activity = time.time()
            if self.dimmed:
                self.restore_brightness()

            if self.timer and self.timer.is_alive():
                self.timer.cancel()
            self.start_dim_timer()

    def start_dim_timer(self):
        self.timer = threading.Timer(self.dim_timeout, self.dim_display)
        self.timer.start()

    def dim_display(self):
        with self.lock:
            if time.time() - self.last_activity >= self.dim_timeout:
                print("Dimming display...")
                self._set_brightness(self.dim_brightness)
                self.dimmed = True
            else:
                print("Activity detected during dimming timer. Restarting timer.")
                self.start_dim_timer()

    def restore_brightness(self):
        with self.lock:
            print("Restoring display brightness...")
            self._set_brightness(self.normal_brightness)
            self.dimmed = False

    def _set_brightness(self, brightness):
        # Placeholder for actual brightness setting functionality
        # This would involve platform-specific code (e.g., using OS APIs)
        # For demonstration purposes, we just print the intended brightness.
        print(f"Setting display brightness to: {brightness}")

    def shutdown(self):
        if self.timer and self.timer.is_alive():
            self.timer.cancel()
        print("Display Manager shutting down.")

if __name__ == '__main__':
    # Example usage (requires a dummy PowerManager for testing)
    class DummyPowerManager:
        def __init__(self):
            pass

        def register_activity(self):
            print("Activity registered by PowerManager")

    power_manager = DummyPowerManager()
    display_manager = DisplayManager(power_manager)

    # Simulate activity
    display_manager.record_activity()
    time.sleep(5)
    display_manager.record_activity()
    time.sleep(70)
    display_manager.record_activity()

    display_manager.shutdown()
