import { LiveData } from '../reactive/LiveData.js'
import { PatchableFileModel } from './PatchableFileModel.js'

export default class PatchableLiveDataContentModel<T extends object> extends PatchableFileModel<T> {
  protected setupFile(content: T): void {
    this.raw = new LiveData(content) as T
    this.setupPreviousData(content)
  }

  protected override createRevision(): T {
    const v = this.value as LiveData<T>
    if (!v) {
      throw new Error('LiveData value is not set.')
    }
    return JSON.parse(JSON.stringify(v.value)) as T
  }

  protected override readValue(): T {
    const v = this.value as LiveData<T>
    if (!v) {
      throw new Error('LiveData value is not set.')
    }
    return v.value as T
  }

  protected override setValue(value: T): void {
    const v = this.value as LiveData<T>
    if (v) {
      v.set(value)
    } else {
      this.raw = new LiveData(value) as T
    }
  }
}
