package edu.hm.hafner.analysis;

import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

import static edu.hm.hafner.analysis.PackageDetectors.*;

/**
 * Detects the namespace of a C# workspace file.
 *
 * @author Ullrich Hafner
 */
class CSharpNamespaceDetector extends AbstractPackageDetector {
    private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^namespace .*$");

    CSharpNamespaceDetector() {
        this(new FileSystem());
    }

    CSharpNamespaceDetector(final FileSystem fileSystem) {
        super(fileSystem);
    }

    @Override
    public boolean accepts(final String fileName) {
        return fileName.endsWith(".cs");
    }

    @Override
    public String detectPackageName(final Stream<String> lines) {
        Optional<String> namespace = lines.filter(NAMESPACE_PATTERN.asPredicate()).findFirst();
        if (namespace.isPresent()) {
            String line = namespace.get();
            if (line.contains("{")) {
                return StringUtils.substringBetween(line, " ", "{").trim();
            }
            else {
                return StringUtils.substringAfter(line, " ").trim();
            }
        }
        return UNDEFINED_PACKAGE;
    }
}


@@ -43,24 +43,29 @@
 va.util.
-Optional
+regex.Matcher
 ;%0Aimport
@@ -127,54 +127,8 @@
 m;%0A%0A
-import org.apache.commons.lang3.StringUtils;%0A%0A
 impo
@@ -402,16 +402,20 @@
 mpile(%22%5E
+%5C%5Cs*
 namespac
@@ -419,10 +419,30 @@
 pace
- .
+%5C%5Cs+(%5B%5E%7B%5D*)%5C%5Cs*%5C%5C%7B?%5C%5Cs
 *$%22)
@@ -814,49 +814,24 @@
     
-Optional%3CString%3E namespace =
+return
  lines.
-filter
+map
 (NAM
@@ -848,230 +848,89 @@
 TERN
-.asPredicate()).findFirst();%0A        if (namespace.isPresent()) %7B%0A            String line = namespace.get();%0A            if (line.contains(%22%7B%22)) %7B%0A                return StringUtils.substringBetween(line, %22 %22, %22%7B%22).trim();
+::matcher)%0A                .filter(Matcher::matches)%0A                .findFirst()
 %0A   
@@ -942,137 +942,70 @@
     
-%7D%0A
     
-        else %7B%0A                return StringUtils.substringAfter(line, %22 %22).trim();%0A            %7D%0A        %7D%0A        return 
+.map(matcher -%3E matcher.group(1))%0A                .orElse(
 UNDE
@@ -1017,16 +1017,24 @@
 _PACKAGE
+).trim()
 ;%0A    %7D%0A

Use regexp with matcher to identify a namespace.