package com.karateca.jstoolbox.generatemethod;

import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;

public class ClassFinder {

  protected final Document document;
  private final String documentText;

  public ClassFinder(Document document) {
    this.document = document;
    documentText = document.getText();
  }

  public String getClassName() {
    // Find the @constructor and then go to the first function.
    int constructorOffset = documentText.indexOf("@constructor");
    if (constructorOffset < 0) {
      return null;
    }

    // Find the closing jsdoc.
    int closingJsDocOffset = documentText.indexOf("*/", constructorOffset);
    if (closingJsDocOffset < 0) {
      return null;
    }

    closingJsDocOffset += 2;

    // Get the string until the first "=".
    int indexOfEqual = documentText.indexOf("=", closingJsDocOffset);
    if (indexOfEqual < 0) {
      return null;
    }

    // And remove empty spaces.
    return documentText.substring(closingJsDocOffset, indexOfEqual)
        .replaceAll("\\s+", "");
  }

  public String getParentClassName() {
    // Find @extends.
    int extendsOffset = documentText.indexOf("@extends");
    if (extendsOffset < 0) {
      return null;
    }

    // Find the next "*".
    int lineNumber = document.getLineNumber(extendsOffset);
    String line = document.getText(getTextRange(lineNumber));

    // Remove the beginning of the line.
    line = line.replaceAll("[\\s\\*]*@extends\\s*\\{?", "");

    // Remove the end of the line.
    line = line.replaceAll("\\}?\\s*$", "");

    return line;
  }

  private TextRange getTextRange(int lineNumber) {
    int lineStart = document.getLineStartOffset(lineNumber);
    int lineEnd = document.getLineEndOffset(lineNumber);

    return new TextRange(lineStart, lineEnd);
  }
}

@@ -131,16 +131,132 @@
 Range;%0A%0A
+import java.util.ArrayList;%0Aimport java.util.List;%0Aimport java.util.regex.Matcher;%0Aimport java.util.regex.Pattern;%0A%0A
 public c
@@ -1938,11 +1938,631 @@
 nd);%0A  %7D
+%0A%0A  public List%3CFunction%3E getMethods() %7B%0A    List%3CFunction%3E result = new ArrayList%3CFunction%3E();%0A%0A    String className = getClassName();%0A%0A    String regexp = %22(%25s.prototype.)(%5B%5C%5Cw%5D+)(%5C%5Cs*=%5C%5Cs*function%5C%5Cs*%5C%5C()%22 +%0A        %22(%5B%5C%5Cw%5C%5Cs%5C%5Cn,%5D*)(%5C%5C))%22;%0A    String methodPattern = String.format(regexp, className);%0A%0A    Pattern pattern = Pattern.compile(methodPattern, Pattern.MULTILINE);%0A    Matcher matcher = pattern.matcher(documentText);%0A%0A    while (matcher.find()) %7B%0A      String name = matcher.group(2);%0A      String arguments = matcher.group(4);%0A      result.add(new Function(name, arguments));%0A    %7D%0A%0A    return result;%0A  %7D
 %0A%7D%0A

add getMethods