package com.phrase.intellij;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.CapturingProcessHandler;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessListener;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.phrase.intellij.ui.ColorTextPane;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kolja on 15.10.15.
 */
public class PushPullAdapter {
    private String clientPath;
    private String projectPath;
    private ToolWindowHelper outputWindowHelper;
    private SimpleDateFormat sdf;

    public PushPullAdapter(final String path, Project project) {
        clientPath = path;
        projectPath = project.getBasePath();
        outputWindowHelper = new ToolWindowHelper(project);
        sdf = new SimpleDateFormat("HH:mm:ss");
    }

    public void run(final String clientAction) {

        if (outputWindowHelper.getOutputWindow().isActive()) {
            final ColorTextPane finalArea = outputWindowHelper.getColorTextPane();
            outputWindowHelper.getOutputWindow().show(new Runnable() {
                @Override
                public void run() {
                    runCommand(clientAction, finalArea);
                }
            });
        } else {
            outputWindowHelper.getOutputWindow().activate(new Runnable() {
                @Override
                public void run() {
                    runCommand(clientAction, outputWindowHelper.getColorTextPane());
                }
            });
        }
    }

    private void runCommand(final String clientAction, final ColorTextPane finalArea) {
        try {
            GeneralCommandLine gcl = new GeneralCommandLine(clientPath,
                    clientAction);
            gcl.withWorkDirectory(projectPath);

            PluginId pluginId = com.intellij.ide.plugins.PluginManager.getPluginByClassName(getClass().getName());

            final CapturingProcessHandler processHandler = new CapturingProcessHandler(gcl.createProcess(), Charset.defaultCharset(), gcl.getCommandLineString());
            processHandler.addProcessListener(new ProcessListener() {
                @Override
                public void startNotified(ProcessEvent event) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            finalArea.setEditable(true);
                            finalArea.appendANSI(getFormattedTime() + "phrase " + clientAction + "\n");
                        }
                    });
                }

                @Override
                public void processTerminated(ProcessEvent event) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            finalArea.setEditable(false);
                        }
                    });
                }

                @Override
                public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {

                }

                @Override
                public void onTextAvailable(final ProcessEvent event, final Key outputType) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            if (event.getText().length() < 5) {
                                finalArea.appendANSI(event.getText());
                                return;
                            }

                            if (outputType.toString() == "stdout") {
                                finalArea.appendANSI(getFormattedTime() + event.getText());
                            } else if (outputType.toString() == "system") {
                                finalArea.append(Color.getHSBColor(0.000f, 0.000f, 0.000f), getFormattedTime() + event.getText());
                            } else {
                                finalArea.append(Color.getHSBColor(0.000f, 1.000f, 0.502f), event.getText());
                            }
                        }
                    });
                }
            });
            Thread queryThread = new Thread() {
                public void run() {
                    processHandler.runProcess();
                }
            };
            queryThread.start();

        } catch (ExecutionException exception) {
            Notifications.Bus.notify(new Notification("Phrase", "Error", exception.getMessage(), NotificationType.ERROR));
        }
    }

    @NotNull
    private String getFormattedTime() {
        return sdf.format(new Date()) + " ";
    }
}

@@ -312,62 +312,8 @@
 er;%0A
-import com.intellij.ide.plugins.IdeaPluginDescriptor;%0A
 impo
@@ -518,57 +518,8 @@
 er;%0A
-import com.intellij.openapi.extensions.PluginId;%0A
 impo
@@ -2299,108 +2299,143 @@
     
-PluginId pluginId = com.intellij.ide.plugins.PluginManager.getPluginByClassName(getClass().getName()
+Map env = new HashMap%3CString, String%3E();%0A            env.put(%22PHRASE_USER_AGENT%22, %22AndroidStudio%22);%0A            gcl.withEnvironment(env
 );%0A%0A

Add Android Studio user agent