package org.yamcs.studio.ui.handlers;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import org.yamcs.protobuf.Rest.RestExceptionMessage;
import org.yamcs.protobuf.YamcsManagement.ProcessorInfo;
import org.yamcs.protobuf.YamcsManagement.ProcessorManagementRequest;
import org.yamcs.protobuf.YamcsManagement.ProcessorManagementRequest.Operation;
import org.yamcs.studio.core.YamcsPlugin;
import org.yamcs.studio.core.web.ResponseHandler;
import org.yamcs.studio.ui.processor.SwitchProcessorDialog;

import com.google.protobuf.MessageLite;

public class SwitchProcessorHandler extends AbstractRestHandler {

    private static final Logger log = Logger.getLogger(SwitchProcessorHandler.class.getName());

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        if (!checkRestClient(event, "switch processor"))
            return null;

        Shell shell = HandlerUtil.getActiveShellChecked(event);
        SwitchProcessorDialog dialog = new SwitchProcessorDialog(shell);
        if (dialog.open() == Window.OK) {
            ProcessorInfo info = dialog.getProcessorInfo();
            if (info != null) {
                ProcessorManagementRequest req = ProcessorManagementRequest.newBuilder()
                        .setOperation(Operation.CONNECT_TO_PROCESSOR)
                        .setInstance(info.getInstance())
                        .setName(info.getName())
                        .addClientId(YamcsPlugin.getDefault().getClientInfo().getId()).build();
                restClient.createProcessorManagementRequest(req, new ResponseHandler() {
                    @Override
                    public void onMessage(MessageLite responseMsg) {
                        if (responseMsg instanceof RestExceptionMessage) {
                            log.log(Level.SEVERE, "Could not switch processor. " + responseMsg);
                        } else {
                            // Would prefer to get updates to this from the web socket client
                            Display.getCurrent().asyncExec(() -> {
                                YamcsPlugin.getDefault().refreshClientInfo();
                            });
                        }
                    }

                    @Override
                    public void onException(Exception e) {
                        log.log(Level.SEVERE, "Could not switch processor", e);
                    }
                });
            }
        }

        return null;
    }
}

@@ -98,16 +98,170 @@
 ogger;%0A%0A
+import org.csstudio.opibuilder.runmode.IOPIRuntime;%0Aimport org.csstudio.opibuilder.runmode.OPIView;%0Aimport org.csstudio.opibuilder.util.ErrorHandlerUtil;%0A
 import o
@@ -472,16 +472,349 @@
 .Shell;%0A
+import org.eclipse.ui.IEditorPart;%0Aimport org.eclipse.ui.IEditorReference;%0Aimport org.eclipse.ui.IViewPart;%0Aimport org.eclipse.ui.IViewReference;%0Aimport org.eclipse.ui.IWorkbench;%0Aimport org.eclipse.ui.IWorkbenchPage;%0Aimport org.eclipse.ui.IWorkbenchWindow;%0Aimport org.eclipse.ui.PartInitException;%0Aimport org.eclipse.ui.PlatformUI;%0A
 import o
@@ -1907,24 +1907,58 @@
  != null) %7B%0A
+                resetDisplays();%0A%0A
             
@@ -2836,14 +2836,14 @@
 .get
-Curren
+Defaul
 t().
@@ -3281,11 +3281,1145 @@
 l;%0A    %7D
+%0A%0A    private void resetDisplays() %7B%0A        IWorkbench workbench = PlatformUI.getWorkbench();%0A        for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) %7B%0A            for (IWorkbenchPage page : window.getPages()) %7B%0A                for (IViewReference reference : page.getViewReferences()) %7B%0A                    IViewPart viewPart = reference.getView(false);%0A                    if (viewPart instanceof IOPIRuntime)%0A                        refreshDisplay((IOPIRuntime) viewPart);%0A                %7D%0A                for (IEditorReference reference : page.getEditorReferences()) %7B%0A                    IEditorPart editorPart = reference.getEditor(false);%0A                    if (editorPart instanceof IOPIRuntime)%0A                        refreshDisplay((IOPIRuntime) editorPart);%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A    private void refreshDisplay(IOPIRuntime opiRuntime) %7B%0A        try %7B%0A            OPIView.ignoreMemento();%0A            opiRuntime.setOPIInput(opiRuntime.getOPIInput());%0A        %7D catch (PartInitException e) %7B%0A            ErrorHandlerUtil.handleError(%22Failed to refresh OPI%22, e);%0A        %7D%0A    %7D
 %0A%7D%0A

Fix NPE and reset displays before switching processors