package lan.dk.podcastserver.service;

import javaslang.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

/**
 * Created by kevin on 25/01/2016 for Podcast Server
 */
@Slf4j
@Service
public class ProcessService {

    public ProcessBuilder newProcessBuilder(String... command) { return new ProcessBuilder(command); }

    public Try<Process> start(ProcessBuilder processBuilder) {
        return Try.of(processBuilder::start);
    }

    public int pidOf(Process p) {
        try {
            if (p.getClass().getSimpleName().contains("UNIXProcess")) {
                Field pidField = p.getClass().getDeclaredField("pid");
                pidField.setAccessible(true);
                return pidField.getInt(p);
            }
        } catch (IllegalAccessException | NoSuchFieldException ignored) {}
        return -1;
    }

    public Try<Integer> waitFor(Process process) {
        return Try.of(process::waitFor);
    }
}

@@ -148,41 +148,8 @@
 e;%0A%0A
-import java.lang.reflect.Field;%0A%0A
 /**%0A
@@ -518,30 +518,28 @@
     
-try %7B%0A            if (
+return Try.of(() -%3E 
 p.ge
@@ -562,16 +562,60 @@
 leName()
+)%0A            .filter(className -%3E className
 .contain
@@ -631,18 +631,16 @@
 ocess%22))
- %7B
 %0A       
@@ -648,28 +648,28 @@
     
-    Field pidField =
+.mapTry(className -%3E
  p.g
@@ -701,17 +701,17 @@
 d(%22pid%22)
-;
+)
 %0A       
@@ -719,20 +719,26 @@
     
-    pidField
+.andThenTry(c -%3E c
 .set
@@ -753,17 +753,17 @@
 le(true)
-;
+)
 %0A       
@@ -771,27 +771,22 @@
     
-    return pidField
+.mapTry(c -%3E c
 .get
@@ -791,17 +791,17 @@
 etInt(p)
-;
+)
 %0A       
@@ -809,102 +809,22 @@
     
-%7D%0A        %7D catch (IllegalAccessException %7C NoSuchFieldException ignored) %7B%7D%0A        return 
+.getOrElse(
 -1
+)
 ;%0A  

use javaslang monad to treat with process id