/*
 * Copyright 2003-2018 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 jetbrains.mps.smodel.adapter.structure;

import jetbrains.mps.RuntimeFlags;
import jetbrains.mps.smodel.runtime.NamedElementDescriptor;
import jetbrains.mps.util.NameUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.language.SNamedElement;
import org.jetbrains.mps.openapi.model.SNodeReference;

/**
 * @author Radimir.Sorokin
 * @since 2018.3
 */
public abstract class SNamedElementAdapter implements SNamedElement {

  protected final String myFqName;

  public SNamedElementAdapter(String fqName) {
    myFqName = fqName;
  }

  @Nullable
  protected abstract NamedElementDescriptor getDescriptor();

  protected boolean isBootstrap() {
    return false;
  }

  @Nullable
  @Override
  public final SNodeReference getSourceNode() {
    NamedElementDescriptor d = getDescriptor();
    if (d == null) {
      return null;
    }
    return d.getSourceNode();
  }

  @NotNull
  @Override
  public String getName() {
    if (RuntimeFlags.isMergeDriverMode() || isBootstrap()) {
      return getDebugName();
    }
    final NamedElementDescriptor descriptor = getDescriptor();
    if (descriptor == null) {
      return getDebugName();
    }
    return descriptor.getName();
  }

  @NotNull
  private String getDebugName() {
    return NameUtil.shortNameFromLongName(myFqName);
  }
}
