package jetbrains.mps.lang.editor.menus.extras.runtime;

/*Generated by MPS */

import jetbrains.mps.openapi.editor.menus.transformation.ActionItemBase;
import jetbrains.mps.openapi.editor.menus.transformation.TransformationMenuContext;
import jetbrains.mps.refactoring.framework.IRefactoring;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import jetbrains.mps.project.MPSProject;
import jetbrains.mps.refactoring.framework.RefactoringContext;
import java.util.Collections;
import jetbrains.mps.refactoring.runtime.access.RefactoringAccess;
import jetbrains.mps.ide.actions.MPSCommonDataKeys;
import com.intellij.ide.DataManager;
import java.awt.Component;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.refactoring.framework.IRefactoringTarget;

public class RefactoringMenuItemBase extends ActionItemBase {
  protected final TransformationMenuContext _context;
  protected final IRefactoring myRefactoring;

  public RefactoringMenuItemBase(TransformationMenuContext context, IRefactoring refactoring) {
    _context = context;
    myRefactoring = refactoring;
  }

  @Nullable
  @Override
  public String getLabelText(@NotNull String pattern) {
    return myRefactoring.getUserFriendlyName();
  }

  @Override
  public boolean canExecute(@NotNull String pattern) {
    return isRefactoringApplicableToNode(myRefactoring, _context.getNode());
  }

  @Override
  public void execute(@NotNull String pattern) {
    MPSProject project = projectFromContext();

    RefactoringContext refactoringContext = RefactoringContext.createRefactoringContext(myRefactoring, Collections.emptyList(), Collections.emptyList(), _context.getNode(), project);
    RefactoringAccess.getInstance(project).getRefactoringFacade().execute(refactoringContext);
  }

  private MPSProject projectFromContext() {
    return MPSCommonDataKeys.MPS_PROJECT.getData(DataManager.getInstance().getDataContext((Component) _context.getEditorContext().getEditorComponent()));
  }

  private boolean isRefactoringApplicableToNode(IRefactoring refactoring, SNode node) {
    IRefactoringTarget refactoringTarget = refactoring.getRefactoringTarget();
    if (refactoringTarget.getTarget() != IRefactoringTarget.TargetType.NODE) {
      return false;
    }

    Object targetEntity = (refactoringTarget.allowMultipleTargets() ? Collections.singletonList(node) : node);
    return RefactoringAccess.getInstance(projectFromContext()).isApplicable(refactoring, targetEntity);
  }
}
