/*
 * Copyright 2016 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
package io.flutter.console;

import com.intellij.execution.ConsoleFolding;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Fold lines like
 * '/Users/.../projects/flutter/flutter/bin/flutter --no-color packages get'.
 */
public class FlutterConsoleFolding extends ConsoleFolding {
  private static final String marker = File.separator + "flutter --no-color ";

  private boolean isFolding = false;

  // CoreSimulatorBridge: Requesting launch of ... with options: {
  private static final Pattern iosPattern = Pattern.compile("^\\w+: .* \\{$");

  @Override
  public boolean shouldFoldLine(String line) {
    if (line.contains(marker)) {
      isFolding = false;
      return true;
    }

    if (isFolding && line.startsWith(("\t"))) {
      return true;
    }

    if (iosPattern.matcher(line).matches()) {
      isFolding = true;
      return false;
    }

    isFolding = false;

    return false;
  }

  @Nullable
  @Override
  public String getPlaceholderText(List<String> lines) {
    final String fullText = StringUtil.join(lines, "\n");
    final int index = fullText.indexOf(marker);
    if (index == -1) {
      return " ... }";
    }
    else {
      return "flutter " + fullText.substring(index + marker.length());
    }
  }
}

@@ -841,16 +841,315 @@
 %5C%7B$%22);%0A%0A
+  //     %5Bx86_64%5D libnetcore-856.20.4%0A  // 0   libsystem_network.dylib             0x0000000111918682 __nw_create_backtrace_string + 123%0A  // 1   libnetwork.dylib                    0x0000000111ab2932 nw_socket_add_input_handler + 3100%0A  private static final String iosCrashPrefix = %22%5Ct        %5B%22;%0A%0A
   @Overr
@@ -1296,46 +1296,103 @@
 f (i
-sFolding && line.startsWith((%22%5Ct%22))) %7B
+osPattern.matcher(line).matches() %7C%7C line.startsWith(iosCrashPrefix)) %7B%0A      isFolding = true;
 %0A   
@@ -1393,35 +1393,36 @@
 e;%0A      return 
-tru
+fals
 e;%0A    %7D%0A%0A    if
@@ -1428,96 +1428,85 @@
 f (i
-osPattern.matcher(line).matches()) %7B%0A      isFolding = true;%0A      return false;
+sFolding && line.startsWith((%22%5Ct%22))) %7B%0A      return true;%0A    %7D%0A    else %7B
 %0A  
-  %7D%0A%0A
     
@@ -1524,21 +1524,22 @@
  false;%0A
-%0A
+ 
     
+ 
 return f
@@ -1544,16 +1544,22 @@
  false;%0A
+    %7D%0A
   %7D%0A%0A  @
@@ -1775,24 +1775,139 @@
     
-return %22 ... %7D%22;
+if (lines.stream().anyMatch((s) -%3E s.endsWith(%22%7D%22))) %7B%0A        return %22 ... %7D%22;%0A      %7D%0A      else %7B%0A        return %22 ...%22;%0A      %7D
 %0A   

improve the console folding for iOS (#562)