package jetbrains.mps.nodeEditor.cells.jetpad;

/*Generated by MPS */

import jetbrains.jetpad.model.property.ValueProperty;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.smodel.ModelAccessHelper;
import jetbrains.mps.smodel.NodeReadAccessCasterInEditor;

public abstract class ReadableModelProperty<T> extends ValueProperty<T> {
  protected final EditorContext myEditorContext;

  public ReadableModelProperty(EditorContext editorContext) {
    assert editorContext != null;
    myEditorContext = editorContext;
  }

  /**
   * This method should be called right after creation of this class in order to complete initialization process.
   * 
   * @return this
   */
  public ReadableModelProperty init() {
    synchronizeViewWithModel();
    return this;
  }

  private T safeGetModelPropertyValue() {
    return new ModelAccessHelper(myEditorContext.getRepository()).runReadAction(() -> NodeReadAccessCasterInEditor.runCleanPropertyAccessAction(() -> getModelPropertyValue()));
  }

  protected abstract T getModelPropertyValue();

  public void synchronizeViewWithModel() {
    set(safeGetModelPropertyValue());
  }
}
