package jetbrains.mps.ide.migration;

/*Generated by MPS */

import jetbrains.mps.annotations.GeneratedClass;
import jetbrains.mps.lang.migration.runtime.base.BaseScriptReference;
import org.jetbrains.mps.openapi.module.SModuleReference;
import jetbrains.mps.lang.migration.runtime.base.BaseScript;
import org.jetbrains.mps.openapi.module.SModule;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.module.SRepository;
import org.jetbrains.annotations.Nullable;

@GeneratedClass(node = "a5b1c28d-abeb-49a6-a58c-559039616d64/r:a9597bdf-0806-4a79-8ace-88240c6b9878(jetbrains.mps.migration.component/jetbrains.mps.ide.migration)/7201972523303742950", model = "a5b1c28d-abeb-49a6-a58c-559039616d64/r:a9597bdf-0806-4a79-8ace-88240c6b9878(jetbrains.mps.migration.component/jetbrains.mps.ide.migration)")
public class ScriptApplied<T extends BaseScriptReference> {
  private final SModuleReference myModule;
  private final T myScriptRef;
  private BaseScript myScript;

  public ScriptApplied(SModule module, T scriptRef) {
    myModule = module.getModuleReference();
    myScriptRef = scriptRef;
    myScript = null;
  }

  /**
   * Use when there's valid (existing) script code
   */
  public ScriptApplied(@NotNull SModule module, @NotNull BaseScript scriptInstance) {
    myModule = module.getModuleReference();
    myScriptRef = (T) scriptInstance.getReference();
    myScript = scriptInstance;
  }

  public SModuleReference getModuleReference() {
    return myModule;
  }

  @NotNull
  public SModule getModule(SRepository toResolve) {
    SModule result = myModule.resolve(toResolve);
    if (result == null) {
      throw new IllegalStateException("Module " + myModule + " cannot be resolved in repository.");
    }
    return result;
  }

  public T getScriptReference() {
    return myScriptRef;
  }

  @Nullable
  public BaseScript getScriptInstance() {
    return myScript;
  }

  /**
   * internal implementation facility to deal with reloading of original classloaders
   */
  /*package*/ void updateScriptInstance(BaseScript script) {
    myScript = script;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || this.getClass() != o.getClass()) {
      return false;
    }

    ScriptApplied that = (ScriptApplied) o;
    if (!(myModule.equals(that.myModule))) {
      return false;
    }
    if (!(myScriptRef.equals(that.myScriptRef))) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 31 * myModule.hashCode() + myScriptRef.hashCode();
  }

  @Override
  public String toString() {
    return myScriptRef + " to module " + myModule.getModuleName();
  }
}
