package org.asciidoc.intellij.namesValidator;

import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.rename.RenameInputValidator;
import com.intellij.util.ProcessingContext;
import org.asciidoc.intellij.psi.AsciiDocAttributeDeclarationName;
import org.asciidoc.intellij.psi.AsciiDocBlockId;
import org.asciidoc.intellij.psi.AsciiDocIncludeTagInDocument;
import org.asciidoc.intellij.psi.AsciiDocTagDeclaration;
import org.jetbrains.annotations.NotNull;

import java.util.regex.Pattern;

public class AsciiDocRenameInputValidator implements RenameInputValidator {
  private final ElementPattern<? extends PsiElement> myPattern = PlatformPatterns.or(
    PlatformPatterns.psiElement(AsciiDocIncludeTagInDocument.class),
    PlatformPatterns.psiElement(AsciiDocTagDeclaration.class),
    PlatformPatterns.psiElement(AsciiDocBlockId.class),
    PlatformPatterns.psiElement(AsciiDocAttributeDeclarationName.class)
  );
  private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("[a-zA-Z0-9_-]*");
  // source: BlockAnchorRx in Asciidoctor's rx.rb
  public static final Pattern BLOCK_ID_PATTERN = Pattern.compile("[\\p{Alpha}_:][\\w\\-:.]*");

  @NotNull
  @Override
  public ElementPattern<? extends PsiElement> getPattern() {
    return myPattern;
  }

  @Override
  public boolean isInputValid(@NotNull String newName, @NotNull PsiElement element, @NotNull ProcessingContext context) {
    if (element instanceof AsciiDocBlockId) {
      return BLOCK_ID_PATTERN.matcher(newName).matches();
    } else {
      return IDENTIFIER_PATTERN.matcher(newName).matches();
    }
  }
}

@@ -1087,17 +1087,18 @@
 e(%22%5B
-a-zA-Z0-9
+%5C%5Cp%7BAlnum%7D
 _-%5D*
@@ -1234,16 +1234,26 @@
 a%7D_:%5D%5B%5C%5C
+p%7BAlnum%7D%5C%5C
 w%5C%5C-:.%5D*

allow unicode characters and numbers in block IDs (#436)