package de.espend.idea.php.annotation.completion.insert;

import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiUtilCore;
import com.jetbrains.php.completion.insert.PhpInsertHandlerUtil;
import com.jetbrains.php.completion.insert.PhpReferenceInsertHandler;
import org.jetbrains.annotations.NotNull;

public class AnnotationTagInsertHandler implements InsertHandler<LookupElement> {

    private static final AnnotationTagInsertHandler instance = new AnnotationTagInsertHandler();

    public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {

        // reuse jetbrains us importer: this is private only so we need some workaround
        // to not implement your own algo for that
        PhpReferenceInsertHandler.getInstance().handleInsert(context, lookupElement);
        PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), "()");
        context.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, true);

        // "@" is not provide by lookup element because its remove by auto import so attach it if necessary
        PsiElement element = PsiUtilCore.getElementAtOffset(context.getFile(), context.getStartOffset());
        if(!element.getText().startsWith("@")) {
            StringBuilder textToInsertBuilder = new StringBuilder();
            textToInsertBuilder.append("@");
            context.getDocument().insertString(context.getStartOffset(), textToInsertBuilder);
        }
    }

    public static AnnotationTagInsertHandler getInstance(){
        return instance;
    }

}
@@ -991,16 +991,98 @@
 ement);%0A
+        if(!PhpInsertHandlerUtil.isStringAtCaret(context.getEditor(), %22(%22)) %7B%0A    
         
@@ -1146,24 +1146,28 @@
 r(), %22()%22);%0A
+    
         cont
@@ -1245,16 +1245,26 @@
 , true);
+%0A        %7D
 %0A%0A      

optimize insert handler for doc tag