# Credit: Dai Chao Online == Date: 2026-02-23
import emulator
import subprocess
import os
import time

class EmulatorManager:
    def __init__(self, ld_dir):
        self.ld_instance = emulator.LDPlayer(ld_dir)
        self.ldplayer = self.ld_instance.emulators
        self.creation_flags = subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
    
    def launch_instance(self, index):
        self.ldplayer[index].start()

    def stop_instance(self, index):
        self.ldplayer[index].quit()
        
    def reboot_instance(self, index, delay=3):
        self.stop_instance(index)
        time.sleep(delay)
        self.launch_instance(index)
            
    def organize_windows(self):
        self.ld_instance.sort_window()
        
    def check_status(self, index):
        return "Running" if self.ldplayer[index].is_running() else "Stopped"

    def get_instance_name(self, index):
        return self.ldplayer[index].name 
    
    def calculate_vms_size(self, index, ld_dir):
        vms_folder = os.path.join(ld_dir, "vms", f"leidian{index}")
        if not os.path.exists(vms_folder):
            return False

        total_bytes = 0
        for dirpath, _, filenames in os.walk(vms_folder):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                total_bytes += os.path.getsize(fp)

        size_mb = total_bytes / (1024 * 1024)
        size_gb = total_bytes / (1024 * 1024 * 1024)

        if size_gb >= 1:
            return f"{size_gb:.1f} GB"
        else:
            return f"{size_mb:.1f} MB"