package jetbrains.mps.kotlin.stubs.jvmStubs;

/*Generated by MPS */

import jetbrains.mps.annotations.GeneratedClass;
import jetbrains.mps.kotlin.stubs.common.metadata.VisitorContext;
import jetbrains.mps.vfs.IFile;
import jetbrains.mps.kotlin.stubs.common.references.KotlinJvmReferenceSolver;
import org.jetbrains.mps.openapi.model.SNode;
import java.util.List;
import jetbrains.mps.kotlin.stubs.common.references.StereotypeReference;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import java.util.ArrayList;
import kotlinx.metadata.jvm.KotlinClassHeader;
import kotlinx.metadata.jvm.KotlinClassMetadata;
import jetbrains.mps.kotlin.stubs.common.metadata.KtClassParser;

@GeneratedClass(node = "r:bdaa2532-d0d0-46ce-8145-d47be9b807a4(jetbrains.mps.kotlin.stubs.jvmStubs)/8963686186946753488", model = "r:bdaa2532-d0d0-46ce-8145-d47be9b807a4(jetbrains.mps.kotlin.stubs.jvmStubs)")
public class JvmVisitorContext extends VisitorContext {
  private final IFile myFile;
  public JvmVisitorContext(KotlinJvmReferenceSolver factory, String moduleName, SNode enclosing, IFile file) {
    super(factory, moduleName, enclosing);
    myFile = file;
  }

  @Override
  protected List<StereotypeReference.ClassStereotype> fqNameToNodeIds(String fqName) {
    // Kotlin classes + java ones
    return ListSequence.fromListAndArray(new ArrayList<StereotypeReference.ClassStereotype>(), new StereotypeReference.KotlinClassReference(fqName), new StereotypeReference.JavaClassReference(fqName));
  }
  @Override
  public SNode getClass(String key) {
    SNode parentClass = super.getClass(key);

    if ((parentClass == null)) {
      // Read class from file
      String fileName = myFile.getName();
      IFile child = myFile.getParent().findChild(fileName.substring(0, fileName.indexOf(".")) + "$" + key + ".class");
      if (child.exists()) {
        KotlinAwareClassifierLoader loader = new KotlinAwareClassifierLoader(child, true, true);
        KotlinClassHeader kotlinData = KotlinMetadataLazyExtractor.getKotlinData(loader, getPackageName().replace("/", "."));
        VisitorContext context = new JvmVisitorContext(getReferenceFactory(), getPackageName(), null, child);

        if (kotlinData != null) {
          KotlinClassMetadata metadata = KotlinClassMetadata.read(kotlinData);

          // Only handle classes
          if (metadata instanceof KotlinClassMetadata.Class) {
            // Class file
            SNode res = KtClassParser.parseClass(((KotlinClassMetadata.Class) metadata).toKmClass(), context, true);
            if (res != null) {
              this.addClass(res);
              return res;
            }
          }
        }

        // Nothing to load?
        // Cannot be a java class, can it?
      }
    }

    return parentClass;
  }
}
