/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.plugins.groovy.lang.surroundWith;

import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrUnaryExpression;

/**
 * @author Max Medvedev
 */
public class NotAndParenthesesSurrounder extends GroovyExpressionSurrounder {
  @Override
  protected TextRange surroundExpression(GrExpression expression, PsiElement context) {
    GrUnaryExpression result = (GrUnaryExpression)GroovyPsiElementFactory.getInstance(expression.getProject()).createExpressionFromText("!(a)", context);
    GroovyExpressionSurrounder.replaceToOldExpression(((GrParenthesizedExpression)result.getOperand()).getOperand(), expression);
    result = (GrUnaryExpression)expression.replaceWithExpression(result, true);
    return new TextRange(result.getTextRange().getEndOffset(), result.getTextRange().getEndOffset());
  }

  @Override
  public String getTemplateDescription() {
    return "!(expr)";
  }
}

@@ -21,9 +21,9 @@
 -201
-3
+5
  Jet
@@ -1188,16 +1188,17 @@
 under %7B%0A
+%0A
   @Overr
@@ -1297,54 +1297,48 @@
     
-GrUnaryExpression result = (GrUnaryExpression)
+final GroovyPsiElementFactory factory = 
 Groo
@@ -1393,16 +1393,83 @@
 oject())
+;%0A    final GrUnaryExpression template = (GrUnaryExpression)factory
 .createE
@@ -1504,16 +1504,58 @@
 ntext);%0A
+    assert template.getOperand() != null;%0A
     Groo
@@ -1628,22 +1628,24 @@
 ression)
-result
+template
 .getOper
@@ -1686,36 +1686,36 @@
     
-result = (GrUnaryExpression)
+final GrExpression result = 
 expr
@@ -1743,22 +1743,24 @@
 ression(
-result
+template
 , true);
@@ -1768,29 +1768,30 @@
     
-return new TextRange(
+final int endOffset = 
 resu
@@ -1826,44 +1826,55 @@
 et()
-, result.getTextRange().getE
+;%0A    return new TextRange(endOffset, e
 ndOffset
 ());
@@ -1869,18 +1869,16 @@
 ndOffset
-()
 );%0A  %7D%0A%0A

remove cast (EA-69981)