import { PatchableFileModel, type PatchableFileModelOptions } from './PatchableFileModel.js'

export default class PatchableRawContentModel<T extends object> extends PatchableFileModel<T> {
  constructor(options: PatchableFileModelOptions<T>) {
    super(options)
    this.changeListener = this.changeListener.bind(this)
  }

  protected changeListener(): void {
    this.handleChange()
    this.dispatchEvent(new Event('change'))
  }

  protected setupFile(content: T): void {
    this.raw = content
    const typed = content as EventTarget
    typed.addEventListener('change', this.changeListener)
    this.setupPreviousData(content)
  }

  protected override createRevision(): T {
    return JSON.parse(JSON.stringify(this.value)) as T
  }

  protected override readValue(): T {
    const v = this.value as T
    if (v) {
      return JSON.parse(JSON.stringify(this.value)) as T
    }
    return v
  }

  protected override setValue(content: T): void {
    if (this.value) {
      const typed = this.value as EventTarget
      typed.removeEventListener('change', this.changeListener)
    }
    const typed = content as EventTarget
    typed.addEventListener('change', this.changeListener)
    this.raw = content
    this.changeListener()
  }
}
