/*
 * Copyright (c) 2017. tangzx(love.tangzx@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tang.intellij.lua.debugger.app;

import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessListener;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.xdebugger.XDebugSession;
import com.tang.intellij.lua.debugger.remote.LuaMobDebugProcess;
import com.tang.intellij.lua.psi.LuaFileUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;

class LuaAppMobProcess extends LuaMobDebugProcess {
    private final LuaAppRunConfiguration configuration;
    private Process process;
    private boolean isStoped;

    LuaAppMobProcess(@NotNull XDebugSession session) {
        super(session);
        configuration = (LuaAppRunConfiguration) session.getRunProfile();
    }

    @Override
    public void sessionInitialized() {
        super.sessionInitialized();
        StringBuilder setupPackagePath = new StringBuilder(String.format("%s/?.lua;", LuaFileUtil.getPluginVirtualFile("debugger/mobdebug")));

        Module[] modules = ModuleManager.getInstance(getSession().getProject()).getModules();
        for (Module module : modules) {
            VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots();
            for (VirtualFile sourceRoot : sourceRoots) {
                String path = sourceRoot.getCanonicalPath();
                if (path != null) {
                    setupPackagePath.append(path).append("/?.lua;");
                }
            }
        }

        ProcessBuilder builder = new ProcessBuilder(configuration.getProgram(),
                "-e",
                String.format("package.path = package.path .. ';%s' require('mobdebug').start()", setupPackagePath.toString()),
                configuration.getFile());
        String dir = configuration.getWorkingDir();
        if (dir != null && !dir.isEmpty())
            builder.directory(new File(dir));

        try {
            process = builder.start();
            OSProcessHandler handler = new OSProcessHandler(process, null);
            handler.addProcessListener(new ProcessListener() {
                @Override
                public void startNotified(ProcessEvent processEvent) {

                }

                @Override
                public void processTerminated(ProcessEvent processEvent) {
                    if (!isStoped)
                        getSession().stop();
                }

                @Override
                public void processWillTerminate(ProcessEvent processEvent, boolean b) {

                }

                @Override
                public void onTextAvailable(ProcessEvent processEvent, Key key) {
                    print(processEvent.getText());
                }
            });
            handler.startNotify();
        } catch (Exception e) {
            getSession().getConsoleView().print(e.getMessage(), ConsoleViewContentType.ERROR_OUTPUT);
            getSession().stop();
        }
    }

    @Override
    public void stop() {
        isStoped = true;
        super.stop();
        if (process != null) {
            process.destroy();
            process = null;
        }
    }
}

@@ -650,16 +650,81 @@
 r.app;%0A%0A
+import com.intellij.execution.configurations.GeneralCommandLine;%0A
 import c
@@ -1367,30 +1367,8 @@
 l;%0A%0A
-import java.io.File;%0A%0A
 clas
@@ -1475,37 +1475,8 @@
 on;%0A
-    private Process process;%0A
     
@@ -1497,16 +1497,17 @@
 n isStop
+p
 ed;%0A%0A   
@@ -2404,51 +2404,63 @@
     
-ProcessBuilder builder = new ProcessBuilder
+GeneralCommandLine commandLine = new GeneralCommandLine
 (con
@@ -2482,17 +2482,18 @@
 rogram()
-,
+);
 %0A       
@@ -2497,37 +2497,39 @@
     
-        %22-e%22,%0A               
+commandLine.addParameters(%22-e%22,
  Str
@@ -2635,17 +2635,18 @@
 tring())
-,
+);
 %0A       
@@ -2646,24 +2646,42 @@
         
-        
+commandLine.addParameters(
 configur
@@ -2694,24 +2694,25 @@
 getFile());%0A
+%0A
         Stri
@@ -2810,40 +2810,41 @@
     
-builder.directory(new File
+commandLine.setWorkDirectory
 (dir)
-)
 ;%0A%0A 
@@ -2860,47 +2860,8 @@
 y %7B%0A
-            process = builder.start();%0A
     
@@ -2920,21 +2920,19 @@
 ler(
-process, null
+commandLine
 );%0A 
@@ -3242,16 +3242,17 @@
 (!isStop
+p
 ed)%0A    
@@ -3911,16 +3911,17 @@
   isStop
+p
 ed = tru
@@ -3949,108 +3949,8 @@
 ();%0A
-        if (process != null) %7B%0A            process.destroy();%0A            process = null;%0A        %7D%0A
     

use GeneralCommandLine