import sys
import os
from pydm import Display
from PyQt5.QtWidgets import QApplication
import subprocess

class MyDisplay(Display):
    # UI files with full paths including environment variables
    UI_FILES = {
        'MOC Expert': '$PYDM/misc/asyn_octet.ui',
        'IOC Expert': '$PYDM/misc/ioc_stats_vioc.ui',
        'Motor Expert': '$PYDM/mc/Common/MotorExpert.ui',
        'Setpoint Expert': '$PYDM/mc/CBXFEL/Setpoint-Edit.ui',
        'Console Expert': '$TOOLS/script/mc-tools-motion/pydm/GetConsoleStatus.py',
        'Axis Expert': {
            'PMAC': '$PYDM/mc/CBXFEL/PMAC-Axis.ui',
            'MCS2': '$PYDM/mc/CBXFEL/MCS2-Axis.ui'
        },
        'Homing Expert': {
            'PMAC': '$PYDM/mc/CBXFEL/PMAC-Home.ui',
            'MCS2': '$PYDM/mc/CBXFEL/MCS2-Home.ui'
        }
    }

    def __init__(self, parent=None, args=None, macros=None):
        self.macros = macros or {}
        try:
            self.ui_path = self.resolve_ui_path()
            super().__init__(parent=parent, args=args, macros=self.macros)
        except Exception as e:
            print(f"Error initializing display: {e}")
            raise

    def resolve_ui_path(self):
        """Resolve the UI path based on provided macros"""
        ui_type = self.macros.get('UI')
        if not ui_type:
            raise ValueError("Missing required macro 'UI'")
            
        if ui_type not in self.UI_FILES:
            raise ValueError(f"Unknown UI type: {ui_type}")
            
        file_path = self.UI_FILES[ui_type]
        
        # Handle Console Expert (launches subprocess)
        if ui_type == 'Console Expert':
            ioc = self.macros.get('IOC')
            if not ioc:
                raise ValueError("Missing required macro 'IOC' for Console Expert")
                
            script_path = os.path.expandvars(file_path)
            subprocess.Popen(['python', script_path, '--ioc', ioc])
            raise ValueError("Console launched in separate process")
            
        # Handle nested UI options
        if isinstance(file_path, dict):
            controller = self.macros.get('Controller')
            if not controller:
                raise ValueError(f"Missing required macro 'Controller' for {ui_type}")
                
            # Special case for Homing Expert
            if ui_type == 'Homing Expert' and self.macros.get('Home') == 'None':
                raise ValueError("Homing not applicable for this controller")
                
            file_path = file_path.get(controller)
            if not file_path:
                raise ValueError(f"Unknown Controller type: {controller}")
        
        # Expand environment variables in path
        return os.path.expandvars(file_path)
        
    def ui_filename(self):
        return self.ui_path
        
    def ui_filepath(self):
        return self.ui_path

def main():
    app = QApplication(sys.argv)
    
    try:
        display = MyDisplay()
        display.show()
        sys.exit(app.exec_())
    except ValueError as e:
        print(f"Configuration error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == '__main__':
    main()
